launch-film 0.3.1 → 0.3.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/src/brand.js CHANGED
@@ -40,9 +40,10 @@ const normHex = (v) => {
40
40
  // The commands that may run easybrandkit, in the order they are tried: the
41
41
  // one given (a command, or the path of easybrandkit's script), else
42
42
  // LAUNCH_FILM_EASYBRANDKIT, else an easybrandkit installed on PATH, else
43
- // easybrandkit 0.4.1 from npm through npx, then the same release from its
44
- // GitHub repository when npm cannot give it. The version is pinned, so a run
45
- // never picks up a newer easybrandkit on its own.
43
+ // easybrandkit 0.4.3 from npm through npx, then the same release from its
44
+ // GitHub repository when npm cannot give it, by the commit 0.4.3 was
45
+ // published from, which no one can move as a tag can be moved. The version
46
+ // is pinned, so a run never picks up another easybrandkit on its own.
46
47
  function easybrandkitCommands(given = "") {
47
48
  const raw = String(given || process.env.LAUNCH_FILM_EASYBRANDKIT || "").trim();
48
49
  if (raw) {
@@ -53,7 +54,7 @@ function easybrandkitCommands(given = "") {
53
54
  const installed = onPath(windows ? "easybrandkit.cmd" : "easybrandkit");
54
55
  if (installed) return [windows ? scriptOfInstalled(installed) : [installed]];
55
56
  const npx = windows ? scriptOfNpx() : ["npx"];
56
- return [[...npx, "-y", "easybrandkit@0.4.1"], [...npx, "-y", "github:MakersMCP/easybrandkit#v0.4.1"]];
57
+ return [[...npx, "-y", "easybrandkit@0.4.3"], [...npx, "-y", "github:MakersMCP/easybrandkit#e95088d7f366be18168c7583687a1e5d7f56bb53"]];
57
58
  }
58
59
 
59
60
  // On Windows npx and an installed easybrandkit are .cmd files. Node starts
@@ -83,11 +84,15 @@ const HOW = "Install easybrandkit (npm install -g easybrandkit), or point LAUNCH
83
84
  // Runs easybrandkit for a URL into a folder. Resolves the path of brand.json.
84
85
  // The next command is tried only when npx could not fetch easybrandkit; when
85
86
  // easybrandkit ran and failed, running it again would fail the same way.
86
- async function runEasybrandkit(url, dir, { log = () => {}, command = "" } = {}) {
87
+ // namedBy: the address of the page that named the site, as an App Store
88
+ // listing names the maker's site (store.js), which easybrandkit then reads
89
+ // as a page it chose, held to its rule for one, and not as the address
90
+ // given (--named-by).
91
+ async function runEasybrandkit(url, dir, { log = () => {}, command = "", namedBy = "" } = {}) {
87
92
  const commands = easybrandkitCommands(command);
88
93
  for (const [i, cmd] of commands.entries()) {
89
94
  try {
90
- return await runOnce(cmd, url, dir, log);
95
+ return await runOnce(cmd, url, dir, log, namedBy);
91
96
  } catch (err) {
92
97
  if (!err.unfetched || i === commands.length - 1) throw err;
93
98
  log(`${err.message.split(". ")[0]}; trying ${commands[i + 1].join(" ")}\n`);
@@ -98,7 +103,7 @@ async function runEasybrandkit(url, dir, { log = () => {}, command = "" } = {})
98
103
  // The Chrome of easybrandkit 0.4.0 and older saves a file a page makes it
99
104
  // download, of any size, into the Downloads folder of the user it runs as,
100
105
  // where nothing removes it, as launch-film's own Chrome no longer does
101
- // (chrome.js). 0.4.1, which launch-film runs through npx, refuses downloads,
106
+ // (chrome.js). 0.4.3, which launch-film runs through npx, refuses downloads,
102
107
  // but one on PATH or named by LAUNCH_FILM_EASYBRANDKIT can be older. On Linux
103
108
  // Chrome finds that folder in $XDG_CONFIG_HOME/user-dirs.dirs, so easybrandkit
104
109
  // is given such a folder in the run's temp folder, `temp`, that names one
@@ -122,7 +127,7 @@ function downloadsIn(temp, env) {
122
127
  // A stop removes the temp folder itself once what uses it has been killed:
123
128
  // removed here while Chrome still writes there, the removal's retries would
124
129
  // hold the stop up past the moment a supervisor kills the run.
125
- function runOnce([cmd, ...pre], url, dir, log) {
130
+ function runOnce([cmd, ...pre], url, dir, log, namedBy = "") {
126
131
  return new Promise((resolve, reject) => {
127
132
  const temp = process.platform === "linux" ? tempDir("launch-film-brand-") : null;
128
133
  const done = () => temp && !stopping() && release(temp);
@@ -145,7 +150,7 @@ function runOnce([cmd, ...pre], url, dir, log) {
145
150
  }
146
151
  let child;
147
152
  try {
148
- child = track(spawn(cmd, [...pre, url, "--out", dir], { stdio: ["ignore", "pipe", "pipe"], env }), { watch: true });
153
+ child = track(spawn(cmd, [...pre, url, "--out", dir, ...(namedBy ? ["--named-by", namedBy] : [])], { stdio: ["ignore", "pipe", "pipe"], env }), { watch: true });
149
154
  } catch (e) {
150
155
  // A .cmd file on Windows, given without a shell.
151
156
  return unstarted(e);
@@ -155,12 +160,16 @@ function runOnce([cmd, ...pre], url, dir, log) {
155
160
  child.on("error", unstarted);
156
161
  if (!child.stdout) return;
157
162
  let out = "";
163
+ // The start of what it said, where an easybrandkit older than 0.4.3,
164
+ // given --named-by, names that option before its usage text.
165
+ let start = "";
158
166
  child.stdout.on("data", (d) => {
159
167
  out = (out + d).slice(-3000);
160
168
  log(String(d));
161
169
  });
162
170
  child.stderr.on("data", (d) => {
163
171
  out = (out + d).slice(-3000);
172
+ if (start.length < 3000) start += d;
164
173
  log(String(d));
165
174
  });
166
175
  child.on("close", (code) => {
@@ -174,6 +183,7 @@ function runOnce([cmd, ...pre], url, dir, log) {
174
183
  // package, no network) before it ran; easybrandkit never prints them.
175
184
  const npm = /^npm (?:error|ERR!) code \S+/m.exec(out) || /^npm (?:error|ERR!) .+/m.exec(out);
176
185
  if (npm) reject(Object.assign(new Error(`easybrandkit could not be fetched (${npm[0].trim()}). ${HOW}`), { unfetched: true }));
186
+ else if (namedBy && /Unknown option: --named-by/.test(start)) reject(Object.assign(new Error(`easybrandkit failed (exit ${code}): Unknown option: --named-by, which easybrandkit takes from 0.4.3 on`), { ownWords: true }));
177
187
  else if (/bot check/i.test(out)) reject(Object.assign(new Error(`${said} The brand could not be read: ask for the logo file and the main colors, or give a kit with --brand.`), { ownWords: true }));
178
188
  else reject(Object.assign(new Error(`easybrandkit failed (exit ${code})${said ? `: ${said}` : ""}`), { ownWords: true }));
179
189
  });
@@ -200,6 +210,22 @@ function wordsOf(text) {
200
210
  return { title: String(text.title || ""), description: String(text.description || ""), headings, ctas: Array.isArray(text.ctas) ? text.ctas.map(String) : [], paragraphs: [], jsonld: [] };
201
211
  }
202
212
 
213
+ // Whether a note of a kit is one easybrandkit 0.4.3 gives an address its
214
+ // browser asked for and its proxy did not reach, or how many more there
215
+ // were, by its fixed words on one line. The words are looked for with
216
+ // indexOf, in a time that grows as the note does, as a kit can hold any
217
+ // note: a pattern with three open parts took 6 s on a note of 27 kB built
218
+ // for it, and that time grows as the cube of the note's length.
219
+ function unreachedNote(note) {
220
+ if (typeof note !== "string" || /[\n\r\u2028\u2029]/.test(note)) return false;
221
+ if (/^(?:At least )?\d{1,9} more address(?:es)? the browser asked for (?:was|were) not reached either\.$/.test(note)) return true;
222
+ const [start, asked, which, end] = ["While easybrandkit read ", ", the browser asked for ", ", which ", ": it was not reached."];
223
+ if (!note.startsWith(start) || !note.endsWith(end)) return false;
224
+ const at = note.indexOf(asked, start.length + 1);
225
+ const why = at < 0 ? -1 : note.indexOf(which, at + asked.length + 1);
226
+ return why >= 0 && why + which.length < note.length - end.length;
227
+ }
228
+
203
229
  // brand.json read and put in the shape the film uses. Files that are
204
230
  // missing are left out with a note. With LAUNCH_FILM_CONFINE set, a file
205
231
  // named outside the kit's folder makes the kit one that cannot be read
@@ -263,6 +289,13 @@ function readBrand(file) {
263
289
  assets: (Array.isArray(s.assets) ? s.assets : []).map((a, k) => ({ file: fileOf(a && a.file, `stores[${i}].assets[${k}].file`), kind: String((a && a.kind) || ""), width: Number(a && a.width) || 0, height: Number(a && a.height) || 0 })).filter((a) => a.file),
264
290
  }));
265
291
  if (outside.length) throw new Error(`${path.basename(file)} names files outside its folder, which LAUNCH_FILM_CONFINE does not allow: ${outside.join(", ")}`);
292
+ // The kit's own notes that name an address its browser asked for and did
293
+ // not reach, as easybrandkit 0.4.3 writes them, as what its page takes from
294
+ // another port of a site under development: kept apart (unreached), so a
295
+ // plan passes them on to say why the kit lacks what that address held, and
296
+ // a render of its film does not say them again; cut when long, and no more
297
+ // of them than easybrandkit writes (three and how many more).
298
+ const unreached = (Array.isArray(raw.notes) ? raw.notes : []).filter(unreachedNote).slice(0, 4).map((note) => confine.said(note, 600));
266
299
  if (lists.length) throw new Error(`${path.basename(file)} names lists of other files where pictures go, whose files ffmpeg would open wherever they are, which LAUNCH_FILM_CONFINE does not allow: ${lists.join(", ")}`);
267
300
  const appStores = stores.filter((s) => /appstore|googleplay|play/i.test(s.type));
268
301
  const phoneScreens = appStores.flatMap((s) => s.assets.filter((a) => /screen/i.test(a.kind) && a.height > a.width));
@@ -297,6 +330,7 @@ function readBrand(file) {
297
330
  app: raw.app && typeof raw.app === "object" ? { name: String(raw.app.name || ""), by: String(raw.app.by || ""), site: String(raw.app.site || "") } : null,
298
331
  text: wordsOf(raw.text),
299
332
  notes,
333
+ unreached,
300
334
  };
301
335
  }
302
336
 
package/src/chrome.js CHANGED
@@ -16,11 +16,25 @@
16
16
  // plan read filled that folder, outside every folder of the run's. So every
17
17
  // Chrome is told to refuse downloads before any page opens, and its profile
18
18
  // names a folder inside it for them, should one still be saved.
19
+ //
20
+ // The Chrome that reads a site's words sends every request through a proxy
21
+ // of launch-film's own on 127.0.0.1 (proxy.js), which holds it to the run's
22
+ // rule for the addresses it opens (web.js): whatever asks for an address, a
23
+ // page, a frame, a picture, a script, the data a page fetches, a WebSocket,
24
+ // a service worker or the fetch of a certificate's issuer, the request goes
25
+ // there, and one the rule refuses gets no connection. It looks no name up
26
+ // itself, and its WebRTC sends no UDP, which goes around a proxy. The ones
27
+ // that render the clips stay offline.
19
28
 
20
29
  const fs = require("fs");
21
30
  const os = require("os");
22
31
  const path = require("path");
32
+ const dgram = require("dgram");
33
+ const crypto = require("crypto");
23
34
  const { spawn } = require("child_process");
35
+ const { startProxy, keyOf, OWN_NAME } = require("./proxy");
36
+ const { UNRESOLVED } = require("./address");
37
+ const confine = require("./confine");
24
38
  const { encoder } = require("./ffmpeg");
25
39
  const { getSystemErrorMap } = require("util");
26
40
  const { tempDir, tempEnv, release, track, socketFolder, closeProfile, save, socketFits, fetching, SOCKET_ROOM } = require("./out");
@@ -221,11 +235,15 @@ function withoutOpeners(env = process.env) {
221
235
  // takes as the display's socket itself. Left unset, that display too is
222
236
  // looked for in XDG_RUNTIME_DIR, as wayland-0, which a Wayland desktop's
223
237
  // is, so a program Chrome starts could open a window there. A display
224
- // handed down already open (WAYLAND_SOCKET) goes as well.
238
+ // handed down already open (WAYLAND_SOCKET) goes as well. Chrome's own
239
+ // config folder is that folder too (CHROME_CONFIG_HOME), where its crash
240
+ // handler keeps its database and the dumps of a Chrome that crashes, which
241
+ // went into the user's own ~/.config/google-chrome/Crash Reports, holding
242
+ // Chrome's command line, and stayed there, --disable-breakpad or not.
225
243
  function offTheDesktop(env, folder) {
226
244
  if (process.platform !== "linux") return env;
227
245
  const { DISPLAY, WAYLAND_DISPLAY, WAYLAND_SOCKET, ...rest } = env;
228
- return { ...rest, DBUS_SESSION_BUS_ADDRESS: `unix:path=${busPath(path.join(folder, "no-bus"))}`, WAYLAND_DISPLAY: path.join(folder, "no-display") };
246
+ return { ...rest, DBUS_SESSION_BUS_ADDRESS: `unix:path=${busPath(path.join(folder, "no-bus"))}`, WAYLAND_DISPLAY: path.join(folder, "no-display"), CHROME_CONFIG_HOME: folder };
229
247
  }
230
248
 
231
249
  // A path as a bus address holds it: every byte but a letter, a digit and
@@ -266,13 +284,20 @@ function opened() {
266
284
  }
267
285
 
268
286
  // What Chrome is started with: the browser that renders the clips' pages
269
- // (offline), or the one that reads a site's words (network).
270
- function chromeArgs({ W = 1920, H = 1080, network = false, profile }) {
287
+ // (offline), or the one that reads a site's words (network), whose requests
288
+ // go through launch-film's proxy on 127.0.0.1 at the port `proxy` (none
289
+ // given, the port where nothing listens that keeps a render offline).
290
+ function chromeArgs({ W = 1920, H = 1080, network = false, profile, proxy = 9 }) {
271
291
  return [
272
292
  "--headless=new", "--hide-scrollbars", "--mute-audio", "--no-first-run", "--no-default-browser-check",
273
293
  "--disable-extensions", "--disable-sync", "--disable-default-apps", "--disable-background-networking",
274
294
  "--disable-component-update", "--disable-domain-reliability", "--disable-breakpad", "--metrics-recording-only",
275
- "--disable-features=Translate,MediaRouter,OptimizationHints,AutofillServerCommunication",
295
+ // Chrome reads one value of this switch, so the browser that reads a
296
+ // site has its own in it too: no names of WebRTC's for this machine's
297
+ // own addresses, for which it joined the mDNS group on each of this
298
+ // machine's networks as a page made a connection, past the proxy,
299
+ // though its WebRTC gathers no address of this machine.
300
+ `--disable-features=Translate,MediaRouter,OptimizationHints,AutofillServerCommunication${network ? ",WebRtcHideLocalIpsWithMdns" : ""}`,
276
301
  "--use-mock-keychain", "--password-store=basic", "--force-color-profile=srgb", "--font-render-hinting=none",
277
302
  // Chrome's sandbox does not start as root; anyone else keeps it, so a
278
303
  // page that breaks into Chrome's renderer is held there.
@@ -282,7 +307,17 @@ function chromeArgs({ W = 1920, H = 1080, network = false, profile }) {
282
307
  // Pages render offline: they carry their fonts and pictures with them,
283
308
  // and are given their files by openPage. WebRTC goes around a proxy over
284
309
  // UDP, so it is let send nothing but through the proxy, which is none.
285
- ...(network ? [] : ["--proxy-server=http://127.0.0.1:9", "--proxy-bypass-list=<-loopback>", "--webrtc-ip-handling-policy=disable_non_proxied_udp"]),
310
+ // The browser that reads a site sends every request through launch-film's
311
+ // proxy, those for this machine's own addresses too, which a browser
312
+ // otherwise sends past a proxy (<-loopback>), and its WebRTC sends no
313
+ // UDP, as that proxy takes none. It looks no name up itself: every name
314
+ // fails in its own lookup (^NOTFOUND), but 127.0.0.1, the proxy's
315
+ // address, so a name a page gives WebRTC is looked up nowhere, and its
316
+ // own DNS over HTTPS reaches no server. And no HTTP/3, with which a
317
+ // site's answer sends the browser's next requests to another port or
318
+ // host over UDP.
319
+ ...(network ? ["--host-resolver-rules=MAP * ^NOTFOUND, EXCLUDE 127.0.0.1", "--disable-quic"] : []),
320
+ `--proxy-server=http://127.0.0.1:${network ? proxy : 9}`, "--proxy-bypass-list=<-loopback>", "--webrtc-ip-handling-policy=disable_non_proxied_udp",
286
321
  "--remote-debugging-pipe", `--user-data-dir=${profile}`, `--window-size=${W},${H}`, "about:blank",
287
322
  ];
288
323
  }
@@ -303,7 +338,10 @@ function ownProfile(dir) {
303
338
  }
304
339
 
305
340
  // A browser with its own temp profile, answering protocol calls by promise.
306
- async function launch({ W = 1920, H = 1080, network = false } = {}) {
341
+ // One with the network on (network) reads a site: guard is the run's rule
342
+ // for the addresses it opens (web.js), which its proxy holds every request
343
+ // to; with none, it reaches no address at all.
344
+ async function launch({ W = 1920, H = 1080, network = false, guard = null } = {}) {
307
345
  const chrome = findChrome();
308
346
  if (!chrome) throw new Error("Chrome was not found. Install Google Chrome or Chromium, or set LAUNCH_FILM_CHROME to its path.");
309
347
  // The stand-ins first, so a temp folder they cannot run in starts no Chrome.
@@ -329,18 +367,46 @@ async function launch({ W = 1920, H = 1080, network = false } = {}) {
329
367
  let fetched = null;
330
368
  const profile = tempDir(short ? "lf-" : "launch-film-chrome-", (dir) => closeProfile(dir, socket, fetched), short ? ownProfile : null);
331
369
  // Downloads, should Chrome save one in spite of the refusal below, go in
332
- // the profile, which goes with the run.
370
+ // the profile, which goes with the run. The browser that reads a site
371
+ // makes no connection ahead of a request and preloads no page
372
+ // (network_prediction_options 2, never), and its WebRTC sends UDP to a
373
+ // proxy's alone and has no handling of its own for any site: a Chrome
374
+ // policy that recommends WebRTC's handling for some sites alone comes
375
+ // before the switch for those sites, and a user's own setting, which this
376
+ // profile is, before such a policy.
333
377
  fs.mkdirSync(path.join(profile, "Default"));
334
- save(path.join(profile, "Default", "Preferences"), JSON.stringify({ download: { default_directory: path.join(profile, "Downloads"), prompt_for_download: false } }));
335
- const args = chromeArgs({ W, H, network, profile });
378
+ const download = { default_directory: path.join(profile, "Downloads"), prompt_for_download: false };
379
+ save(path.join(profile, "Default", "Preferences"), JSON.stringify(network ? { download, net: { network_prediction_options: 2 }, webrtc: { ip_handling_policy: "disable_non_proxied_udp", ip_handling_url: [] } } : { download }));
380
+ // The proxy every request of the browser that reads a site goes through,
381
+ // on a port of 127.0.0.1 the system picks, for as long as that browser
382
+ // runs.
383
+ let proxy = null;
384
+ if (network) {
385
+ try {
386
+ proxy = await startProxy(guard);
387
+ } catch (err) {
388
+ release(profile);
389
+ throw new Error(`launch-film could not start the proxy that every request of its Chrome goes through, on 127.0.0.1 (${err.message})`);
390
+ }
391
+ }
392
+ const args = chromeArgs({ W, H, network, profile, proxy: proxy && proxy.port });
336
393
  const env = network ? tempEnv(profile) : process.env;
337
394
  if (linux && env === process.env) fetched = fetching();
338
- const child = track(spawn(chrome, args, { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"], env: withoutOpeners(offTheDesktop(env, profile)) }));
395
+ let child;
396
+ try {
397
+ child = track(spawn(chrome, args, { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"], env: withoutOpeners(offTheDesktop(env, profile)) }));
398
+ } catch (err) {
399
+ // A Chrome the system will not start in a way Node throws for leaves no
400
+ // proxy listening.
401
+ if (proxy) proxy.close();
402
+ throw err;
403
+ }
339
404
  // One the system had no file descriptor for comes back with no pipes, and
340
405
  // its error comes next (ffmpeg.js run): that is all there is to wait for.
341
406
  if (!child.stdio) {
342
407
  const err = await new Promise((resolve) => child.once("error", resolve));
343
408
  release(profile);
409
+ if (proxy) proxy.close();
344
410
  const { short } = require("./programs");
345
411
  throw Object.assign(new Error(short(err, "Chrome") || `Chrome could not be started from ${chrome}: ${err.message}`), { short: Boolean(short(err, "Chrome")) });
346
412
  }
@@ -376,6 +442,7 @@ async function launch({ W = 1920, H = 1080, network = false } = {}) {
376
442
  // holds its stderr: what is said of it waits for that, a second at most.
377
443
  child.on("exit", (code, signal) => {
378
444
  exited = true;
445
+ if (proxy) proxy.close();
379
446
  let told = false;
380
447
  const tell = () => {
381
448
  if (told) return;
@@ -430,17 +497,21 @@ async function launch({ W = 1920, H = 1080, network = false } = {}) {
430
497
  // left running, its pipes kept the process up after doctor or a plan that
431
498
  // went on with the page's HTML had ended. One that does not take the
432
499
  // refusal of downloads is ended the same way, before it opens a page.
433
- try {
434
- await send("Browser.getVersion");
435
- await send("Browser.setDownloadBehavior", { behavior: "deny" });
436
- } catch (err) {
500
+ const unstarted = (err) => {
437
501
  if (!exited) child.kill("SIGKILL");
438
502
  release(profile);
503
+ if (proxy) proxy.close();
439
504
  for (const stream of [child.stderr, child.stdio[3], child.stdio[4]]) if (stream) stream.destroy();
440
505
  throw err;
506
+ };
507
+ try {
508
+ await send("Browser.getVersion");
509
+ await send("Browser.setDownloadBehavior", { behavior: "deny" });
510
+ } catch (err) {
511
+ unstarted(err);
441
512
  }
442
513
  socket = socketFolder(profile);
443
- return {
514
+ const browser = {
444
515
  send,
445
516
  on: (fn) => listeners.add(fn),
446
517
  off: (fn) => listeners.delete(fn),
@@ -449,14 +520,21 @@ async function launch({ W = 1920, H = 1080, network = false } = {}) {
449
520
  const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
450
521
  return { sessionId, targetId, call: (m, p) => send(m, p, sessionId) };
451
522
  },
523
+ // The proxy the browser that reads a site sends its requests through,
524
+ // with what it refused and the connections it could not make
525
+ // (proxy.js), else null.
526
+ proxy,
452
527
  // Chrome is asked to close, so its helpers (the GPU, network and page
453
528
  // processes) end with it: killed outright, they went on writing to the
454
529
  // profile for seconds. One that has not gone in 3 s is killed. The
455
- // profile is removed once it has gone.
530
+ // profile is removed once it has gone, and the proxy closed.
456
531
  close() {
457
532
  if (closing) return;
458
533
  closing = true;
459
- const gone = () => release(profile);
534
+ const gone = () => {
535
+ release(profile);
536
+ if (proxy) proxy.close();
537
+ };
460
538
  if (dead || exited) return gone();
461
539
  child.once("exit", gone);
462
540
  const timer = setTimeout(() => child.kill("SIGKILL"), 3000);
@@ -465,6 +543,236 @@ async function launch({ W = 1920, H = 1080, network = false } = {}) {
465
543
  send("Browser.close").catch(() => {});
466
544
  },
467
545
  };
546
+ // Every request of the browser that reads a site goes through the proxy,
547
+ // as it is started to: asked before any page is opened. One that sends a
548
+ // request past it or elsewhere, or whose WebRTC sends UDP, is not used: it
549
+ // is asked to close as any is, its profile removed once it has gone. One
550
+ // that does not answer the check is ended as one that does not answer its
551
+ // first call.
552
+ if (network) {
553
+ let missed;
554
+ try {
555
+ missed = await throughProxy(browser, proxy);
556
+ } catch (err) {
557
+ unstarted(err);
558
+ }
559
+ if (missed) {
560
+ const why = missedProxy(missed, proxy);
561
+ browser.close();
562
+ throw new Error(why);
563
+ }
564
+ }
565
+ return browser;
566
+ }
567
+
568
+ // The browser that reads a site sends its requests through launch-film's
569
+ // proxy, as it is started to (launch): asked before any page is opened, in
570
+ // a tab of its own, with four addresses the proxy answers itself, by a word
571
+ // of its own in their paths: a name under .invalid, which no DNS answers,
572
+ // and this machine's 127.0.0.1, localhost and [::1] on the proxy's own
573
+ // port. Each has to come to the proxy as a request for the whole address,
574
+ // as a browser sends a proxy. One that comes to the proxy's port as an
575
+ // address of its own came past the proxy, and one that does not come went
576
+ // elsewhere: a Chrome policy (ProxyMode, ProxySettings, ProxyBypassList) or
577
+ // a program that starts the browser with switches of its own can make it do
578
+ // that. Then, in the same tab, the browser's WebRTC is to send no UDP (see
579
+ // udpPastProxy). null when all of it holds, else the first that did not:
580
+ // its number and what the browser said of it, { udp }, or { deaf } for a
581
+ // check of the browser's WebRTC that could not be made. As easybrandkit
582
+ // checks its own.
583
+ async function throughProxy(browser, proxy) {
584
+ const addresses = [`http://${OWN_NAME}/${proxy.token}/1`, `http://127.0.0.1:${proxy.port}/${proxy.token}/2`, `http://localhost:${proxy.port}/${proxy.token}/3`, `http://[::1]:${proxy.port}/${proxy.token}/4`];
585
+ const page = await browser.page();
586
+ // A browser whose connection to the proxy gets no answer, as behind a
587
+ // firewall that drops it, waits for as long as the system tries, two
588
+ // minutes and more on Linux: once it has asked for the first address, a
589
+ // proxy that has taken no connection at all in 15 s is one it cannot
590
+ // reach.
591
+ let asked = null;
592
+ const askedFirst = new Promise((resolve) => (asked = resolve));
593
+ const heard = (msg) => {
594
+ if (msg.sessionId === page.sessionId && msg.method === "Network.requestWillBeSent" && msg.params && msg.params.request && msg.params.request.url === addresses[0]) asked();
595
+ };
596
+ browser.on(heard);
597
+ try {
598
+ await page.call("Network.enable", { maxTotalBufferSize: 0, maxResourceBufferSize: 0 });
599
+ for (const [at, address] of addresses.entries()) {
600
+ const n = at + 1;
601
+ const navigating = page.call("Page.navigate", { url: address });
602
+ let timer;
603
+ const unreached = n === 1 ? askedFirst.then(() => new Promise((resolve) => (timer = setTimeout(() => resolve(!proxy.accepted), PROXY_CONNECT_WAIT)))) : new Promise(() => {});
604
+ const told = await Promise.race([navigating.then((answer) => ({ answer })), unreached.then((none) => (none ? { none } : navigating.then((answer) => ({ answer }))))]).finally(() => clearTimeout(timer));
605
+ if (told.none) {
606
+ navigating.catch(() => {});
607
+ return { n, errorText: "", unanswered: PROXY_CONNECT_WAIT };
608
+ }
609
+ if (!proxy.through.has(n)) return { n, errorText: told.answer.errorText || "" };
610
+ }
611
+ return await udpPastProxy(page);
612
+ } finally {
613
+ browser.off(heard);
614
+ browser.send("Target.closeTarget", { targetId: page.targetId }).catch(() => {});
615
+ }
616
+ }
617
+
618
+ // How long the browser is given to make its first connection to the proxy,
619
+ // once it has asked for the first address of the check.
620
+ const PROXY_CONNECT_WAIT = 15_000;
621
+
622
+ // How long a datagram launch-film sends its own STUN port is waited for: one
623
+ // on this machine's loopback comes at once.
624
+ const OWN_DATAGRAM_WAIT = 2_000;
625
+
626
+ // Whether the browser's WebRTC sends UDP, which goes around a proxy: asked
627
+ // in the tab of throughProxy, with a STUN server of this machine that
628
+ // launch-film listens for itself, for as long as the browser gathers its
629
+ // ways to reach a peer, 1.5 s at most, and a moment after. Started as
630
+ // launch-film starts it, the browser sends none; a Chrome policy
631
+ // (WebRtcIPHandling) or a program that starts it with switches of its own
632
+ // can turn that back, and then its first STUN packet comes at once. The
633
+ // check hears only what reaches that port, so a datagram of launch-film's
634
+ // own is sent there first, from a socket of its own: one that does not
635
+ // come, as behind a firewall that drops UDP to 127.0.0.1, would leave it
636
+ // deaf to the browser's packets too. { udp } for a browser that sends UDP,
637
+ // { deaf } for a check that could not be made, the error of a socket that
638
+ // could not listen or true, else null. As easybrandkit checks its own.
639
+ async function udpPastProxy(page) {
640
+ const udp = dgram.createSocket("udp4");
641
+ const mark = crypto.randomBytes(16);
642
+ let packets = 0;
643
+ let own = false;
644
+ let came;
645
+ const ownCame = new Promise((resolve) => (came = resolve));
646
+ udp.on("message", (message) => {
647
+ if (message.equals(mark)) {
648
+ own = true;
649
+ came();
650
+ } else packets++;
651
+ });
652
+ try {
653
+ await new Promise((resolve, reject) => {
654
+ udp.once("error", reject);
655
+ udp.bind(0, "127.0.0.1", resolve);
656
+ });
657
+ } catch (err) {
658
+ udp.close();
659
+ return { deaf: err };
660
+ }
661
+ udp.on("error", () => {});
662
+ try {
663
+ if (!(await ownDatagram(udp.address().port, mark, ownCame, () => own, OWN_DATAGRAM_WAIT))) return { deaf: true };
664
+ const expression = `(async () => {
665
+ if (typeof RTCPeerConnection === "undefined") return "none";
666
+ const peer = new RTCPeerConnection({ iceServers: [{ urls: "stun:127.0.0.1:${udp.address().port}" }] });
667
+ peer.createDataChannel("launch-film");
668
+ await peer.setLocalDescription(await peer.createOffer());
669
+ await new Promise((done) => {
670
+ if (peer.iceGatheringState === "complete") return done();
671
+ peer.onicegatheringstatechange = () => peer.iceGatheringState === "complete" && done();
672
+ setTimeout(done, 1500);
673
+ });
674
+ peer.close();
675
+ return "asked";
676
+ })()`;
677
+ await page.call("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
678
+ if (!packets) await new Promise((resolve) => setTimeout(resolve, 50));
679
+ return packets > 0 ? { udp: true } : null;
680
+ } finally {
681
+ udp.close();
682
+ }
683
+ }
684
+
685
+ // Whether mark, sent to port on 127.0.0.1 from a socket of its own, came
686
+ // (came resolves then, and own() says so) within ms. A datagram that has
687
+ // come by the time ms runs out is read before that is decided: on a busy
688
+ // machine the timer and the datagram can be due at once, and the timer's
689
+ // turn comes first.
690
+ function ownDatagram(port, mark, came, own, ms) {
691
+ const sender = dgram.createSocket("udp4");
692
+ sender.on("error", () => {});
693
+ let timer;
694
+ const late = new Promise((resolve) => (timer = setTimeout(resolve, ms))).then(() => new Promise((resolve) => setImmediate(resolve)));
695
+ const sent = new Promise((resolve) => sender.send(mark, port, "127.0.0.1", (err) => (err ? resolve() : null)));
696
+ return Promise.race([came, late, sent]).then(() => {
697
+ clearTimeout(timer);
698
+ sender.close();
699
+ return own();
700
+ });
701
+ }
702
+
703
+ // Why the browser that reads a site was not used, when it does not send a
704
+ // request of the check through launch-film's proxy, or its WebRTC could not
705
+ // be checked (see throughProxy).
706
+ function missedProxy({ n, errorText, udp, deaf, unanswered }, proxy) {
707
+ const helps = "lift that policy, or set LAUNCH_FILM_CHROME to Chrome's own program or to another Chrome";
708
+ const risk = "so it was not used: a page could have it reach an address launch-film does not open without launch-film judging that address";
709
+ if (deaf === true) {
710
+ return "launch-film could not check that Chrome's WebRTC sends no UDP past its proxy, as a datagram it sent to a port of its own on 127.0.0.1 did not come there, as a firewall of this machine that drops UDP to 127.0.0.1 makes it do, " +
711
+ "so Chrome was not used: one whose WebRTC sends UDP could have a page send UDP to an address launch-film does not open. Let this machine's programs send UDP to 127.0.0.1";
712
+ }
713
+ if (deaf) return `launch-film could not check that Chrome's WebRTC sends no UDP past its proxy, as it could not listen for UDP on 127.0.0.1 (${deaf.message}), so Chrome was not used`;
714
+ if (udp) return `Chrome's WebRTC sends UDP past launch-film's proxy, as a Chrome policy (WebRtcIPHandling) or a program that starts it with switches of its own makes it do, ${risk}: ${helps}`;
715
+ // One that gave up on its connection to the proxy, as a browser can on
716
+ // one that gets no answer, before any reached the proxy, could not
717
+ // connect to it either.
718
+ if (errorText === "net::ERR_PROXY_CONNECTION_FAILED" || unanswered || (!proxy.accepted && (errorText === "net::ERR_TIMED_OUT" || errorText === "net::ERR_CONNECTION_TIMED_OUT"))) {
719
+ const why = unanswered ? `its connection to 127.0.0.1:${proxy.port} got no answer in ${Math.round(unanswered / 1_000)} s` : errorText;
720
+ return `Chrome could not connect to the proxy its requests go through (${why}), so it was not used: let Chrome connect to 127.0.0.1, which a firewall of this machine can keep it from`;
721
+ }
722
+ if (n === 1) return `Chrome does not send its requests through launch-film's proxy, as a Chrome policy (ProxyMode, ProxySettings or ProxyBypassList) or a program that starts it with switches of its own makes it do, ${risk}: ${helps}`;
723
+ return `Chrome sends its requests for this machine's own addresses past launch-film's proxy, as a Chrome policy (ProxyMode, ProxySettings or ProxyBypassList) or a program that starts it with switches of its own makes it do, ${risk}: ${helps}`;
724
+ }
725
+
726
+ // The notes on the requests the proxy refused while launch-film read a page
727
+ // (proxy.refused, proxy.js): each address once, the first three of them, and
728
+ // how many more there were, at least that many when the proxy did not keep
729
+ // them all (past), as easybrandkit says them. One refused because its name
730
+ // was not found is left out, as a browser of its own would not have reached
731
+ // it either, and so are those Chrome asked for before a page was read, and
732
+ // its own push channel at mtalk.google.com:5228, which no page asks for. The
733
+ // page is said on one line, as a kit's address can hold anything.
734
+ function proxyNotes(refused = [], past = false) {
735
+ const list = refused.filter(({ why, page, what }) => page && why !== UNRESOLVED && what !== "mtalk.google.com:5228");
736
+ const notes = list.slice(0, 3).map(({ page, what, why }) => `While launch-film read ${confine.said(page, 300)}, the browser asked for ${what}, which ${why}: it was not reached.`);
737
+ const more = Math.max(0, list.length - 3) + (past ? 1 : 0);
738
+ if (more > 0) notes.push(`${past ? "At least " : ""}${more} more ${more === 1 ? "address the browser asked for was" : "addresses the browser asked for were"} not reached either.`);
739
+ return notes;
740
+ }
741
+
742
+ // What Chrome says of a connection that cannot be made, by the system's
743
+ // word for it, as it says it of one of its own: the proxy makes the
744
+ // browser's connections (proxy.js), and the browser tells one the proxy
745
+ // could not make only as an empty answer or a tunnel that failed. As
746
+ // easybrandkit tells it.
747
+ const NET_WORDS = {
748
+ ECONNREFUSED: "net::ERR_CONNECTION_REFUSED",
749
+ ECONNRESET: "net::ERR_CONNECTION_RESET",
750
+ ECONNABORTED: "net::ERR_CONNECTION_ABORTED",
751
+ ETIMEDOUT: "net::ERR_CONNECTION_TIMED_OUT",
752
+ EHOSTUNREACH: "net::ERR_ADDRESS_UNREACHABLE",
753
+ ENETUNREACH: "net::ERR_ADDRESS_UNREACHABLE",
754
+ EHOSTDOWN: "net::ERR_ADDRESS_UNREACHABLE",
755
+ EADDRNOTAVAIL: "net::ERR_ADDRESS_INVALID",
756
+ ENOTFOUND: "net::ERR_NAME_NOT_RESOLVED",
757
+ };
758
+
759
+ // What the browser says of a page the proxy could not reach.
760
+ const PROXY_SAID = new Set(["net::ERR_EMPTY_RESPONSE", "net::ERR_TUNNEL_CONNECTION_FAILED"]);
761
+
762
+ // Chrome's word for the last connection to `at` that the proxy could not
763
+ // make, "" when it made it. An answer that is not HTTP as the proxy reads
764
+ // one (an error of Node's parser, HPE_...), which the browser was told
765
+ // nothing of, is told as Chrome tells such an answer of its own.
766
+ function proxyFailure(proxy, at) {
767
+ let key;
768
+ try {
769
+ key = keyOf(new URL(at));
770
+ } catch {
771
+ return "";
772
+ }
773
+ const one = proxy.failed.filter((failed) => failed.key === key).pop();
774
+ if (!one) return "";
775
+ return NET_WORDS[one.code] || (/^HPE_/.test(one.code) ? "net::ERR_INVALID_HTTP_RESPONSE" : "net::ERR_CONNECTION_FAILED");
468
776
  }
469
777
 
470
778
  // ─── the virtual clock ─────────────────────────────────────────────────────
@@ -754,4 +1062,4 @@ async function snapshots(pages) {
754
1062
  return out;
755
1063
  }
756
1064
 
757
- module.exports = { findChrome, onPath, chromeArgs, launch, openPage, renderPage, stillOf, snapshots, evaluate, standIns: openerFolder, withoutOpeners, offTheDesktop, busPath, opened, CLOCK, PAGE_FILE_MAX, OPENERS };
1065
+ module.exports = { findChrome, onPath, chromeArgs, launch, openPage, renderPage, stillOf, snapshots, evaluate, standIns: openerFolder, withoutOpeners, offTheDesktop, busPath, opened, proxyFailure, proxyNotes, CLOCK, PAGE_FILE_MAX, OPENERS, PROXY_SAID };
package/src/confine.js CHANGED
@@ -143,10 +143,18 @@ function filmListed(file, named) {
143
143
 
144
144
  // A name as a message shows it, on one line: a line break or another
145
145
  // control character in it is written escaped, as a line of its own could
146
- // pass for one of launch-film's. A film.json, a brand.json or a cues.json can
147
- // name anything.
148
- const CONTROL = /[\p{Cc}\u2028\u2029]/u;
149
- const oneLine = (name) => String(name).replace(new RegExp(CONTROL.source, "gu"), (c) => ({ "\n": "\\n", "\r": "\\r", "\t": "\\t" })[c] || `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
146
+ // pass for one of launch-film's, and so is a format character, a bidi
147
+ // control, a zero-width one or a tag character (U+E0000 to U+E007F), which
148
+ // shows nothing or turns what follows around, as text a reader does not see
149
+ // could pass for none. Each is written by its code point, past U+FFFF as
150
+ // \u{...}. A film.json, a brand.json or a cues.json can name anything.
151
+ const CONTROL = /[\p{Cc}\p{Cf}\u2028\u2029]/u;
152
+ const oneLine = (name) => String(name).replace(new RegExp(CONTROL.source, "gu"), (c) => {
153
+ const plain = { "\n": "\\n", "\r": "\\r", "\t": "\\t" }[c];
154
+ if (plain) return plain;
155
+ const code = c.codePointAt(0);
156
+ return code > 0xffff ? `\\u{${code.toString(16)}}` : `\\u${code.toString(16).padStart(4, "0")}`;
157
+ });
150
158
 
151
159
  // A name as it is said in a message: on one line (oneLine), and cut in the
152
160
  // middle when it is longer than `room`, as one made to slip past a check,