launch-film 0.3.0 → 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/LICENSE +1 -0
- package/README.md +20 -3
- package/THIRD_PARTY.md +1 -1
- package/bin/launch-film.js +76 -6
- package/package.json +1 -1
- package/skills/launch-film/SKILL.md +13 -11
- package/src/address.js +893 -0
- package/src/brand.js +43 -9
- package/src/chrome.js +327 -19
- package/src/confine.js +12 -4
- package/src/dial.js +157 -0
- package/src/film.js +8 -4
- package/src/fonts.js +11 -5
- package/src/out.js +1 -1
- package/src/proxy.js +416 -0
- package/src/stills.js +2 -2
- package/src/store.js +43 -19
- package/src/web.js +169 -0
- package/src/words.js +67 -15
package/src/dial.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// How a run connects to a host: the browser's requests through the kit's
|
|
4
|
+
// proxy (see proxy.js) and the kit's own requests alike (see stores.js and
|
|
5
|
+
// facts.js), each to the addresses the run's rule took for that host (see
|
|
6
|
+
// address.js route) and to no other. A host with more than one address is
|
|
7
|
+
// connected to with each attempt left to go on until it connects or fails,
|
|
8
|
+
// as the browser leaves its own: one attempt per address, the families
|
|
9
|
+
// taking turns, the next started 250 ms after the one before, or at once
|
|
10
|
+
// when every one started before it has failed. The first to connect is
|
|
11
|
+
// taken and the others are ended. Node's own connection to more than one
|
|
12
|
+
// address ends every attempt but the last after 250 ms, so a public site
|
|
13
|
+
// whose name has an IPv6 address this machine has no route to, and whose
|
|
14
|
+
// IPv4 address takes longer than that to answer, as a site far away does,
|
|
15
|
+
// failed with ETIMEDOUT, and so did a site of this machine given as
|
|
16
|
+
// localhost while this process was held a moment, where the browser by
|
|
17
|
+
// itself connects.
|
|
18
|
+
|
|
19
|
+
const net = require("net");
|
|
20
|
+
const tls = require("tls");
|
|
21
|
+
|
|
22
|
+
// Where each connection to one address is made: the one place a run makes
|
|
23
|
+
// one. name is the host the connection is for, a name or the address
|
|
24
|
+
// itself. Tests put their own servers in place of the addresses here.
|
|
25
|
+
// Nagle's algorithm is off on it, as the browser has it on its own
|
|
26
|
+
// connections: with it on, the browser's small writes through the proxy,
|
|
27
|
+
// as the frames of HTTP/2 and the records of TLS, could wait for the site
|
|
28
|
+
// to acknowledge the one before, and a page loaded more slowly than the
|
|
29
|
+
// browser loads it by itself.
|
|
30
|
+
const wire = { dial: (address, port, name) => net.connect({ host: address, port, autoSelectFamily: false, noDelay: true }) };
|
|
31
|
+
|
|
32
|
+
// How long an attempt is waited for before the next one starts, as RFC 8305
|
|
33
|
+
// has it.
|
|
34
|
+
const ATTEMPT_DELAY = 250;
|
|
35
|
+
|
|
36
|
+
// The addresses in the order they are tried: the first one's family first,
|
|
37
|
+
// then the two families in turn, each in the order it was found in.
|
|
38
|
+
function inTurns(addresses) {
|
|
39
|
+
const list = addresses.map((address) => String(address).replace(/^\[|\]$/g, "")).filter((address) => net.isIP(address));
|
|
40
|
+
if (!list.length) return [];
|
|
41
|
+
const first = list.filter((address) => net.isIP(address) === net.isIP(list[0]));
|
|
42
|
+
const other = list.filter((address) => net.isIP(address) !== net.isIP(list[0]));
|
|
43
|
+
const order = [];
|
|
44
|
+
for (let i = 0; i < Math.max(first.length, other.length); i++) {
|
|
45
|
+
if (i < first.length) order.push(first[i]);
|
|
46
|
+
if (i < other.length) order.push(other[i]);
|
|
47
|
+
}
|
|
48
|
+
return order;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// A connection to port at one of addresses, the IP addresses the rule took
|
|
52
|
+
// for name: resolves to the socket that connected first. hold(socket) is
|
|
53
|
+
// given each attempt's socket as it is made, as the proxy keeps every
|
|
54
|
+
// socket it makes to end it with itself. An aborted signal ends the
|
|
55
|
+
// attempts under way and fails with its reason. Fails once every attempt
|
|
56
|
+
// has failed, with the error of the first address tried, as a connection
|
|
57
|
+
// to that address alone fails, or with ENOTFOUND for no address at all.
|
|
58
|
+
function dialFirst(addresses, port, { name = "", hold = (socket) => socket, signal = null } = {}) {
|
|
59
|
+
return new Promise((resolve, reject) => {
|
|
60
|
+
const order = inTurns(addresses);
|
|
61
|
+
if (!order.length) return reject(Object.assign(new Error(`${name || "the host"} was not found`), { code: "ENOTFOUND", hostname: name }));
|
|
62
|
+
const sockets = [];
|
|
63
|
+
const errors = [];
|
|
64
|
+
let started = 0;
|
|
65
|
+
let failed = 0;
|
|
66
|
+
let done = false;
|
|
67
|
+
let timer = null;
|
|
68
|
+
const finish = (err, socket) => {
|
|
69
|
+
if (done) return;
|
|
70
|
+
done = true;
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
if (signal) signal.removeEventListener("abort", aborted);
|
|
73
|
+
for (const one of sockets) if (one !== socket) one.destroy();
|
|
74
|
+
if (err) reject(err);
|
|
75
|
+
else resolve(socket);
|
|
76
|
+
};
|
|
77
|
+
function aborted() {
|
|
78
|
+
finish(signal.reason || Object.assign(new Error("The connection was given up"), { name: "AbortError", code: "ABORT_ERR" }));
|
|
79
|
+
}
|
|
80
|
+
const start = () => {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
if (done || started >= order.length) return;
|
|
83
|
+
const at = started++;
|
|
84
|
+
let socket;
|
|
85
|
+
try {
|
|
86
|
+
socket = hold(wire.dial(order[at], port, name || order[at]));
|
|
87
|
+
} catch (err) {
|
|
88
|
+
return lost(at, err);
|
|
89
|
+
}
|
|
90
|
+
sockets.push(socket);
|
|
91
|
+
// Each attempt ends once: it connects, fails, or is closed, as one
|
|
92
|
+
// the proxy ends with itself is.
|
|
93
|
+
let over = false;
|
|
94
|
+
const end = (err) => {
|
|
95
|
+
if (over) return;
|
|
96
|
+
over = true;
|
|
97
|
+
socket.removeListener("close", closed);
|
|
98
|
+
lost(at, err);
|
|
99
|
+
};
|
|
100
|
+
const closed = () => end(Object.assign(new Error(`The connection to ${order[at]} was closed before it was made`), { code: "ECONNABORTED" }));
|
|
101
|
+
socket.on("error", () => {});
|
|
102
|
+
socket.once("error", end);
|
|
103
|
+
socket.once("close", closed);
|
|
104
|
+
socket.once("connect", () => {
|
|
105
|
+
if (over) return;
|
|
106
|
+
over = true;
|
|
107
|
+
socket.removeListener("error", end);
|
|
108
|
+
socket.removeListener("close", closed);
|
|
109
|
+
finish(null, socket);
|
|
110
|
+
});
|
|
111
|
+
if (started < order.length) timer = setTimeout(start, ATTEMPT_DELAY);
|
|
112
|
+
};
|
|
113
|
+
// An attempt that failed: the next one starts at once when no other is
|
|
114
|
+
// under way, and the connection fails once none is left.
|
|
115
|
+
function lost(at, err) {
|
|
116
|
+
if (done) return;
|
|
117
|
+
errors[at] = err;
|
|
118
|
+
failed++;
|
|
119
|
+
if (failed === order.length) return finish(errors[0] || err);
|
|
120
|
+
if (failed === started) start();
|
|
121
|
+
}
|
|
122
|
+
if (signal) {
|
|
123
|
+
if (signal.aborted) return aborted();
|
|
124
|
+
signal.addEventListener("abort", aborted);
|
|
125
|
+
}
|
|
126
|
+
start();
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The options of a request the kit makes itself to url, over http or https,
|
|
131
|
+
// that connect it to one of the addresses addressesOf() resolves to, the
|
|
132
|
+
// ones the rule took for url's host (see dialFirst). It is given no agent:
|
|
133
|
+
// Node.js sends a request on its global agent through the proxy HTTP_PROXY
|
|
134
|
+
// or HTTPS_PROXY names once NODE_USE_ENV_PROXY or --use-env-proxy is set,
|
|
135
|
+
// without the lookup the request was given, and that proxy looks the name
|
|
136
|
+
// up again for itself and connects wherever its answer points. Over https,
|
|
137
|
+
// TLS starts on the connection for url's host.
|
|
138
|
+
function judgedRequest(url, addressesOf, { signal = null } = {}) {
|
|
139
|
+
const secure = url.protocol === "https:";
|
|
140
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
141
|
+
const port = Number(url.port || (secure ? 443 : 80));
|
|
142
|
+
return {
|
|
143
|
+
port,
|
|
144
|
+
defaultPort: secure ? 443 : 80,
|
|
145
|
+
createConnection: (options, made) => {
|
|
146
|
+
Promise.resolve()
|
|
147
|
+
.then(addressesOf)
|
|
148
|
+
.then((addresses) => dialFirst(addresses, port, { name: host, signal }))
|
|
149
|
+
.then(
|
|
150
|
+
(socket) => made(null, secure ? tls.connect({ socket, host, ...(net.isIP(host) ? {} : { servername: host }) }) : socket),
|
|
151
|
+
(err) => made(err),
|
|
152
|
+
);
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = { wire, dialFirst, judgedRequest, ATTEMPT_DELAY };
|
package/src/film.js
CHANGED
|
@@ -166,9 +166,13 @@ function musicOf(value, dir, problems) {
|
|
|
166
166
|
// reads \\ there as one \. Inside double quotes cmd.exe, PowerShell and Git
|
|
167
167
|
// Bash still expand %, $, ` and !, so a path that holds one gets null. So
|
|
168
168
|
// does one with a line break or another control character in it, which
|
|
169
|
-
// would break the line the command is printed on.
|
|
169
|
+
// would break the line the command is printed on. A format character, as
|
|
170
|
+
// the zero-width non-joiner of Persian spelling, breaks no line and is
|
|
171
|
+
// quoted as any other (BREAKS), where a message writes it by its code point
|
|
172
|
+
// (confine.js, CONTROL).
|
|
173
|
+
const BREAKS = /[\p{Cc}\u2028\u2029]/u;
|
|
170
174
|
function shellWord(file, platform = process.platform) {
|
|
171
|
-
if (
|
|
175
|
+
if (BREAKS.test(file)) return null;
|
|
172
176
|
if (platform === "win32") {
|
|
173
177
|
const name = String(file).replace(/\\/g, "/");
|
|
174
178
|
if (/^[\w.:/-]+$/.test(name)) return name;
|
|
@@ -178,7 +182,7 @@ function shellWord(file, platform = process.platform) {
|
|
|
178
182
|
}
|
|
179
183
|
|
|
180
184
|
// A name as a message shows it, on one line (confine.js).
|
|
181
|
-
const {
|
|
185
|
+
const { oneLine } = confine;
|
|
182
186
|
|
|
183
187
|
// The musicfit command that fits a track to the film, `seconds` long with
|
|
184
188
|
// its hit at `hit`, into `folder`, as the refusal of a short track gives it:
|
|
@@ -651,7 +655,7 @@ async function renderInto(job, file, { film, brand, clips }, { out, track, jobs,
|
|
|
651
655
|
const notes = [...(brand ? brand.notes : [])];
|
|
652
656
|
try {
|
|
653
657
|
const fonts = await resolveFonts({ style: look, font: colours.headingFont || "", bodyFont: colours.bodyFont || "" }, { offline });
|
|
654
|
-
if (fonts.missing.length) notes.push(`
|
|
658
|
+
if (fonts.missing.length) notes.push(`Could not be had from Google Fonts, so the look's own typeface stood in: ${[...new Set(fonts.missing)].join(", ")}.`);
|
|
655
659
|
// Every clip but the last runs on under the next one's crossfade.
|
|
656
660
|
let at = 0;
|
|
657
661
|
clips.forEach((c, i) => {
|
package/src/fonts.js
CHANGED
|
@@ -12,11 +12,16 @@
|
|
|
12
12
|
// others, other people's: a name is asked for, kept and noted as missing in
|
|
13
13
|
// one form, so that a name spelt otherwise, with two spaces, which Google
|
|
14
14
|
// refuses, notes no other family as missing.
|
|
15
|
+
//
|
|
16
|
+
// Google's CSS and each face it names are asked for as the run's rule for
|
|
17
|
+
// the addresses it opens lets them (web.js): an address it refuses gives no
|
|
18
|
+
// face, as one Google does not answer for.
|
|
15
19
|
|
|
16
20
|
const fs = require("fs");
|
|
17
21
|
const os = require("os");
|
|
18
22
|
const path = require("path");
|
|
19
23
|
const crypto = require("crypto");
|
|
24
|
+
const web = require("./web");
|
|
20
25
|
|
|
21
26
|
const MISSING_FOR = 24 * 60 * 60 * 1000;
|
|
22
27
|
|
|
@@ -30,10 +35,11 @@ function cacheDir() {
|
|
|
30
35
|
// A browser's user agent: Google Fonts answers it with WOFF2 faces.
|
|
31
36
|
const UA = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36" };
|
|
32
37
|
|
|
38
|
+
// The bytes of an answer of Google's.
|
|
33
39
|
async function get(url) {
|
|
34
|
-
const res = await
|
|
40
|
+
const res = await web.get(url, { headers: UA, signal: AbortSignal.timeout(10_000) });
|
|
35
41
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
36
|
-
return res;
|
|
42
|
+
return res.body;
|
|
37
43
|
}
|
|
38
44
|
|
|
39
45
|
// @font-face CSS for the family at the weights asked (the nearest it has
|
|
@@ -62,10 +68,10 @@ async function loadFont(family, weights = [400, 700]) {
|
|
|
62
68
|
const base = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(name).replace(/%20/g, "+")}`;
|
|
63
69
|
let css;
|
|
64
70
|
try {
|
|
65
|
-
css =
|
|
71
|
+
css = web.textOf(await get(`${base}:wght@${weights.join(";")}&display=block`));
|
|
66
72
|
} catch {
|
|
67
73
|
try {
|
|
68
|
-
css =
|
|
74
|
+
css = web.textOf(await get(`${base}&display=block`));
|
|
69
75
|
} catch (err) {
|
|
70
76
|
// 400 is Google's answer for a family it does not have.
|
|
71
77
|
if (/HTTP 400/.test(err.message)) fs.writeFileSync(missing, "");
|
|
@@ -78,7 +84,7 @@ async function loadFont(family, weights = [400, 700]) {
|
|
|
78
84
|
for (const block of blocks) {
|
|
79
85
|
const url = (/url\((https:[^)]+)\)/.exec(block) || [])[1];
|
|
80
86
|
if (!url) continue;
|
|
81
|
-
const data =
|
|
87
|
+
const data = (await get(url)).toString("base64");
|
|
82
88
|
out += block.slice(block.indexOf("@font-face")).replace(url, `data:font/woff2;base64,${data}`) + "\n";
|
|
83
89
|
}
|
|
84
90
|
if (out) {
|
package/src/out.js
CHANGED
|
@@ -1091,7 +1091,7 @@ function below(pids) {
|
|
|
1091
1091
|
// easybrandkit runs a Chrome of its own, and 0.4.0 on a stop neither ends
|
|
1092
1092
|
// it nor removes its profile: a stop sent to launch-film alone left that
|
|
1093
1093
|
// Chrome running for good, and Ctrl-C left its profile in the temp folder.
|
|
1094
|
-
// 0.4.
|
|
1094
|
+
// 0.4.3, which launch-film runs through npx, ends its own on a stop, but one
|
|
1095
1095
|
// on PATH or named by LAUNCH_FILM_EASYBRANDKIT can be older, and a stop
|
|
1096
1096
|
// ends easybrandkit once STOP_WAIT has passed, whatever it is doing.
|
|
1097
1097
|
// So the processes below one started with { watch: true } are looked at
|
package/src/proxy.js
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// The proxy every request of a run's browser goes through: a small HTTP
|
|
4
|
+
// proxy of the kit's own on 127.0.0.1, started before the browser, which is
|
|
5
|
+
// started with it as its proxy for every address, this machine's own among
|
|
6
|
+
// them, with every name failing in its own lookup and with its own DNS over
|
|
7
|
+
// HTTPS off (see chrome.js launch). So the browser looks no name up and
|
|
8
|
+
// connects nowhere itself, but to a server of DNS over HTTPS that a Chrome
|
|
9
|
+
// policy names at 127.0.0.1: whatever asks for an address, a page, a frame,
|
|
10
|
+
// a picture, a script, the data a page fetches, a WebSocket, a service
|
|
11
|
+
// worker, a prefetch, the fetch of a site certificate's issuer or a page's
|
|
12
|
+
// WebAuthn check, the request comes here. It takes plain http requests,
|
|
13
|
+
// which the browser sends with the whole address, and CONNECT tunnels, which
|
|
14
|
+
// it opens for https and for WebSockets, and nothing else. Each is judged by
|
|
15
|
+
// the run's rule (see address.js guardFor, route), which looks each name up
|
|
16
|
+
// once a run, and is connected only to an address that rule took for it,
|
|
17
|
+
// without asking the DNS again. What the rule refuses gets a 403 and no
|
|
18
|
+
// connection, and is kept with its address and why for the kit's notes (see
|
|
19
|
+
// chrome.js proxyNotes).
|
|
20
|
+
//
|
|
21
|
+
// It listens on 127.0.0.1 alone, on a port the system picks, for as long as
|
|
22
|
+
// its browser runs. A request it gets that is not one of these, as one
|
|
23
|
+
// that names no host, gets a 400.
|
|
24
|
+
|
|
25
|
+
const fs = require("fs");
|
|
26
|
+
const http = require("http");
|
|
27
|
+
const crypto = require("crypto");
|
|
28
|
+
const { dialFirst } = require("./dial");
|
|
29
|
+
|
|
30
|
+
// The tables of this machine's TCP sockets on Linux, each with the uid of
|
|
31
|
+
// the user whose socket it is.
|
|
32
|
+
const TCP_TABLES = ["/proc/net/tcp", "/proc/net/tcp6"];
|
|
33
|
+
// 127.0.0.1 as those tables write an address, in either byte order, also
|
|
34
|
+
// mapped into IPv6 (::ffff:127.0.0.1).
|
|
35
|
+
const TABLE_LOOPBACK = /^(?:0100007F|7F000001|0000000000000000FFFF00000100007F|00000000000000000000FFFF7F000001):[0-9A-F]{4}$/;
|
|
36
|
+
|
|
37
|
+
// Whose program a connection to the proxy comes from, on Linux: the uid
|
|
38
|
+
// those tables give the socket at its other end, which is on 127.0.0.1 as
|
|
39
|
+
// well, as the proxy listens there alone, found by the ports the connection
|
|
40
|
+
// had when the proxy took it (see startProxy's hold), as a closed one has
|
|
41
|
+
// none. "gone" when the tables could be read and hold no such socket, as
|
|
42
|
+
// for a program that has closed it, and null where it cannot be told: on
|
|
43
|
+
// another system, or with no table to read.
|
|
44
|
+
async function ownerOf(socket) {
|
|
45
|
+
const ports = socket.easybrandkitPorts || { remote: socket.remotePort, local: socket.localPort };
|
|
46
|
+
if (process.platform !== "linux" || !ports.remote || !ports.local) return null;
|
|
47
|
+
const hex = (port) => Number(port).toString(16).toUpperCase().padStart(4, "0");
|
|
48
|
+
const [mine, theirs] = [hex(ports.remote), hex(ports.local)];
|
|
49
|
+
let read = false;
|
|
50
|
+
for (const file of TCP_TABLES) {
|
|
51
|
+
let table;
|
|
52
|
+
try {
|
|
53
|
+
table = await fs.promises.readFile(file, "latin1");
|
|
54
|
+
} catch {
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
read = true;
|
|
58
|
+
for (const line of table.split("\n")) {
|
|
59
|
+
const fields = line.trim().split(/\s+/);
|
|
60
|
+
if (fields.length > 7 && fields[1].endsWith(`:${mine}`) && fields[2].endsWith(`:${theirs}`) && TABLE_LOOPBACK.test(fields[1]) && TABLE_LOOPBACK.test(fields[2])) return Number(fields[7]);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return read ? "gone" : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Whose program a connection to the proxy comes from (see ownerOf). Tests
|
|
67
|
+
// put their own owners here. The proxy connects to the addresses the rule
|
|
68
|
+
// took for a host as every connection of a run is made (see dial.js), so a
|
|
69
|
+
// name is never looked up again.
|
|
70
|
+
const wire = { owner: ownerOf };
|
|
71
|
+
|
|
72
|
+
// The headers that belong to one connection and not to the request or the
|
|
73
|
+
// answer it carries, which the proxy does not pass on, with those a
|
|
74
|
+
// Connection header names.
|
|
75
|
+
const HOP = new Set(["connection", "proxy-connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"]);
|
|
76
|
+
|
|
77
|
+
function passedOn(raw) {
|
|
78
|
+
const named = new Set();
|
|
79
|
+
for (let i = 0; i < raw.length; i += 2) {
|
|
80
|
+
if (/^(proxy-)?connection$/i.test(raw[i])) for (const name of String(raw[i + 1]).split(",")) named.add(name.trim().toLowerCase());
|
|
81
|
+
}
|
|
82
|
+
const out = [];
|
|
83
|
+
for (let i = 0; i < raw.length; i += 2) {
|
|
84
|
+
const name = String(raw[i]).toLowerCase();
|
|
85
|
+
if (!HOP.has(name) && !named.has(name)) out.push(raw[i], raw[i + 1]);
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// The largest headers taken, of a request and of an answer: Node's own 16
|
|
91
|
+
// KB would refuse a site's large cookies or policies that the browser takes.
|
|
92
|
+
const HEADER_MOST = 256 * 1024;
|
|
93
|
+
|
|
94
|
+
// The headers of a site's answer that are passed on to the browser: those
|
|
95
|
+
// passedOn keeps that Node can write, and no Content-Length, as the proxy
|
|
96
|
+
// gives each answer its own framing (see answer). A site's answer is read
|
|
97
|
+
// the way the browser reads one (insecureHTTPParser), which takes headers
|
|
98
|
+
// Node does not write, as one with a control character in its value; such
|
|
99
|
+
// a header is left out, where it ended the whole answer.
|
|
100
|
+
function answerHeaders(raw) {
|
|
101
|
+
const kept = passedOn(raw);
|
|
102
|
+
const out = [];
|
|
103
|
+
for (let i = 0; i < kept.length; i += 2) {
|
|
104
|
+
if (/^content-length$/i.test(kept[i])) continue;
|
|
105
|
+
try {
|
|
106
|
+
http.validateHeaderName(kept[i]);
|
|
107
|
+
http.validateHeaderValue(kept[i], kept[i + 1]);
|
|
108
|
+
} catch {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
out.push(kept[i], kept[i + 1]);
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// A reason phrase Node can write, else none, for which it writes the one it
|
|
117
|
+
// knows for the status.
|
|
118
|
+
const reasonOf = (text) => (/^[\t\x20-\x7e\x80-\xff]*$/.test(String(text)) ? text : undefined);
|
|
119
|
+
|
|
120
|
+
// How many refused addresses are kept, each once, and how many failed
|
|
121
|
+
// connections.
|
|
122
|
+
const KEEP_REFUSED = 50;
|
|
123
|
+
const KEEP_FAILED = 100;
|
|
124
|
+
|
|
125
|
+
// What a request the proxy got stands for: the address it judges, as a URL,
|
|
126
|
+
// and how it is told in the kit's notes, the whole address of a plain http
|
|
127
|
+
// request and the host and port of a tunnel.
|
|
128
|
+
function tunnelUrl(authority) {
|
|
129
|
+
const form = /^(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._~!$&'()*+,;=-]+):(\d{1,5})$/.exec(authority);
|
|
130
|
+
if (!form || Number(form[2]) < 1 || Number(form[2]) > 65535) return null;
|
|
131
|
+
try {
|
|
132
|
+
const url = new URL(`https://${authority}/`);
|
|
133
|
+
const port = url.port || "443";
|
|
134
|
+
return port === String(Number(form[2])) && !url.username && !url.password ? url : null;
|
|
135
|
+
} catch {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// The port of a web address, the scheme's own when it names none.
|
|
141
|
+
const portOf = (url) => url.port || (url.protocol === "https:" ? "443" : "80");
|
|
142
|
+
|
|
143
|
+
// A host as a connection names it: an IPv6 address without its brackets.
|
|
144
|
+
const plainHost = (url) => url.hostname.replace(/^\[|\]$/g, "");
|
|
145
|
+
|
|
146
|
+
// Where a failed connection is kept: its host and port.
|
|
147
|
+
const keyOf = (url) => `${plainHost(url).toLowerCase()}:${portOf(url)}`;
|
|
148
|
+
|
|
149
|
+
// The proxy's own name, under .invalid, which no DNS answers: the browser
|
|
150
|
+
// is asked for it to show that its requests come here (see chrome.js
|
|
151
|
+
// throughProxy), and its own push channel is pointed at it (see chrome.js
|
|
152
|
+
// launch). A request for it, or for this machine on the proxy's own port,
|
|
153
|
+
// is the proxy's own: answered here, and kept nowhere but as a probe.
|
|
154
|
+
const OWN_NAME = "easybrandkit-proxy.invalid";
|
|
155
|
+
|
|
156
|
+
// Why a request is refused when the browser was started with no rule.
|
|
157
|
+
const NO_RULE = "is not opened by a browser the kit gave no rule for the addresses it opens";
|
|
158
|
+
// Why one is refused when the rule itself failed.
|
|
159
|
+
const NOT_JUDGED = "could not be judged";
|
|
160
|
+
// What a tunnel or a request whose address cannot be read is.
|
|
161
|
+
const UNREADABLE = "is not an address launch-film can read";
|
|
162
|
+
|
|
163
|
+
// Starts the proxy for a run's rule (guard, see address.js guardFor; null
|
|
164
|
+
// for a browser that is to open no web page) and resolves to it, once it
|
|
165
|
+
// listens:
|
|
166
|
+
// port the port it listens on, on 127.0.0.1
|
|
167
|
+
// token a word of its own, which the probes of chrome.js put in
|
|
168
|
+
// their paths: a request for /<token>/<n> that comes to it
|
|
169
|
+
// as a proxy request it answers itself, and keeps n in
|
|
170
|
+
// through
|
|
171
|
+
// accepted how many connections it has taken
|
|
172
|
+
// reading the page the kit reads, which the kit sets as it opens one
|
|
173
|
+
// refused what it refused: { what, why, page }, each address once,
|
|
174
|
+
// the first 50, refusedMore saying that there were more
|
|
175
|
+
// failed the connections it could not make to addresses the rule
|
|
176
|
+
// took, and those a server reset before it answered:
|
|
177
|
+
// { n, key, code }, the last 100, key being host:port and n
|
|
178
|
+
// counting them from 1, failedCount being the last n
|
|
179
|
+
// close() stops it and every connection it holds
|
|
180
|
+
function startProxy(guard) {
|
|
181
|
+
const token = crypto.randomBytes(12).toString("hex");
|
|
182
|
+
const sockets = new Set();
|
|
183
|
+
const proxy = { port: 0, token, through: new Set(), accepted: 0, reading: "", refused: [], refusedMore: false, failed: [], failedCount: 0, closed: false };
|
|
184
|
+
const hold = (socket) => {
|
|
185
|
+
sockets.add(socket);
|
|
186
|
+
socket.easybrandkitPorts = { remote: socket.remotePort, local: socket.localPort };
|
|
187
|
+
socket.on("close", () => sockets.delete(socket));
|
|
188
|
+
socket.on("error", () => {});
|
|
189
|
+
if (proxy.closed) socket.destroy();
|
|
190
|
+
return socket;
|
|
191
|
+
};
|
|
192
|
+
const route = async (raw) => {
|
|
193
|
+
if (!guard) return { why: NO_RULE, addresses: [] };
|
|
194
|
+
try {
|
|
195
|
+
return await guard.route(raw);
|
|
196
|
+
} catch {
|
|
197
|
+
return { why: NOT_JUDGED, addresses: [] };
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
// A request refused, kept for the kit's notes when it came from a program
|
|
201
|
+
// of this user's, as the browser is: any program of this machine can
|
|
202
|
+
// connect to the proxy, as to any port of 127.0.0.1, and what another
|
|
203
|
+
// user's asks is refused as any request is, but not named in the notes as
|
|
204
|
+
// the browser's. Where that cannot be told, as on another system than
|
|
205
|
+
// Linux, it is kept. The table is read before the refusal is answered,
|
|
206
|
+
// while the connection is still there.
|
|
207
|
+
const own = process.getuid ? process.getuid() : null;
|
|
208
|
+
const refuse = async (what, why, socket) => {
|
|
209
|
+
const page = proxy.reading;
|
|
210
|
+
if (proxy.refused.some((one) => one.what === what) || (proxy.refusedMore && proxy.refused.length >= KEEP_REFUSED)) return;
|
|
211
|
+
if (own !== null && socket) {
|
|
212
|
+
let owner = null;
|
|
213
|
+
try {
|
|
214
|
+
owner = await wire.owner(socket);
|
|
215
|
+
} catch {
|
|
216
|
+
// Cannot be told.
|
|
217
|
+
}
|
|
218
|
+
if (owner !== null && owner !== own) return;
|
|
219
|
+
}
|
|
220
|
+
if (proxy.refused.some((one) => one.what === what)) return;
|
|
221
|
+
if (proxy.refused.length < KEEP_REFUSED) proxy.refused.push({ what, why, page });
|
|
222
|
+
else proxy.refusedMore = true;
|
|
223
|
+
};
|
|
224
|
+
const failed = (url, err) => {
|
|
225
|
+
proxy.failed.push({ n: ++proxy.failedCount, key: keyOf(url), code: String((err && err.code) || "") });
|
|
226
|
+
if (proxy.failed.length > KEEP_FAILED) proxy.failed.shift();
|
|
227
|
+
if (err) err.kept = true;
|
|
228
|
+
};
|
|
229
|
+
// A connection to url's host and port at one of addresses, the ones the
|
|
230
|
+
// rule took for it (see dial.js): the socket, once connected. Every
|
|
231
|
+
// attempt is held, so close ends those still under way too.
|
|
232
|
+
const connect = (url, addresses, signal = null) => dialFirst(addresses, Number(portOf(url)), { name: plainHost(url), hold, signal });
|
|
233
|
+
// Whether an address is the proxy's own.
|
|
234
|
+
const ownAddress = (url) => url.hostname === OWN_NAME || (["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) && portOf(url) === String(proxy.port));
|
|
235
|
+
// The probes of chrome.js: /<token>/<n>, answered here.
|
|
236
|
+
const probe = (path) => {
|
|
237
|
+
const n = new RegExp(`^/${token}/(\\d)$`).exec(path);
|
|
238
|
+
if (!n) return false;
|
|
239
|
+
proxy.through.add(Number(n[1]));
|
|
240
|
+
return true;
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
// The connections of plain http requests with no body, kept open between
|
|
244
|
+
// requests to the same host and port, as the browser keeps its own: a
|
|
245
|
+
// page of a site under development that loads its modules one request
|
|
246
|
+
// each, a few hundred of them, loaded half as fast with a connection of
|
|
247
|
+
// its own for each. Agent keeps them by the host as the request names it,
|
|
248
|
+
// a name or an IP address, and its port, and makes each by connect, so to
|
|
249
|
+
// an address the rule took for that host and held (see hold), which close
|
|
250
|
+
// ends; one idle for 5 s is closed.
|
|
251
|
+
const agent = new http.Agent({ keepAlive: true, timeout: 5_000 });
|
|
252
|
+
agent.createConnection = (options, made) => {
|
|
253
|
+
connect(options.easybrandkitUrl, options.easybrandkitAddresses).then(
|
|
254
|
+
(socket) => made(null, socket),
|
|
255
|
+
(err) => {
|
|
256
|
+
failed(options.easybrandkitUrl, err);
|
|
257
|
+
made(err);
|
|
258
|
+
},
|
|
259
|
+
);
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
// A plain http request, the whole address in its first line.
|
|
263
|
+
const answer = async (req, res) => {
|
|
264
|
+
res.sendDate = false;
|
|
265
|
+
const target = String(req.url || "");
|
|
266
|
+
// A request with no whole address came to this port as an address of
|
|
267
|
+
// its own, past the proxy, and is answered with nothing.
|
|
268
|
+
if (!/^http:\/\//i.test(target)) return res.writeHead(400, { "content-length": "0", connection: "close" }).end();
|
|
269
|
+
let url;
|
|
270
|
+
try {
|
|
271
|
+
url = new URL(target);
|
|
272
|
+
} catch {
|
|
273
|
+
await refuse(target.slice(0, 300), UNREADABLE, req.socket);
|
|
274
|
+
return res.writeHead(403, { "content-length": "0" }).end();
|
|
275
|
+
}
|
|
276
|
+
if (ownAddress(url)) {
|
|
277
|
+
if (probe(url.pathname)) return res.writeHead(200, { "content-type": "text/plain", "content-length": "0" }).end();
|
|
278
|
+
return res.writeHead(404, { "content-length": "0" }).end();
|
|
279
|
+
}
|
|
280
|
+
const { why, addresses } = await route(url.href);
|
|
281
|
+
if (why) {
|
|
282
|
+
await refuse(url.href.slice(0, 300), why, req.socket);
|
|
283
|
+
return res.writeHead(403, { "content-length": "0" }).end();
|
|
284
|
+
}
|
|
285
|
+
if (req.socket.destroyed) return;
|
|
286
|
+
// The request as the browser sent it, for the address's own host, which
|
|
287
|
+
// the connection already reaches.
|
|
288
|
+
const headers = ["Host", url.host];
|
|
289
|
+
const kept = passedOn(req.rawHeaders);
|
|
290
|
+
for (let i = 0; i < kept.length; i += 2) if (!/^host$/i.test(kept[i])) headers.push(kept[i], kept[i + 1]);
|
|
291
|
+
// A request with a body goes on a connection of its own, which is
|
|
292
|
+
// closed after it: one kept open that the site has closed meanwhile
|
|
293
|
+
// fails it, and its body cannot be sent again.
|
|
294
|
+
const bodiless = req.headers["content-length"] === undefined && req.headers["transfer-encoding"] === undefined;
|
|
295
|
+
const options = { method: req.method, path: `${url.pathname}${url.search}`, headers, setHost: false, maxHeaderSize: HEADER_MOST, insecureHTTPParser: true, host: plainHost(url), port: Number(portOf(url)), easybrandkitUrl: url, easybrandkitAddresses: addresses };
|
|
296
|
+
let answered = false;
|
|
297
|
+
let gone = false;
|
|
298
|
+
let asked;
|
|
299
|
+
// A connection that was kept open can have been closed by the site just
|
|
300
|
+
// as the request went out on it: the request is sent once more, on a
|
|
301
|
+
// connection of its own. A request with no agent connects only through
|
|
302
|
+
// createConnection; agent: false would have Node make one of its own,
|
|
303
|
+
// which looks the name up again.
|
|
304
|
+
const send = (again) => {
|
|
305
|
+
const one = http.request(bodiless && !again ? { ...options, agent } : { ...options, headers: [...headers, "Connection", "close"], createConnection: (opts, made) => agent.createConnection(opts, made) });
|
|
306
|
+
asked = one;
|
|
307
|
+
one.on("response", (answer) => {
|
|
308
|
+
answered = true;
|
|
309
|
+
try {
|
|
310
|
+
res.writeHead(answer.statusCode, reasonOf(answer.statusMessage), answerHeaders(answer.rawHeaders));
|
|
311
|
+
} catch {
|
|
312
|
+
// A status Node does not write, as one under 100.
|
|
313
|
+
failed(url, { code: "HPE_INVALID_STATUS" });
|
|
314
|
+
one.destroy();
|
|
315
|
+
return req.socket.destroy();
|
|
316
|
+
}
|
|
317
|
+
answer.pipe(res);
|
|
318
|
+
// An answer cut short by the site, which Node.js tells as an error
|
|
319
|
+
// of the answer, is cut short for the browser too.
|
|
320
|
+
answer.on("error", () => res.destroy());
|
|
321
|
+
});
|
|
322
|
+
// A server that closes the connection before it answers is told by
|
|
323
|
+
// the browser as an empty answer, as it would be told without the
|
|
324
|
+
// proxy; one that resets it, a system error, is kept as that, and so
|
|
325
|
+
// is an answer that is not HTTP as the browser reads it, which the
|
|
326
|
+
// browser is told nothing of (see chrome.js navigate). Node.js tells a
|
|
327
|
+
// request's error once.
|
|
328
|
+
one.on("error", (err) => {
|
|
329
|
+
if (answered || gone) return res.destroy();
|
|
330
|
+
if (bodiless && !again && one.reusedSocket && !err.kept) return send(true);
|
|
331
|
+
if (err && !err.kept && (err.syscall || /^HPE_/.test(String(err.code)))) failed(url, err);
|
|
332
|
+
req.socket.destroy();
|
|
333
|
+
});
|
|
334
|
+
if (bodiless) one.end();
|
|
335
|
+
else req.pipe(one);
|
|
336
|
+
};
|
|
337
|
+
send(false);
|
|
338
|
+
// The browser that gives the request up ends its connection too.
|
|
339
|
+
res.on("close", () => {
|
|
340
|
+
gone = true;
|
|
341
|
+
if (!res.writableFinished) asked.destroy();
|
|
342
|
+
});
|
|
343
|
+
};
|
|
344
|
+
// A CONNECT tunnel to the host and port it names.
|
|
345
|
+
const tunnel = async (req, socket, head) => {
|
|
346
|
+
const authority = String(req.url || "");
|
|
347
|
+
const url = tunnelUrl(authority);
|
|
348
|
+
if (!url) {
|
|
349
|
+
await refuse(authority.slice(0, 300), UNREADABLE, socket);
|
|
350
|
+
return socket.end("HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n");
|
|
351
|
+
}
|
|
352
|
+
if (ownAddress(url)) return socket.end("HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n");
|
|
353
|
+
const what = `${url.hostname}:${portOf(url)}`;
|
|
354
|
+
// A tunnel carries https, or a WebSocket, to the host and port it
|
|
355
|
+
// names: it is judged as an https address there.
|
|
356
|
+
const { why, addresses } = await route(url.href);
|
|
357
|
+
if (why) {
|
|
358
|
+
await refuse(what, why, socket);
|
|
359
|
+
return socket.end("HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n");
|
|
360
|
+
}
|
|
361
|
+
// A browser that gives the tunnel up while it is made ends the attempts
|
|
362
|
+
// under way.
|
|
363
|
+
const given = new AbortController();
|
|
364
|
+
const up = () => given.abort();
|
|
365
|
+
socket.once("close", up);
|
|
366
|
+
let upstream;
|
|
367
|
+
try {
|
|
368
|
+
upstream = await connect(url, addresses, given.signal);
|
|
369
|
+
} catch (err) {
|
|
370
|
+
if (given.signal.aborted) return;
|
|
371
|
+
socket.removeListener("close", up);
|
|
372
|
+
failed(url, err);
|
|
373
|
+
return socket.end("HTTP/1.1 502 Bad Gateway\r\ncontent-length: 0\r\n\r\n");
|
|
374
|
+
}
|
|
375
|
+
socket.removeListener("close", up);
|
|
376
|
+
if (socket.destroyed) return upstream.destroy();
|
|
377
|
+
socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
|
|
378
|
+
if (head && head.length) upstream.write(head);
|
|
379
|
+
upstream.pipe(socket);
|
|
380
|
+
socket.pipe(upstream);
|
|
381
|
+
socket.on("close", () => upstream.destroy());
|
|
382
|
+
upstream.on("close", () => socket.destroy());
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
const server = http.createServer({ maxHeaderSize: HEADER_MOST });
|
|
386
|
+
server.on("connection", (socket) => {
|
|
387
|
+
proxy.accepted++;
|
|
388
|
+
hold(socket);
|
|
389
|
+
});
|
|
390
|
+
server.on("clientError", (err, socket) => socket.destroy());
|
|
391
|
+
// What fails on the way ends that connection, and nothing else.
|
|
392
|
+
server.on("request", (req, res) => answer(req, res).catch(() => req.socket.destroy()));
|
|
393
|
+
server.on("connect", (req, socket, head) => tunnel(req, socket, head).catch(() => socket.destroy()));
|
|
394
|
+
// A request that asks for another protocol on its own connection is no
|
|
395
|
+
// request the browser sends a proxy: it sends a WebSocket through a
|
|
396
|
+
// tunnel.
|
|
397
|
+
server.on("upgrade", (req, socket) => socket.end("HTTP/1.1 501 Not Implemented\r\ncontent-length: 0\r\n\r\n"));
|
|
398
|
+
|
|
399
|
+
proxy.close = () => {
|
|
400
|
+
if (proxy.closed) return;
|
|
401
|
+
proxy.closed = true;
|
|
402
|
+
server.close();
|
|
403
|
+
for (const socket of sockets) socket.destroy();
|
|
404
|
+
};
|
|
405
|
+
return new Promise((resolve, reject) => {
|
|
406
|
+
server.once("error", reject);
|
|
407
|
+
server.listen(0, "127.0.0.1", () => {
|
|
408
|
+
server.removeListener("error", reject);
|
|
409
|
+
server.on("error", () => {});
|
|
410
|
+
proxy.port = server.address().port;
|
|
411
|
+
resolve(proxy);
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
module.exports = { startProxy, wire, keyOf, OWN_NAME, UNREADABLE };
|