@astratra/web-search 1.1.0 → 1.2.1

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,426 @@
1
+ /**
2
+ * Les fichiers de déploiement du service `astratra-web-browser` : fonctions
3
+ * pures, rien n'est écrit ni lancé ici.
4
+ *
5
+ * - `createBrowserSystemdUnit` : l'unité systemd durcie (utilisateur à part,
6
+ * mémoire et processeur bornés, système en lecture seule, jeton et clé par
7
+ * `LoadCredential`) ; seuls les espaces de noms dont le cloisonnement de
8
+ * Chromium a besoin (user, pid, net) sont permis ;
9
+ * - `createBrowserPm2App` : une entrée pm2, sans les protections de systemd ;
10
+ * - `createBrowserFirewall` : les règles nftables qui interdisent à
11
+ * l'utilisateur du service toute sortie vers une adresse non publique, sauf
12
+ * le résolveur DNS et le relais de sortie du service ;
13
+ * - `createBrowserFirewallUnit` : l'unité qui charge ces règles au démarrage ;
14
+ * - `createBrowserAppArmorProfile` : le profil qui permet au binaire de
15
+ * Chromium de créer son espace de noms (Ubuntu 23.10 et suivants) ;
16
+ * - `browserSetupFiles` : tout cela d'un coup, avec la marche à suivre
17
+ * (INSTALL.md en anglais, INSTALL.fr.md en français).
18
+ *
19
+ * Le jeton et la clé de signature ne sont jamais écrits dans un fichier
20
+ * généré (ces fichiers finissent dans git) : on passe leur CHEMIN.
21
+ */
22
+
23
+ const path = require('path');
24
+ const { BLOCKED_IPV4, BLOCKED_IPV6 } = require('../address');
25
+
26
+ const SCRIPT = path.resolve(__dirname, 'cli.js');
27
+ const SECRET_ENV = /^WEB_BROWSER_TOKEN$|^WEB_BROWSER_SIGNING_KEY$/;
28
+ const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;
29
+ const NAME = /^[a-z_][a-z0-9_-]*$/;
30
+
31
+ function fail(message) {
32
+ throw new TypeError(message);
33
+ }
34
+
35
+ function safeValue(value, name) {
36
+ const text = String(value);
37
+ // eslint-disable-next-line no-control-regex -- une fin de ligne écrirait d'autres directives
38
+ if (/[\u0000-\u001f\u007f]/.test(text)) fail(`${name}: control characters are not allowed.`);
39
+ return text;
40
+ }
41
+
42
+ function absolute(value, name) {
43
+ if (typeof value !== 'string' || !path.isAbsolute(value)) fail(`${name}: absolute path expected.`);
44
+ return safeValue(value, name);
45
+ }
46
+
47
+ function portOf(value, name) {
48
+ if (!Number.isInteger(value) || value < 1 || value > 65535) fail(`${name}: 1 to 65535.`);
49
+ return value;
50
+ }
51
+
52
+ function httpsUrl(value, name) {
53
+ let url;
54
+ try {
55
+ url = new URL(String(value));
56
+ } catch (_error) {
57
+ url = null;
58
+ }
59
+ if (!url || url.protocol !== 'https:') fail(`${name}: an https address.`);
60
+ return safeValue(url.href, name);
61
+ }
62
+
63
+ /** L'environnement WEB_BROWSER_* du service. */
64
+ function browserServiceEnv(options = {}) {
65
+ const env = {};
66
+ if (options.port !== undefined) env.WEB_BROWSER_PORT = String(portOf(options.port, 'port'));
67
+ if (options.proxyPort !== undefined) env.WEB_BROWSER_PROXY_PORT = String(portOf(options.proxyPort, 'proxyPort'));
68
+ if (options.maxContexts !== undefined) {
69
+ if (!Number.isInteger(options.maxContexts) || options.maxContexts < 1 || options.maxContexts > 16) fail('maxContexts: 1 to 16.');
70
+ env.WEB_BROWSER_MAX_CONTEXTS = String(options.maxContexts);
71
+ }
72
+ if (options.queueMs !== undefined) {
73
+ if (!Number.isInteger(options.queueMs) || options.queueMs < 0) fail('queueMs: non-negative integer.');
74
+ env.WEB_BROWSER_QUEUE_MS = String(options.queueMs);
75
+ }
76
+ if (options.infoUrl !== undefined) env.WEB_BROWSER_INFO_URL = httpsUrl(options.infoUrl, 'infoUrl');
77
+ if (options.signatureAgent !== undefined) env.WEB_BROWSER_SIGNATURE_AGENT = httpsUrl(options.signatureAgent, 'signatureAgent');
78
+ if (options.browsersPath !== undefined) env.PLAYWRIGHT_BROWSERS_PATH = absolute(options.browsersPath, 'browsersPath');
79
+ if (options.tokenFile !== undefined) env.WEB_BROWSER_TOKEN_FILE = absolute(options.tokenFile, 'tokenFile');
80
+ if (options.signingKeyFile !== undefined) env.WEB_BROWSER_SIGNING_KEY_FILE = absolute(options.signingKeyFile, 'signingKeyFile');
81
+ for (const [name, value] of Object.entries(options.env || {})) {
82
+ if (!ENV_NAME.test(name)) fail(`env.${name}: invalid variable name.`);
83
+ if (SECRET_ENV.test(name)) fail(`env.${name}: pass a file path (tokenFile, signingKeyFile) — generated files end up in git.`);
84
+ if (name === 'WEB_BROWSER_UNSAFE_NO_FIREWALL') fail('env.WEB_BROWSER_UNSAFE_NO_FIREWALL: never in a deployment.');
85
+ env[name] = safeValue(value, `env.${name}`);
86
+ }
87
+ return env;
88
+ }
89
+
90
+ function quoteArg(value) {
91
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) return value.replace(/%/g, '%%');
92
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
93
+ }
94
+
95
+ function quoteEnv(name, value) {
96
+ return `"${name}=${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
97
+ }
98
+
99
+ /**
100
+ * L'unité systemd du service.
101
+ * @param {object} options
102
+ * @param {string} options.node le binaire node (chemin absolu).
103
+ * @param {string} options.user l'utilisateur système du service (ex. navigateur).
104
+ * @param {string} options.tokenFile le fichier du jeton (lu par LoadCredential).
105
+ * @param {string} [options.script] Défaut : la commande du paquet.
106
+ * @param {string} [options.signingKeyFile] la clé Web Bot Auth (LoadCredential), avec signatureAgent.
107
+ * @param {string} [options.memoryMax] Défaut "2G".
108
+ * @param {string} [options.memoryHigh]
109
+ * @param {string} [options.cpuQuota] Défaut "200%".
110
+ * @param {number} [options.tasksMax] Défaut 512.
111
+ */
112
+ function createBrowserSystemdUnit(options = {}) {
113
+ const node = absolute(options.node, 'node');
114
+ const script = options.script === undefined ? SCRIPT : absolute(options.script, 'script');
115
+ const user = safeValue(options.user || '', 'user');
116
+ if (!NAME.test(user) || user === 'root') fail('user: a dedicated system user (not root) is required.');
117
+ const group = options.group === undefined ? null : safeValue(options.group, 'group');
118
+ if (group !== null && !NAME.test(group)) fail('group: invalid name.');
119
+ if (options.tokenFile === undefined) fail('tokenFile: the service refuses to start without a token.');
120
+ if ((options.signingKeyFile === undefined) !== (options.signatureAgent === undefined)) fail('signingKeyFile and signatureAgent go together.');
121
+ const size = (value, name) => {
122
+ const text = safeValue(value, name);
123
+ if (!/^\d+[KMGT]?$/.test(text)) fail(`${name}: e.g. "2G".`);
124
+ return text;
125
+ };
126
+ const cpuQuota = safeValue(options.cpuQuota ?? '200%', 'cpuQuota');
127
+ if (!/^\d+%$/.test(cpuQuota)) fail('cpuQuota: e.g. "200%".');
128
+ const tasksMax = options.tasksMax ?? 512;
129
+ if (!Number.isInteger(tasksMax) || tasksMax < 64) fail('tasksMax: 64 or more.');
130
+ const restartSec = options.restartSec ?? 5;
131
+ if (!Number.isInteger(restartSec) || restartSec < 0) fail('restartSec: non-negative integer.');
132
+ const description = safeValue(options.description || 'Astratra integrated web browser (read-only)', 'description');
133
+ const workingDirectory = options.workingDirectory === undefined ? path.dirname(script) : absolute(options.workingDirectory, 'workingDirectory');
134
+
135
+ const { tokenFile, signingKeyFile, ...rest } = options;
136
+ const env = browserServiceEnv(rest);
137
+ const lines = [
138
+ '[Unit]',
139
+ `Description=${description}`,
140
+ 'After=network-online.target astratra-web-browser-firewall.service',
141
+ 'Wants=network-online.target',
142
+ '# The firewall rules are loaded first; without them the service refuses to start anyway.',
143
+ 'Requires=astratra-web-browser-firewall.service',
144
+ '',
145
+ '[Service]',
146
+ 'Type=simple',
147
+ `User=${user}`
148
+ ];
149
+ if (group) lines.push(`Group=${group}`);
150
+ lines.push(
151
+ `WorkingDirectory=${quoteArg(workingDirectory)}`,
152
+ `ExecStart=${quoteArg(node)} ${quoteArg(script)} serve`,
153
+ 'StateDirectory=astratra-web-browser',
154
+ 'StateDirectoryMode=0700',
155
+ 'Environment="HOME=%S/astratra-web-browser"',
156
+ 'Environment=NODE_ENV=production'
157
+ );
158
+ if (options.environmentFile !== undefined) lines.push(`EnvironmentFile=${absolute(options.environmentFile, 'environmentFile')}`);
159
+ /* Le jeton et la clé : lisibles par ce service seul, jamais dans l'unité. */
160
+ lines.push(`LoadCredential=browser-token:${absolute(tokenFile, 'tokenFile')}`, 'Environment="WEB_BROWSER_TOKEN_FILE=%d/browser-token"');
161
+ if (signingKeyFile !== undefined) {
162
+ lines.push(`LoadCredential=browser-signing-key:${absolute(signingKeyFile, 'signingKeyFile')}`, 'Environment="WEB_BROWSER_SIGNING_KEY_FILE=%d/browser-signing-key"');
163
+ }
164
+ for (const [name, value] of Object.entries(env)) lines.push(`Environment=${quoteEnv(name, value)}`);
165
+ lines.push(
166
+ 'Restart=on-failure',
167
+ `RestartSec=${restartSec}`,
168
+ 'TimeoutStopSec=15',
169
+ `MemoryMax=${size(options.memoryMax ?? '2G', 'memoryMax')}`
170
+ );
171
+ if (options.memoryHigh !== undefined) lines.push(`MemoryHigh=${size(options.memoryHigh, 'memoryHigh')}`);
172
+ lines.push(
173
+ `CPUQuota=${cpuQuota}`,
174
+ `TasksMax=${tasksMax}`,
175
+ '# Hardening. Chromium keeps its own sandbox: it needs user, pid and net namespaces.',
176
+ '# No MemoryDenyWriteExecute: the JavaScript engine compiles code at run time.',
177
+ 'NoNewPrivileges=yes',
178
+ 'PrivateTmp=yes',
179
+ 'PrivateDevices=yes',
180
+ 'ProtectSystem=strict',
181
+ 'ProtectHome=yes',
182
+ 'ProtectKernelTunables=yes',
183
+ 'ProtectKernelModules=yes',
184
+ 'ProtectKernelLogs=yes',
185
+ 'ProtectControlGroups=yes',
186
+ 'ProtectClock=yes',
187
+ 'ProtectHostname=yes',
188
+ 'ProtectProc=invisible',
189
+ 'RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK',
190
+ 'RestrictNamespaces=user pid net',
191
+ 'RestrictRealtime=yes',
192
+ 'RestrictSUIDSGID=yes',
193
+ 'LockPersonality=yes',
194
+ 'SystemCallArchitectures=native',
195
+ 'CapabilityBoundingSet=',
196
+ 'AmbientCapabilities=',
197
+ 'UMask=0077'
198
+ );
199
+ for (const writable of options.readWritePaths || []) lines.push(`ReadWritePaths=${quoteArg(absolute(writable, 'readWritePaths'))}`);
200
+ lines.push('', '[Install]', 'WantedBy=multi-user.target', '');
201
+ return lines.join('\n');
202
+ }
203
+
204
+ /**
205
+ * Une entrée pm2. ATTENTION : pm2 ne donne aucune des protections de systemd
206
+ * (utilisateur à part, système en lecture seule…) ; le pare-feu reste
207
+ * obligatoire, et il faut lancer pm2 sous l'utilisateur du service.
208
+ */
209
+ function createBrowserPm2App(options = {}) {
210
+ const script = options.script === undefined ? SCRIPT : absolute(options.script, 'script');
211
+ const name = options.name === undefined ? 'astratra-web-browser' : safeValue(options.name, 'name');
212
+ if (!/^[A-Za-z0-9._-]+$/.test(name)) fail('name: letters, digits, dot, dash, underscore.');
213
+ if (options.tokenFile === undefined) fail('tokenFile: the service refuses to start without a token.');
214
+ const app = {
215
+ name,
216
+ script,
217
+ args: 'serve',
218
+ ...(options.node !== undefined ? { interpreter: absolute(options.node, 'node') } : {}),
219
+ cwd: options.cwd === undefined ? path.dirname(script) : absolute(options.cwd, 'cwd'),
220
+ exec_mode: 'fork',
221
+ instances: 1,
222
+ autorestart: true,
223
+ max_restarts: options.maxRestarts ?? 10,
224
+ restart_delay: options.restartDelay ?? 5000,
225
+ kill_timeout: options.killTimeout ?? 15000,
226
+ max_memory_restart: options.maxMemoryRestart ?? '2G',
227
+ env: { NODE_ENV: 'production', ...browserServiceEnv(options) }
228
+ };
229
+ if (!/^\d+[KMG]?$/.test(String(app.max_memory_restart))) fail('maxMemoryRestart: e.g. "2G".');
230
+ return app;
231
+ }
232
+
233
+ function nftAddress(prefix, bits) {
234
+ return `${prefix}/${bits}`;
235
+ }
236
+
237
+ /**
238
+ * Les règles nftables (à charger par `nft -f`) : l'utilisateur du service ne
239
+ * peut sortir que vers des adresses publiques, son résolveur DNS et son
240
+ * relais de sortie local. Toute autre adresse est jetée en sortie (la
241
+ * connexion n'aboutit jamais), ce que vérifie le contrôle au démarrage.
242
+ * @param {object} [options]
243
+ * @param {string} [options.user] Défaut "navigateur".
244
+ * @param {number} [options.proxyPort] Défaut 5009.
245
+ * @param {string[]} [options.dnsServers] Défaut ["127.0.0.53"] (systemd-resolved).
246
+ * @param {string} [options.table] Défaut "astratra_navigateur".
247
+ */
248
+ function createBrowserFirewall(options = {}) {
249
+ const user = safeValue(options.user ?? 'navigateur', 'user');
250
+ if (!NAME.test(user) || user === 'root') fail('user: a dedicated system user (not root).');
251
+ const table = safeValue(options.table ?? 'astratra_navigateur', 'table');
252
+ if (!/^[a-z_][a-z0-9_]*$/.test(table)) fail('table: letters, digits and underscores.');
253
+ const proxyPort = portOf(options.proxyPort ?? 5009, 'proxyPort');
254
+ const dnsServers = options.dnsServers ?? ['127.0.0.53'];
255
+ if (!Array.isArray(dnsServers) || !dnsServers.length) fail('dnsServers: at least one resolver address.');
256
+ const net = require('net');
257
+ for (const server of dnsServers) if (!net.isIP(String(server))) fail(`dnsServers: ${String(server).slice(0, 40)} is not an IP address.`);
258
+ const dnsLines = dnsServers.flatMap((server) => {
259
+ const family = net.isIPv6(server) ? 'ip6' : 'ip';
260
+ return [` ${family} daddr ${server} udp dport 53 accept`, ` ${family} daddr ${server} tcp dport 53 accept`];
261
+ });
262
+ return [
263
+ '#!/usr/sbin/nft -f',
264
+ `# Astratra web browser: user "${user}" may reach public addresses only.`,
265
+ '# Generated by @astratra/web-search (createBrowserFirewall). Load with: nft -f <this file>',
266
+ `table inet ${table}`,
267
+ `delete table inet ${table}`,
268
+ `table inet ${table} {`,
269
+ ' chain output {',
270
+ ' type filter hook output priority 0; policy accept;',
271
+ ` meta skuid != "${user}" return`,
272
+ ' ct state established,related accept',
273
+ ` ip daddr 127.0.0.1 tcp dport ${proxyPort} accept comment "browser egress relay"`,
274
+ ...dnsLines,
275
+ ` ip daddr { ${BLOCKED_IPV4.map(([prefix, bits]) => nftAddress(prefix, bits)).join(', ')} } drop comment "non-public IPv4"`,
276
+ ' ip6 daddr != 2000::/3 drop comment "IPv6 outside global unicast"',
277
+ ` ip6 daddr { ${BLOCKED_IPV6.filter(([prefix]) => /^[23]/.test(prefix)).map(([prefix, bits]) => nftAddress(prefix, bits)).join(', ')} } drop comment "reserved IPv6 inside 2000::/3"`,
278
+ ' }',
279
+ '}',
280
+ ''
281
+ ].join('\n');
282
+ }
283
+
284
+ /**
285
+ * L'unité qui charge les règles du navigateur au démarrage de la machine,
286
+ * avant le service. Elle ne touche qu'à sa propre table (le fichier la
287
+ * supprime puis la recrée) : les autres règles de la machine (ufw, Docker,
288
+ * nftables.conf) restent telles quelles. `nftables.service` d'Ubuntu, lui,
289
+ * commence par tout effacer.
290
+ * @param {{ nftFile?: string, nft?: string }} [options]
291
+ */
292
+ function createBrowserFirewallUnit(options = {}) {
293
+ const nftFile = absolute(options.nftFile ?? '/etc/astratra/astratra-web-browser.nft', 'nftFile');
294
+ const nft = absolute(options.nft ?? '/usr/sbin/nft', 'nft');
295
+ return [
296
+ '[Unit]',
297
+ 'Description=Astratra integrated web browser: firewall rules',
298
+ 'DefaultDependencies=no',
299
+ 'Before=network-pre.target astratra-web-browser.service',
300
+ 'Wants=network-pre.target',
301
+ '',
302
+ '[Service]',
303
+ 'Type=oneshot',
304
+ 'RemainAfterExit=yes',
305
+ `ExecStart=${quoteArg(nft)} -f ${quoteArg(nftFile)}`,
306
+ '',
307
+ '[Install]',
308
+ 'WantedBy=multi-user.target',
309
+ ''
310
+ ].join('\n');
311
+ }
312
+
313
+ /**
314
+ * Le profil AppArmor du binaire de Chromium (Ubuntu 23.10 et suivants
315
+ * restreignent les espaces de noms non privilégiés : sans lui, le
316
+ * cloisonnement de Chromium ne démarre pas, et le service refuse de démarrer).
317
+ * @param {{ chromiumPath: string, name?: string }} options
318
+ */
319
+ function createBrowserAppArmorProfile(options = {}) {
320
+ const binary = absolute(options.chromiumPath, 'chromiumPath');
321
+ if (/[\s"{}]/.test(binary)) fail('chromiumPath: no spaces, quotes or braces.');
322
+ const name = safeValue(options.name ?? 'astratra-chromium', 'name');
323
+ if (!/^[a-z][a-z0-9_-]*$/.test(name)) fail('name: letters, digits, dash, underscore.');
324
+ return [
325
+ '# Astratra web browser: lets Chromium create its sandbox namespaces.',
326
+ '# Generated by @astratra/web-search (createBrowserAppArmorProfile).',
327
+ 'abi <abi/4.0>,',
328
+ 'include <tunables/global>',
329
+ '',
330
+ `profile ${name} ${binary} flags=(unconfined) {`,
331
+ ' userns,',
332
+ '',
333
+ ` include if exists <local/${name}>`,
334
+ '}',
335
+ ''
336
+ ].join('\n');
337
+ }
338
+
339
+ /**
340
+ * Tous les fichiers d'un déploiement, et la marche à suivre.
341
+ * @returns {Record<string, string>}
342
+ */
343
+ function browserSetupFiles(options = {}) {
344
+ const user = options.user ?? 'navigateur';
345
+ const proxyPort = options.proxyPort ?? 5009;
346
+ const group = safeValue(options.clientsGroup ?? 'astratra-browser', 'clientsGroup');
347
+ if (!NAME.test(group)) fail('clientsGroup: a group name (letters, digits, dash, underscore).');
348
+ const files = {
349
+ 'astratra-web-browser.service': createBrowserSystemdUnit({ ...options, user, proxyPort }),
350
+ 'astratra-web-browser.nft': createBrowserFirewall({ user, proxyPort, dnsServers: options.dnsServers, table: options.table }),
351
+ 'astratra-web-browser-firewall.service': createBrowserFirewallUnit({ nftFile: options.nftFile })
352
+ };
353
+ const nftFile = options.nftFile ?? '/etc/astratra/astratra-web-browser.nft';
354
+ if (options.chromiumPath) files['astratra-chromium.apparmor'] = createBrowserAppArmorProfile({ chromiumPath: options.chromiumPath });
355
+ const tokenFile = absolute(options.tokenFile, 'tokenFile');
356
+ const port = options.port ?? 5008;
357
+ const apparmor = Boolean(files['astratra-chromium.apparmor']);
358
+ files['INSTALL.md'] = [
359
+ '# Astratra integrated browser — installation (as root)',
360
+ '',
361
+ `1. Service user: \`useradd --system --home-dir /var/lib/astratra-web-browser --shell /usr/sbin/nologin ${user}\``,
362
+ `2. Group of the applications allowed to call the service: \`groupadd --system ${group}\`,`,
363
+ ` then, for each user that runs such an application (the user of its pm2, systemd unit…): \`usermod -aG ${group} <user>\`.`,
364
+ ' A new group membership only applies to processes started afterwards: restart that application\'s process',
365
+ ' manager from a new session (for pm2: `pm2 kill` then `pm2 resurrect`, which restarts all its applications).',
366
+ ` Without a restart: \`setfacl -m u:<user>:r ${tokenFile}\` (package acl) after step 3.`,
367
+ `3. Token: \`astratra-web-browser token --out ${tokenFile} --group ${group}\``,
368
+ ` (owned by root, mode 640, readable by the group ${group}; systemd hands it to the service). Never commit it.`,
369
+ ` Its folder must stay traversable (\`chmod 755 ${path.dirname(tokenFile)}\`), or the applications cannot reach the file.`,
370
+ `4. Firewall: copy \`astratra-web-browser.nft\` to \`${nftFile}\` and \`astratra-web-browser-firewall.service\` to \`/etc/systemd/system/\`,`,
371
+ ' then `systemctl daemon-reload && systemctl enable --now astratra-web-browser-firewall`. This unit loads only its own',
372
+ ' table at boot, before the service; it leaves the machine\'s other rules (ufw, Docker, nftables.conf) alone.',
373
+ ' Do not enable nftables.service for this: it starts by flushing every rule.',
374
+ ...(apparmor
375
+ ? ['5. AppArmor (Ubuntu 23.10 and later): copy `astratra-chromium.apparmor` to `/etc/apparmor.d/astratra-chromium`,', ' then `apparmor_parser -r /etc/apparmor.d/astratra-chromium`.']
376
+ : ['5. AppArmor (Ubuntu 23.10 and later): rerun `setup` with `--chromium <path of chrome-headless-shell>` to get the profile.']),
377
+ '6. Service: copy `astratra-web-browser.service` to `/etc/systemd/system/`, then',
378
+ ' `systemctl daemon-reload && systemctl enable --now astratra-web-browser`.',
379
+ '7. Check: `journalctl -u astratra-web-browser -n 20` must show "isolation ok";',
380
+ ` \`curl -s -H "Authorization: Bearer $(cat ${tokenFile})" http://127.0.0.1:${port}/health\`.`,
381
+ `8. In each application: \`createBrowserClient({ baseUrl: 'http://127.0.0.1:${port}', tokenFile: '${tokenFile}' })\`.`,
382
+ '',
383
+ 'The service refuses to start if it can reach the internal network: keep the firewall loaded.',
384
+ ''
385
+ ].join('\n');
386
+ files['INSTALL.fr.md'] = [
387
+ '# Navigateur intégré Astratra — installation (en root)',
388
+ '',
389
+ `1. Utilisateur du service : \`useradd --system --home-dir /var/lib/astratra-web-browser --shell /usr/sbin/nologin ${user}\``,
390
+ `2. Groupe des applications qui ont le droit d'appeler le service : \`groupadd --system ${group}\`,`,
391
+ ` puis, pour chaque utilisateur qui fait tourner une telle application (celui de son pm2, de son unité systemd…) : \`usermod -aG ${group} <utilisateur>\`.`,
392
+ ' Un nouveau groupe ne vaut que pour les processus lancés après : relancer le gestionnaire de cette application',
393
+ ' depuis une nouvelle session (pour pm2 : `pm2 kill` puis `pm2 resurrect`, qui relance toutes ses applications).',
394
+ ` Sans relance : \`setfacl -m u:<utilisateur>:r ${tokenFile}\` (paquet acl) après l'étape 3.`,
395
+ `3. Jeton : \`astratra-web-browser token --out ${tokenFile} --group ${group}\``,
396
+ ` (à root, mode 640, lisible par le groupe ${group} ; systemd le passe au service). Ne jamais le mettre dans git.`,
397
+ ` Son dossier doit rester traversable (\`chmod 755 ${path.dirname(tokenFile)}\`), sinon les applications n'atteignent pas le fichier.`,
398
+ `4. Pare-feu : copier \`astratra-web-browser.nft\` dans \`${nftFile}\` et \`astratra-web-browser-firewall.service\` dans \`/etc/systemd/system/\`,`,
399
+ ' puis `systemctl daemon-reload && systemctl enable --now astratra-web-browser-firewall`. Cette unité charge seulement sa',
400
+ ' propre table au démarrage, avant le service ; elle ne touche pas aux autres règles de la machine (ufw, Docker, nftables.conf).',
401
+ ' Ne pas activer nftables.service pour cela : il commence par effacer toutes les règles.',
402
+ ...(apparmor
403
+ ? ['5. AppArmor (Ubuntu 23.10 et suivants) : copier `astratra-chromium.apparmor` dans `/etc/apparmor.d/astratra-chromium`,', ' puis `apparmor_parser -r /etc/apparmor.d/astratra-chromium`.']
404
+ : ['5. AppArmor (Ubuntu 23.10 et suivants) : relancer `setup` avec `--chromium <chemin de chrome-headless-shell>` pour obtenir le profil.']),
405
+ '6. Service : copier `astratra-web-browser.service` dans `/etc/systemd/system/`, puis',
406
+ ' `systemctl daemon-reload && systemctl enable --now astratra-web-browser`.',
407
+ '7. Contrôle : `journalctl -u astratra-web-browser -n 20` doit montrer « isolation ok » ;',
408
+ ` \`curl -s -H "Authorization: Bearer $(cat ${tokenFile})" http://127.0.0.1:${port}/health\`.`,
409
+ `8. Dans chaque application : \`createBrowserClient({ baseUrl: 'http://127.0.0.1:${port}', tokenFile: '${tokenFile}' })\`.`,
410
+ '',
411
+ 'Le service refuse de démarrer s\'il peut joindre le réseau interne : le pare-feu doit rester chargé.',
412
+ ''
413
+ ].join('\n');
414
+ return files;
415
+ }
416
+
417
+ module.exports = {
418
+ browserServiceEnv,
419
+ createBrowserSystemdUnit,
420
+ createBrowserPm2App,
421
+ createBrowserFirewall,
422
+ createBrowserFirewallUnit,
423
+ createBrowserAppArmorProfile,
424
+ browserSetupFiles,
425
+ BROWSER_CLI: SCRIPT
426
+ };
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Le relais de sortie du navigateur : Chromium n'ouvre AUCUNE connexion
3
+ * lui-même, tout passe par ce relais (`--proxy-server`, boucle locale comprise).
4
+ *
5
+ * Pour chaque connexion (`CONNECT hôte:port`, ou requête `http` si
6
+ * `allowHttp`) :
7
+ * - le port doit être permis ;
8
+ * - le nom est refusé sans résolution s'il est interne, puis résolu ICI ; si
9
+ * UNE de ses adresses n'est pas publique, la connexion est refusée ;
10
+ * - la connexion part vers l'adresse vérifiée elle-même : un DNS qui
11
+ * changerait de réponse (DNS rebinding) n'y gagne rien.
12
+ *
13
+ * Les redirections, les WebSocket, les requêtes des scripts, des images ou
14
+ * des cadres passent toutes par ici : c'est ce qui les couvre, l'interception
15
+ * de Playwright ne voyant pas les redirections. Le TLS reste de bout en bout
16
+ * (tunnel, pas de déchiffrement).
17
+ *
18
+ * Le relais écoute sur 127.0.0.1 et demande un identifiant tiré au hasard au
19
+ * lancement : un autre processus de la machine ne peut pas s'en servir.
20
+ */
21
+
22
+ const http = require('http');
23
+ const net = require('net');
24
+ const dns = require('dns');
25
+ const crypto = require('crypto');
26
+ const { isPublicAddress, isBlockedHostname } = require('../address');
27
+
28
+ function lookupAll(resolve, hostname) {
29
+ return new Promise((resolvePromise, reject) => {
30
+ resolve(hostname, { all: true, family: 0 }, (error, addresses) => {
31
+ if (error) return reject(error);
32
+ const list = (Array.isArray(addresses) ? addresses : [{ address: addresses }]).map((entry) => (typeof entry === 'string' ? entry : entry?.address)).filter(Boolean);
33
+ return resolvePromise(list);
34
+ });
35
+ });
36
+ }
37
+
38
+ /** `hôte:port` d'une ligne CONNECT (IPv6 entre crochets). */
39
+ function splitTarget(value) {
40
+ const match = /^\[([^\]]+)\]:(\d+)$/.exec(value) || /^([^:]+):(\d+)$/.exec(value);
41
+ if (!match) return null;
42
+ const port = Number(match[2]);
43
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
44
+ return { hostname: match[1].toLowerCase().replace(/\.$/, ''), port };
45
+ }
46
+
47
+ /**
48
+ * @param {object} [options]
49
+ * @param {Function} [options.resolve] dns.lookup (tests).
50
+ * @param {Function} [options.connect] ({ hostname, address, port }) => net.Socket (tests).
51
+ * @param {number[]} [options.ports] Défaut [443] (et 80 avec allowHttp).
52
+ * @param {boolean} [options.allowHttp]
53
+ * @param {number} [options.port] Défaut 0 (un port libre) ; fixe en production pour le pare-feu.
54
+ * @param {string} [options.host] Défaut 127.0.0.1.
55
+ * @param {number} [options.idleMs] Défaut 30 s.
56
+ * @param {Function} [options.onRefused] ({ hostname, port, reason }) => void.
57
+ */
58
+ async function startEgressProxy(options = {}) {
59
+ const resolve = options.resolve || dns.lookup;
60
+ const allowHttp = options.allowHttp === true;
61
+ const ports = new Set(options.ports || (allowHttp ? [443, 80] : [443]));
62
+ const idleMs = options.idleMs ?? 30_000;
63
+ const username = 'astratra';
64
+ const password = crypto.randomBytes(18).toString('base64url');
65
+ const expected = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
66
+ const stats = { tunnels: 0, refused: 0, open: 0 };
67
+ const sockets = new Set();
68
+
69
+ const authorized = (req) => {
70
+ const given = String(req.headers['proxy-authorization'] || '');
71
+ const a = Buffer.from(given);
72
+ const b = Buffer.from(expected);
73
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
74
+ };
75
+
76
+ /** null si permis, sinon la raison ; `address` : l'adresse vérifiée. */
77
+ async function vet(hostname, port) {
78
+ if (!ports.has(port)) return { reason: 'port' };
79
+ const host = hostname.replace(/^\[|\]$/g, '');
80
+ if (isBlockedHostname(host)) return { reason: 'address' };
81
+ if (net.isIP(host)) return { address: host };
82
+ let addresses;
83
+ try {
84
+ addresses = await lookupAll(resolve, host);
85
+ } catch (_error) {
86
+ return { reason: 'dns' };
87
+ }
88
+ if (!addresses.length || addresses.some((address) => !isPublicAddress(address))) return { reason: 'address' };
89
+ return { address: addresses[0] };
90
+ }
91
+
92
+ const refused = (hostname, port, reason) => {
93
+ stats.refused += 1;
94
+ try {
95
+ options.onRefused?.({ hostname, port, reason });
96
+ } catch (_error) {
97
+ /* un observateur ne casse rien */
98
+ }
99
+ };
100
+
101
+ const open = ({ hostname, address, port }) => (options.connect
102
+ ? options.connect({ hostname, address, port })
103
+ : net.connect({ host: address, port }));
104
+
105
+ const server = http.createServer(async (req, res) => {
106
+ /* Requête http ordinaire (adresse absolue) : seulement avec allowHttp. */
107
+ if (!authorized(req)) {
108
+ res.writeHead(407, { 'proxy-authenticate': 'Basic realm="astratra"', connection: 'close' });
109
+ return res.end();
110
+ }
111
+ let url;
112
+ try {
113
+ url = new URL(req.url);
114
+ } catch (_error) {
115
+ res.writeHead(400, { connection: 'close' });
116
+ return res.end();
117
+ }
118
+ if (!allowHttp || url.protocol !== 'http:') {
119
+ refused(url.hostname, Number(url.port || 80), 'protocol');
120
+ res.writeHead(403, { connection: 'close' });
121
+ return res.end();
122
+ }
123
+ const port = Number(url.port || 80);
124
+ const verdict = await vet(url.hostname.toLowerCase(), port);
125
+ if (verdict.reason) {
126
+ refused(url.hostname, port, verdict.reason);
127
+ res.writeHead(403, { connection: 'close' });
128
+ return res.end();
129
+ }
130
+ const headers = { ...req.headers };
131
+ delete headers['proxy-authorization'];
132
+ delete headers['proxy-connection'];
133
+ const upstream = http.request({
134
+ host: verdict.address,
135
+ port,
136
+ method: req.method,
137
+ path: `${url.pathname}${url.search}`,
138
+ headers: { ...headers, host: url.host },
139
+ createConnection: options.connect ? () => open({ hostname: url.hostname, address: verdict.address, port }) : undefined,
140
+ timeout: idleMs
141
+ }, (answer) => {
142
+ res.writeHead(answer.statusCode || 502, answer.headers);
143
+ answer.pipe(res);
144
+ });
145
+ upstream.on('timeout', () => upstream.destroy());
146
+ upstream.on('error', () => {
147
+ if (!res.headersSent) res.writeHead(502, { connection: 'close' });
148
+ res.end();
149
+ });
150
+ req.pipe(upstream);
151
+ });
152
+
153
+ server.on('connect', async (req, client, head) => {
154
+ sockets.add(client);
155
+ client.on('close', () => sockets.delete(client));
156
+ client.on('error', () => {});
157
+ if (!authorized(req)) {
158
+ client.end('HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="astratra"\r\nConnection: close\r\n\r\n');
159
+ return;
160
+ }
161
+ const target = splitTarget(String(req.url || ''));
162
+ if (!target) {
163
+ client.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
164
+ return;
165
+ }
166
+ const verdict = await vet(target.hostname, target.port);
167
+ if (verdict.reason) {
168
+ refused(target.hostname, target.port, verdict.reason);
169
+ client.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');
170
+ return;
171
+ }
172
+ let upstream;
173
+ try {
174
+ upstream = open({ hostname: target.hostname, address: verdict.address, port: target.port });
175
+ } catch (_error) {
176
+ client.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n');
177
+ return;
178
+ }
179
+ sockets.add(upstream);
180
+ stats.tunnels += 1;
181
+ stats.open += 1;
182
+ upstream.setTimeout(idleMs, () => {
183
+ upstream.destroy();
184
+ client.destroy();
185
+ });
186
+ client.setTimeout(idleMs, () => {
187
+ client.destroy();
188
+ upstream.destroy();
189
+ });
190
+ let connected = false;
191
+ upstream.on('connect', () => {
192
+ connected = true;
193
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
194
+ if (head?.length) upstream.write(head);
195
+ /* pipe() ferme chaque côté quand l'autre a fini : rien de ce qui est déjà reçu n'est perdu. */
196
+ upstream.pipe(client);
197
+ client.pipe(upstream);
198
+ });
199
+ upstream.on('error', () => {
200
+ if (!connected && !client.destroyed) client.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n');
201
+ else client.destroy();
202
+ });
203
+ upstream.on('close', () => {
204
+ sockets.delete(upstream);
205
+ stats.open -= 1;
206
+ if (!client.destroyed && !client.writableEnded) client.end();
207
+ });
208
+ client.on('error', () => upstream.destroy());
209
+ client.on('close', () => upstream.destroy());
210
+ });
211
+ server.on('clientError', (_error, socket) => socket.destroy());
212
+
213
+ await new Promise((resolvePromise, reject) => {
214
+ server.once('error', reject);
215
+ server.listen(options.port ?? 0, options.host || '127.0.0.1', () => {
216
+ server.off('error', reject);
217
+ resolvePromise();
218
+ });
219
+ });
220
+ const { port } = server.address();
221
+ return {
222
+ port,
223
+ server: `http://127.0.0.1:${port}`,
224
+ username,
225
+ password,
226
+ stats: () => ({ ...stats }),
227
+ close: () => new Promise((resolvePromise) => {
228
+ for (const socket of sockets) socket.destroy();
229
+ server.close(() => resolvePromise());
230
+ })
231
+ };
232
+ }
233
+
234
+ module.exports = { startEgressProxy };