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/src/address.js ADDED
@@ -0,0 +1,893 @@
1
+ "use strict";
2
+
3
+ // Which addresses a run opens. The address the user gives is opened whatever
4
+ // its host and port, and so are the pages on its scheme, host and port: a
5
+ // site on this machine, as http://localhost:3000, is the user's own choice.
6
+ // Any other address a run opens is one it was not given: a page it chose
7
+ // (the home page of a deeper address, the website a store listing names, a
8
+ // site another source named, a menu page with --facts), each hop of a
9
+ // redirect, a page's own move, a frame or a window a page opens, and
10
+ // robots.txt with each of its redirects. Such an address is opened only on
11
+ // port 80 or 443 and only on the public internet, and not at an address of
12
+ // this machine's own there (see ownIp): no document the browser loads and
13
+ // no request the kit makes itself goes to another program of this machine
14
+ // or of a private network, to another port of a public host, or to a
15
+ // router's page or a cloud server's metadata. The same rule holds for
16
+ // every request the browser makes, whatever makes it: a page's pictures,
17
+ // scripts and data, its WebSockets, a service worker's fetch, a prefetch,
18
+ // the fetch of a certificate's issuer and a page's WebAuthn check all go
19
+ // through the kit's own proxy (see proxy.js), which judges each by it and
20
+ // connects only to an address it took.
21
+ //
22
+ // MAKERSMCP_REFUSE_ADDRESSES, a comma list of IP addresses and CIDR ranges,
23
+ // names more addresses that the host the kit runs on refuses, as a server's
24
+ // own public addresses, which lead back inside its network. They are refused
25
+ // for every address a run opens, the one given included.
26
+ //
27
+ // A host name is judged by every address it is found at here, looked up once
28
+ // a run, and a connection, the browser's through the proxy and the kit's
29
+ // own, goes only to one of those (see guardFor).
30
+
31
+ const fs = require("fs");
32
+ const net = require("net");
33
+ const dns = require("dns");
34
+ const os = require("os");
35
+ const util = require("util");
36
+ const { domainToASCII, domainToUnicode } = require("url");
37
+
38
+ // The ranges that are not on the public internet, as MakersMCP's worker
39
+ // counts them: this machine, private and shared networks, link-local, and
40
+ // in IPv4 the ranges kept for protocol assignments (192.0.0.0/24), 6to4
41
+ // relays (192.88.99.0/24), documentation, benchmarks, multicast and later
42
+ // use; in IPv6 multicast, the documentation range 2001:db8::/32, the discard
43
+ // range 100::/64, Teredo (2001::/32), whose addresses hold the IPv4
44
+ // addresses of a server and of a client, either of which can be this
45
+ // machine or its network, NAT64's local use prefix (64:ff9b:1::/48) and the
46
+ // site local range (fec0::/10). The other IPv6 ranges count as public, the
47
+ // newer documentation range 3fff::/20 and the benchmarking one, 2001:2::/48,
48
+ // among them, as the worker counts them too. The test cases are in
49
+ // test/address-cases.json.
50
+ const V4 = [
51
+ ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16],
52
+ ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.88.99.0", 24], ["192.168.0.0", 16],
53
+ ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24], ["224.0.0.0", 4], ["240.0.0.0", 4],
54
+ ];
55
+ const V6 = [
56
+ ["::", 128], ["::1", 128], ["64:ff9b:1::", 48], ["100::", 64], ["2001::", 32], ["2001:db8::", 32],
57
+ ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8],
58
+ ];
59
+ const blocked4 = new net.BlockList();
60
+ for (const [address, prefix] of V4) blocked4.addSubnet(address, prefix, "ipv4");
61
+ const blocked6 = new net.BlockList();
62
+ for (const [address, prefix] of V6) blocked6.addSubnet(address, prefix, "ipv6");
63
+
64
+ // An IP address as written, without the brackets of one in an address and
65
+ // without a zone (%eth0), which is no part of it.
66
+ const plainIp = (raw) => String(raw || "").replace(/^\[|\]$/g, "").replace(/%.*$/, "");
67
+
68
+ // An IPv6 address as its eight 16 bit groups, or null: a dotted IPv4 tail
69
+ // is two groups.
70
+ function groupsOf(address) {
71
+ let text = plainIp(address).toLowerCase();
72
+ const tail = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(text);
73
+ if (tail) {
74
+ const [a, b, c, d] = tail.slice(1).map(Number);
75
+ text = `${text.slice(0, tail.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;
76
+ }
77
+ const halves = text.split("::");
78
+ if (halves.length > 2) return null;
79
+ const part = (half) => (half ? half.split(":") : []);
80
+ const head = part(halves[0]);
81
+ const rest = halves.length === 2 ? part(halves[1]) : [];
82
+ const fill = halves.length === 2 ? 8 - head.length - rest.length : 0;
83
+ const groups = [...head, ...Array(Math.max(0, fill)).fill("0"), ...rest];
84
+ if (groups.length !== 8 || groups.some((group) => !/^[0-9a-f]{1,4}$/.test(group))) return null;
85
+ return groups.map((group) => parseInt(group, 16));
86
+ }
87
+
88
+ // The IPv4 address an IPv6 address holds, dotted, or "": mapped
89
+ // (::ffff:a.b.c.d), compatible (::a.b.c.d, past :: and ::1), translated
90
+ // (::ffff:0:a.b.c.d), 6to4 (2002:aabb:ccdd::/48) and NAT64's well known
91
+ // prefix (64:ff9b::/96), as a network with IPv6 only gives a name that has
92
+ // only IPv4. Each reaches that IPv4 address wherever it is routed, so it is
93
+ // judged as that address: ::7f00:1, 2002:7f00:1:: and ::ffff:0:7f00:1 are
94
+ // 127.0.0.1, and a NAT64 address of a public site is as public as the site.
95
+ function heldIpv4(raw) {
96
+ const address = plainIp(raw);
97
+ if (net.isIP(address) !== 6) return "";
98
+ const groups = groupsOf(address);
99
+ if (!groups) return "";
100
+ const v4 = (high, low) => [high >> 8, high & 255, low >> 8, low & 255].join(".");
101
+ const zero = (from, to) => groups.slice(from, to).every((group) => group === 0);
102
+ if (zero(0, 5) && groups[5] === 0xffff) return v4(groups[6], groups[7]);
103
+ if (zero(0, 6) && (groups[6] !== 0 || groups[7] > 1)) return v4(groups[6], groups[7]);
104
+ if (zero(0, 4) && groups[4] === 0xffff && groups[5] === 0) return v4(groups[6], groups[7]);
105
+ if (groups[0] === 0x2002) return v4(groups[1], groups[2]);
106
+ if (groups[0] === 0x64 && groups[1] === 0xff9b && zero(2, 6)) return v4(groups[6], groups[7]);
107
+ return "";
108
+ }
109
+
110
+ // The IPv4 addresses a Teredo address (2001::/32) holds, dotted: its
111
+ // server's, the 32 bits after 2001:0, and its client's, the last 32 bits
112
+ // with each bit turned over. Either can be this machine or the network of
113
+ // the host the kit runs on, and a machine with a Teredo client reaches such
114
+ // an address through them. [] for any other address.
115
+ function teredoIpv4(groups) {
116
+ if (groups[0] !== 0x2001 || groups[1] !== 0) return [];
117
+ const v4 = (high, low) => [high >> 8, high & 255, low >> 8, low & 255].join(".");
118
+ return [v4(groups[2], groups[3]), v4(groups[6] ^ 0xffff, groups[7] ^ 0xffff)];
119
+ }
120
+
121
+ // Whether an IPv6 address is in NAT64's local use prefix, 64:ff9b:1::/48,
122
+ // where a network puts the IPv4 address its translator reaches in a way of
123
+ // its own choosing: in the last 32 bits, in another of the places RFC 6052
124
+ // gives, or by a table of its own.
125
+ const localNat64 = (groups) => groups[0] === 0x64 && groups[1] === 0xff9b && groups[2] === 1;
126
+
127
+ // The IPv4 address or range an IPv6 address or range holds, in one of the
128
+ // forms heldIpv4 reads or NAT64's local use prefix, as [address, prefix], or
129
+ // null: the IPv4 part is the last 32 bits of the mapped, compatible,
130
+ // translated and NAT64 forms, the local use prefix's too, as
131
+ // 64:ff9b:1::185.137.215.163 writes it, so a range of them at /96 or longer
132
+ // holds the IPv4 range of its last bits, and the 32 bits after 2002 in 6to4,
133
+ // so a range of those at /16 or longer holds the IPv4 range of its next
134
+ // bits, /32 from /48 on. A shorter range holds none. A compatible range that
135
+ // holds only :: and ::1, which are no IPv4 address, holds none.
136
+ // ::ffff:185.137.215.0/120 holds 185.137.215.0/24, and ::ffff:0:0/96 every
137
+ // IPv4 address, 0.0.0.0/0. As easyscreenshotkit reads it.
138
+ function heldRange(groups, bits) {
139
+ const v4 = (high, low) => [high >> 8, high & 255, low >> 8, low & 255].join(".");
140
+ const zero = (from, to) => groups.slice(from, to).every((group) => group === 0);
141
+ if (bits >= 96) {
142
+ const prefix = bits - 96;
143
+ if ((zero(0, 5) && groups[5] === 0xffff) || (zero(0, 4) && groups[4] === 0xffff && groups[5] === 0) || (groups[0] === 0x64 && groups[1] === 0xff9b && zero(2, 6)) || localNat64(groups)) return [v4(groups[6], groups[7]), prefix];
144
+ if (zero(0, 6)) {
145
+ const low = ((groups[6] << 16) | groups[7]) >>> 0;
146
+ const size = 2 ** (32 - prefix);
147
+ const first = low - (low % size);
148
+ return first + size - 1 >= 2 ? [v4(groups[6], groups[7]), prefix] : null;
149
+ }
150
+ }
151
+ if (groups[0] === 0x2002 && bits >= 16) return [v4(groups[1], groups[2]), Math.min(bits, 48) - 16];
152
+ return null;
153
+ }
154
+
155
+ // Whether an IP address is on the public internet. Anything that is no IP
156
+ // address is not.
157
+ function isPublicAddress(raw) {
158
+ const address = plainIp(raw);
159
+ const family = net.isIP(address);
160
+ if (family === 4) return !blocked4.check(address, "ipv4");
161
+ if (family !== 6) return false;
162
+ const held = heldIpv4(address);
163
+ if (held && !isPublicAddress(held)) return false;
164
+ return !blocked6.check(address, "ipv6");
165
+ }
166
+
167
+ // Whether an IP address is this machine's own: "machine" for one of the
168
+ // addresses it holds, "network" for one of the IPv6 network of an address
169
+ // of an interface on the public internet (see machineNow), else "". A
170
+ // machine on an IPv6 network holds global addresses of its own
171
+ // (SLAAC, or DHCPv6), temporary ones among them that come and go, and a
172
+ // server can hold a public IPv4 address on an interface: such an address is
173
+ // on the public internet by its range, so a site that read it off the
174
+ // kit's own connection had the browser load a frame, a picture or a fetch()
175
+ // from a service of this machine that listens on all its addresses, and a
176
+ // site that sent its visitors there had the kit saved as that service's,
177
+ // with no word. A global IPv6 network is mostly the user's own, whose
178
+ // router and other machines answer there, and on a server whose provider
179
+ // puts other customers' servers in it, as a DigitalOcean droplet's /64,
180
+ // theirs, which are refused all the same (the README's Limits say so); the
181
+ // rest of a public IPv4 range on an interface is other people's servers, so
182
+ // in IPv4 the address alone. An IPv6 address that holds an IPv4 one is
183
+ // judged by that IPv4 address (see heldIpv4) and by itself, as any other
184
+ // IPv6 address: a network that gives this machine a 6to4 address builds it
185
+ // from the IPv4 address of its 6to4 router, which another box holds, and
186
+ // judged by that IPv4 address alone, the machine's own 6to4 address and
187
+ // every device of its 6to4 network, the router at the prefix's ::1 among
188
+ // them, were taken for the public internet. An address that leads into
189
+ // this machine or its network from outside, as the public IPv4 address of
190
+ // a router that turns a connection back inside, is no address it holds,
191
+ // and cannot be told from any other, nor can the rest of the user's own
192
+ // network at addresses on the public internet outside the networks of its
193
+ // interfaces, as another IPv6 network of the same site:
194
+ // MAKERSMCP_REFUSE_ADDRESSES is for those (the README's Limits say so).
195
+ function ownIp(raw) {
196
+ const address = plainIp(raw);
197
+ const family = net.isIP(address);
198
+ if (!family) return "";
199
+ const { mine, networks } = machineNow();
200
+ if (family === 4) return mine.check(address, "ipv4") ? "machine" : "";
201
+ const held = heldIpv4(address);
202
+ if ((held && mine.check(held, "ipv4")) || mine.check(address, "ipv6")) return "machine";
203
+ return networks.check(address, "ipv6") ? "network" : "";
204
+ }
205
+
206
+ // This machine's own addresses (mine) and the IPv6 networks of them
207
+ // (networks), read again once a second has passed since the last reading
208
+ // (wait, see below), or the clock went back, or a function that reads them
209
+ // is another, as a test puts one in its place. os.networkInterfaces() lists
210
+ // the addresses of the interfaces that are up and have a link alone, as
211
+ // Node.js's libuv leaves the others out, on every system. On Linux the
212
+ // kernel takes a connection to more of them for one to this machine, which
213
+ // its own files list (see kernelAddresses), and those are read too, as
214
+ // easyscreenshotkit reads them: an address of an interface that is up with
215
+ // no link, as a cable out, a veth whose other end is down or a bridge whose
216
+ // containers or virtual machines are all stopped, of an interface that is
217
+ // down, and every address of a range routed to the machine itself, as a
218
+ // pool of addresses for a proxy is set up (ip route add local ... dev lo).
219
+ // Read from the interfaces alone, each was taken for an address on the
220
+ // public internet away from the address given: a page's pictures, frames
221
+ // and fetch() reached a service of this machine that listens on all its
222
+ // addresses there, through the kit's proxy, what a fetch() read went into
223
+ // brand.json, and a site that sent its visitors there had the kit saved as
224
+ // that service's, with no word.
225
+ //
226
+ // The proxy judges every address of every request the browser makes, and
227
+ // each reading takes longer the more interfaces the machine has, as a
228
+ // Docker host has one for each container: read at each judgement, as
229
+ // easyscreenshotkit first read them, they were read 4001 times for one load
230
+ // of a news site's home page, and with 200 interfaces such a page loaded 3
231
+ // to 5 times more slowly, the main thread busy reading them. The kernel's
232
+ // lists of its routes take longer to read the more routes it holds (see
233
+ // KERNEL_ROUTES), so a machine of many is read again only once a second has
234
+ // passed for each ROUTES_A_SECOND of them, where that is longer.
235
+ //
236
+ // A reading of the interfaces that the system refuses, as where a Linux
237
+ // service's RestrictAddressFamilies leaves out AF_NETLINK, or where this
238
+ // process has as many files open as it may, leaves the last one of the same
239
+ // functions in its place, as this machine's addresses seldom change while a
240
+ // run goes. With none, it gives why not (unread, see interfacesUnread), and
241
+ // a run stops before any work: where the error was let go, the machine was
242
+ // taken for one with no addresses, so every address of this machine and of
243
+ // its IPv6 networks was opened away from the address given, and a name that
244
+ // answered with one of them beside an address on the public internet was
245
+ // no name whose answers mix, with no word.
246
+ //
247
+ // The IPv6 network of an address on the public internet is the prefix its
248
+ // interface gives it, held to /48 at the widest, as a wider one would take
249
+ // in other people's networks, and to /64 at the narrowest, as IPv6
250
+ // networks are /64 (RFC 7421): a DHCPv6 client holds the address it gets
251
+ // at /128, and the network's /64 comes from the router's advertisement as
252
+ // a route alone, which the kit does not take for a network (of the
253
+ // kernel's routes it takes the local ones alone, see kernelAddresses), so
254
+ // with the interface's prefix alone the router at the prefix's ::1 and
255
+ // every other device of such a network counted as the public internet. ::1
256
+ // and the other addresses that are not on the public internet give none:
257
+ // ::1 is held at /128, and the /64 around it holds addresses the rule takes
258
+ // for public by their range.
259
+ const INTERFACES_WAIT = 1_000;
260
+ const ROUTES_A_SECOND = 20_000;
261
+ let machine = null;
262
+
263
+ // The kernel's lists of this machine's addresses and routes, on Linux, and
264
+ // how the kit reads one (read(file), the file's text), which a test puts
265
+ // another function in place of.
266
+ const KERNEL_FILES = {
267
+ trieStats: "/proc/net/fib_triestat",
268
+ trie: "/proc/net/fib_trie",
269
+ inet6: "/proc/net/if_inet6",
270
+ routeStats6: "/proc/net/rt6_stats",
271
+ route6: "/proc/net/ipv6_route",
272
+ };
273
+ const kernel = { read: (file) => fs.readFileSync(file, "latin1") };
274
+
275
+ // The most routes the kernel's list of them is read with: it lists them a
276
+ // page at a time, each page counted from the first route again, so the time
277
+ // a reading takes grows with the square of their number, the run's main
278
+ // thread doing nothing else meanwhile. On a busy machine here
279
+ // /proc/net/fib_trie took 5 to 7 ms to read with 2,000 IPv4 routes, which
280
+ // /proc/net/fib_triestat counts as 4,000 where the kernel keeps its local
281
+ // and main tables as one, 150 ms with 20,000 and 75 s with 300,000;
282
+ // /proc/net/ipv6_route took 7 ms with 2,000 IPv6 routes and 1.7 to 2.1 s
283
+ // with 20,000. A machine of more, as a router, is read by its interfaces
284
+ // that are up and have a link, and in IPv6 by the addresses of all its
285
+ // interfaces too (/proc/net/if_inet6, a line for each address).
286
+ const KERNEL_ROUTES = 4_000;
287
+
288
+ // An IPv6 address as the kernel's files write it, 32 hex digits, in the
289
+ // form a BlockList takes, or "".
290
+ function hexIpv6(hex) {
291
+ if (!/^[0-9a-f]{32}$/i.test(hex)) return "";
292
+ return hex.match(/.{4}/g).join(":");
293
+ }
294
+
295
+ // The text each of the kernel's files last gave, for the function that read
296
+ // it: a file that cannot be read is taken as it was last read, as a reading
297
+ // of the interfaces that the system refuses is (see machineNow), so a moment
298
+ // where this process has as many files open as it may does not have the
299
+ // addresses it lists taken for the public internet until it is read again.
300
+ // A file never read, as where /proc is not there or the system does not let
301
+ // it be read, is taken as empty, and the interfaces stand alone for what it
302
+ // lists.
303
+ let kernelTexts = { read: null, texts: {} };
304
+
305
+ // The addresses the kernel takes a connection to for one to this machine,
306
+ // as [address, prefix] pairs: in IPv4 (four) every LOCAL entry of the
307
+ // tables every connection is looked up in by the kernel's own rules, local,
308
+ // main and default (the parts of /proc/net/fib_trie after "Local:", "Main:"
309
+ // and "Id 253:"), an address of an interface, whatever its state, or a range
310
+ // routed to the machine itself; in IPv6 (six) every address of an
311
+ // interface, whatever its state (/proc/net/if_inet6), and every route of
312
+ // the kind local (RTF_LOCAL in /proc/net/ipv6_route) of /48 or longer; and
313
+ // each address of an interface with the prefix its interface gives it
314
+ // (prefixes), for its network (see machineNow). A transparent proxy routes
315
+ // every address to the machine itself in a table of its own, 0.0.0.0/0 and
316
+ // ::/0, which only the packets it marks go by, as a rule of its own says:
317
+ // taken, it made every address of the internet one of this machine's. In
318
+ // IPv4 such a table is a part of fib_trie of its own, as "Id 100:"; the
319
+ // kernel names no table for an IPv6 route, so a local route shorter than
320
+ // /48 is left out. The routes are listed only where the kernel's counts of
321
+ // them (/proc/net/fib_triestat, /proc/net/rt6_stats) are KERNEL_ROUTES at
322
+ // most. Empty on any other system; routes: how many routes the kernel
323
+ // counted.
324
+ function kernelAddresses() {
325
+ const found = { four: [], six: [], prefixes: [], routes: 0 };
326
+ if (process.platform !== "linux") return found;
327
+ if (kernelTexts.read !== kernel.read) kernelTexts = { read: kernel.read, texts: {} };
328
+ const { texts } = kernelTexts;
329
+ const text = (file) => {
330
+ try {
331
+ texts[file] = String(kernel.read(file));
332
+ } catch {
333
+ // As it was last read, or empty (see kernelTexts).
334
+ }
335
+ return texts[file] || "";
336
+ };
337
+ // fib_triestat names each table and its count of prefixes, the routes
338
+ // fib_trie lists for it.
339
+ const counts4 = [...text(KERNEL_FILES.trieStats).matchAll(/^\s*Prefixes:\s*(\d+)\s*$/gm)].map((m) => Number(m[1]));
340
+ const routes4 = counts4.reduce((sum, n) => sum + n, 0);
341
+ // rt6_stats: seven counts in hex, the fourth the routes.
342
+ const counts6 = text(KERNEL_FILES.routeStats6).trim().split(/\s+/);
343
+ const routes6 = /^[0-9a-f]+$/i.test(counts6[3] || "") ? parseInt(counts6[3], 16) : Infinity;
344
+ found.routes = routes4 + (Number.isFinite(routes6) ? routes6 : 0);
345
+ let local = false;
346
+ let leaf = "";
347
+ for (const line of counts4.length && routes4 <= KERNEL_ROUTES ? text(KERNEL_FILES.trie).split("\n") : []) {
348
+ if (/^\S/.test(line)) {
349
+ local = /^(?:Local|Main|Id 253):/.test(line);
350
+ leaf = "";
351
+ continue;
352
+ }
353
+ if (!local) continue;
354
+ const key = /^\s*\|-- (\d{1,3}(?:\.\d{1,3}){3})\s*$/.exec(line);
355
+ if (key) {
356
+ leaf = key[1];
357
+ continue;
358
+ }
359
+ if (/^\s*\+--/.test(line)) {
360
+ leaf = "";
361
+ continue;
362
+ }
363
+ const entry = /^\s*\/(\d{1,2}) \S+ (\S+)/.exec(line);
364
+ if (entry && leaf && entry[2] === "LOCAL" && net.isIP(leaf) === 4 && Number(entry[1]) <= 32) found.four.push([leaf, Number(entry[1])]);
365
+ }
366
+ for (const line of text(KERNEL_FILES.inet6).split("\n")) {
367
+ const [hex, , bits] = line.trim().split(/\s+/);
368
+ const at = hexIpv6(hex || "");
369
+ if (!at) continue;
370
+ found.six.push([at, 128]);
371
+ found.prefixes.push([at, parseInt(bits, 16)]);
372
+ }
373
+ for (const line of routes6 <= KERNEL_ROUTES ? text(KERNEL_FILES.route6).split("\n") : []) {
374
+ const fields = line.trim().split(/\s+/);
375
+ const at = hexIpv6(fields[0] || "");
376
+ const prefix = parseInt(fields[1], 16);
377
+ if (!at || !(prefix >= 48 && prefix <= 128) || !/^[0-9a-f]{8}$/i.test(fields[8] || "")) continue;
378
+ if (parseInt(fields[8], 16) & 0x80000000) found.six.push([at, prefix]);
379
+ }
380
+ return found;
381
+ }
382
+
383
+ function machineNow() {
384
+ const now = Date.now();
385
+ if (machine && machine.read === os.networkInterfaces && machine.kernel === kernel.read && now >= machine.at && now - machine.at < machine.wait) return machine;
386
+ const read = os.networkInterfaces;
387
+ let interfaces = {};
388
+ try {
389
+ interfaces = read.call(os);
390
+ } catch (err) {
391
+ const last = machine && machine.read === read && machine.kernel === kernel.read ? machine : null;
392
+ machine = last ? { ...last, at: now } : { at: now, read, kernel: kernel.read, wait: INTERFACES_WAIT, mine: new net.BlockList(), networks: new net.BlockList(), unread: unreadWhy(err) };
393
+ return machine;
394
+ }
395
+ const mine = new net.BlockList();
396
+ const networks = new net.BlockList();
397
+ // The network of an IPv6 address on the public internet (see above); one
398
+ // whose prefix is not given is held alone, at /128.
399
+ const network = (at, bits) => {
400
+ if (isPublicAddress(at)) networks.addSubnet(at, Math.min(64, Math.max(48, bits || 128)), "ipv6");
401
+ };
402
+ for (const list of Object.values(interfaces || {})) {
403
+ for (const one of list || []) {
404
+ const at = plainIp(one && one.address);
405
+ const kind = net.isIP(at);
406
+ if (!kind) continue;
407
+ mine.addAddress(at, kind === 4 ? "ipv4" : "ipv6");
408
+ if (kind === 6) network(at, Number(String(one.cidr || "").split("/")[1]));
409
+ }
410
+ }
411
+ const { four, six, prefixes, routes } = kernelAddresses();
412
+ for (const [at, bits] of four) mine.addSubnet(at, bits, "ipv4");
413
+ for (const [at, bits] of six) mine.addSubnet(at, bits, "ipv6");
414
+ for (const [at, bits] of prefixes) network(at, bits);
415
+ // wait: how long this reading is kept.
416
+ machine = { at: now, read, kernel: kernel.read, wait: Math.max(INTERFACES_WAIT, (routes / ROUTES_A_SECOND) * 1_000), mine, networks };
417
+ return machine;
418
+ }
419
+
420
+ // Why this machine's network interfaces could not be read, as
421
+ // { code, words }: the system's words for the error by its code, as "too
422
+ // many open files (EMFILE)", where Node.js names it by its number alone, as
423
+ // "Unknown system error 24", or its message cut to 200 characters, its
424
+ // control characters made spaces, when it has no number.
425
+ function unreadWhy(err) {
426
+ const number = err && Number.isInteger(err.errno) ? -Math.abs(err.errno) : 0;
427
+ const known = number ? util.getSystemErrorMap().get(number) : null;
428
+ if (known) return { code: known[0], words: `${known[1]} (${known[0]})` };
429
+ return { code: "", words: String((err && err.message) || err).replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 200) };
430
+ }
431
+
432
+ // Why this machine's network interfaces cannot be read, as { code, words },
433
+ // or null where they could be read, now or earlier in the run (see
434
+ // machineNow): a run stops before any work then, as it could not tell this
435
+ // machine's own addresses from those on the public internet (see kit.js
436
+ // makeKit).
437
+ const interfacesUnread = () => machineNow().unread || null;
438
+
439
+ // Where an IP address stands for a run away from the address given: "" for
440
+ // one on the public internet that is not this machine's own, else "not
441
+ // public", or "machine" or "network" for one on the public internet that
442
+ // is this machine's (see ownIp). Each such address is refused there.
443
+ function standingOf(raw) {
444
+ if (!isPublicAddress(raw)) return "not public";
445
+ return ownIp(raw);
446
+ }
447
+
448
+ // The names a browser takes for this machine without asking the DNS:
449
+ // localhost, and any name under it.
450
+ const localName = (host) => /(^|\.)localhost$/i.test(host);
451
+
452
+ // The names the system can look up on this machine's own networks, by
453
+ // multicast: a name under .local, which goes to multicast DNS on each of
454
+ // them (RFC 6762), as nss-mdns hands it to avahi on a Linux desktop, and a
455
+ // name of one label, which goes to LLMNR where the system has it on, as
456
+ // Windows and systemd-resolved can. Looked up for a page, a picture at
457
+ // such a name put a question of the page's choosing on the user's own
458
+ // networks, and how soon it failed told the page whether a device there
459
+ // answers to that name. Neither is a name on the public internet, so one
460
+ // the run was not given is refused by its form, before any lookup.
461
+ const linkName = (host) => !net.isIP(host) && (/(^|\.)local$/i.test(host) || !host.includes("."));
462
+
463
+ // Whether a host has a label of broken punycode: one that starts with xn--
464
+ // and does not decode to a name that is written back as that label, as
465
+ // xn--a, xn--, xn--zz, or xn--a-, which decodes to a. The URL parser of
466
+ // Node.js 22.22 refuses such a host, that of Node.js 22.23 reads xn--a- as
467
+ // a host, and that of Node.js 24 keeps each as it is written, and the
468
+ // browser reads them all the same: the kit reads each as no address, so its
469
+ // rule is the same whatever Node.js it runs on. A label that decodes, as
470
+ // xn--bcher-kva, is the name it stands for.
471
+ const brokenPunycode = (host) =>
472
+ String(host)
473
+ .split(".")
474
+ .some((label) => {
475
+ if (!/^xn--/i.test(label)) return false;
476
+ const name = domainToUnicode(label);
477
+ return !name || /^xn--/i.test(name) || domainToASCII(name) !== label.toLowerCase();
478
+ });
479
+
480
+ // A web address as the URL parser here reads it, or null for one it cannot
481
+ // read: one whose host has a label of broken punycode is not read either.
482
+ function readUrl(raw) {
483
+ let url;
484
+ try {
485
+ url = new URL(String(raw));
486
+ } catch {
487
+ return null;
488
+ }
489
+ return brokenPunycode(url.hostname) ? null : url;
490
+ }
491
+
492
+ // An address's host as it is judged: in small letters, without the brackets
493
+ // of an IPv6 address and without its last dots, as 127.0.0.1.. is still
494
+ // 127.0.0.1 to the browser. What is left is read again as the URL parser
495
+ // reads a host, so a short or other IPv4 form with its dots taken off is
496
+ // the address it is: 127.1.., 0x7f.1.. and 192.168.1.. are 127.0.0.1,
497
+ // 127.0.0.1 and 192.168.0.1, where the URL parser leaves them names, as it
498
+ // does any host with two dots or more after it.
499
+ function bare(url) {
500
+ const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
501
+ const plain = host.replace(/\.+$/, "");
502
+ if (plain === host || net.isIP(plain)) return plain;
503
+ try {
504
+ const again = new URL(`http://${plain}/`).hostname;
505
+ return net.isIP(again) === 4 ? again : plain;
506
+ } catch {
507
+ return plain;
508
+ }
509
+ }
510
+
511
+ // This machine's loopback addresses, in the order a connection to
512
+ // localhost tries them, ::1 first, as this machine's resolver and the
513
+ // browser order them: with 127.0.0.1 first, a site under development that
514
+ // listens on ::1 alone, as Node.js's own listen(port, "localhost") binds
515
+ // on Ubuntu, was passed over for another program that listens on
516
+ // 127.0.0.1 on the same port, whose pages the run then saved with no word.
517
+ const LOOPBACK = ["::1", "127.0.0.1"];
518
+
519
+ // The addresses of this machine that one of its own names for itself
520
+ // stands for, for a host as it is judged (see bare): localhost both of its
521
+ // loopback addresses (see LOOPBACK), and 127.0.0.1 and ::1 themselves; null
522
+ // for any other host. A name under localhost is none of them: a router on
523
+ // this machine, as Traefik or Caddy, serves each such name, as
524
+ // app1.localhost or traefik.localhost, as a site of its own. Nor are
525
+ // another address of 127.0.0.0/8, where another program can listen, as on
526
+ // 127.0.0.2 or 127.0.0.53, 0.0.0.0 and ::, which a connection takes for
527
+ // 127.0.0.1 and ::1 but a server there can tell apart by the name a
528
+ // request is for, and an IPv6 form of 127.0.0.1, as ::ffff:127.0.0.1.
529
+ function machineAddresses(host) {
530
+ if (host === "localhost") return [...LOOPBACK];
531
+ return host === "127.0.0.1" || host === "::1" ? [host] : null;
532
+ }
533
+
534
+ // The addresses of this machine that two hosts both stand for (see
535
+ // machineAddresses), or null: localhost and 127.0.0.1 share 127.0.0.1, and
536
+ // 127.0.0.1 and ::1 share none, as they can be two programs on one port.
537
+ function sharedAddresses(one, two) {
538
+ const mine = machineAddresses(one);
539
+ const theirs = machineAddresses(two);
540
+ const both = mine && theirs ? mine.filter((address) => theirs.includes(address)) : [];
541
+ return both.length ? both : null;
542
+ }
543
+
544
+ // Whether an address is not on the public internet by its form alone, or
545
+ // is this machine's own: an IP address that is not on it or is one of
546
+ // this machine's (see standingOf), a name of this machine's own, or a name
547
+ // the system looks up on this machine's own networks (see linkName).
548
+ function notPublicByForm(url) {
549
+ const host = bare(url);
550
+ return net.isIP(host) ? Boolean(standingOf(host)) : localName(host) || linkName(host);
551
+ }
552
+
553
+ // The port a web address is served on, the scheme's own when it names none.
554
+ const portOf = (url) => url.port || (url.protocol === "https:" ? "443" : "80");
555
+
556
+ // Whether an address is written with http: or https:, read as the URL
557
+ // parser reads a scheme: in any case, with tabs and line breaks taken out
558
+ // and the control characters and spaces before it left off.
559
+ const webScheme = (raw) => /^https?:/i.test(String(raw).replace(/[\t\n\r]/g, "").replace(/^[\u0000- ]+/, ""));
560
+
561
+ // The ports an address the run was not given may be on.
562
+ const WEB_PORTS = new Set(["80", "443"]);
563
+
564
+ // Whether two web addresses are on the same host and port: the same host,
565
+ // or two of this machine's own names for itself that reach an address of
566
+ // each other's, on the same port (see sharedAddresses). A local site can
567
+ // send its visitors from one of them to another, as from 127.0.0.1:8080 to
568
+ // localhost:8080, which reaches the same program at 127.0.0.1. Any other
569
+ // name is another host, though it lead to the same address and port: many
570
+ // sites are served at one address and port, a program there picking each
571
+ // by the name a request is for, as Laravel Valet or Herd serve *.test,
572
+ // DDEV's router *.ddev.site, which the public DNS answers with 127.0.0.1,
573
+ // Traefik or Caddy the names under localhost, and a web server its virtual
574
+ // hosts. Counted as the host given, a name under localhost had a page of
575
+ // http://localhost:3000/ load a frame, a picture and the data of a fetch()
576
+ // from http://traefik.localhost:3000/, another site of the same program.
577
+ function sameHost(a, b) {
578
+ if (portOf(a) !== portOf(b)) return false;
579
+ const [one, two] = [bare(a), bare(b)];
580
+ return one === two || Boolean(sharedAddresses(one, two));
581
+ }
582
+
583
+ // ---- MAKERSMCP_REFUSE_ADDRESSES ----
584
+
585
+ const SETTING = "MAKERSMCP_REFUSE_ADDRESSES";
586
+
587
+ // The addresses the setting refuses: a comma list of IP addresses and CIDR
588
+ // ranges, as 185.137.215.163,10.0.0.0/8,fd00::/8, spaces around each
589
+ // allowed. Missing or empty, it refuses nothing more. A value that does not
590
+ // parse stops the run before any work, in words that name the setting.
591
+ //
592
+ // IPv4 entries and IPv6 entries are kept apart, as easyscreenshotkit keeps
593
+ // them: kept together, an IPv4 address was checked against an IPv6 entry as
594
+ // ::ffff:a.b.c.d, so ::/0 or ::/80 refused every IPv4 address, and so every
595
+ // site. An IPv4 entry refuses that address in every IPv6 form that holds it
596
+ // too (see heldIpv4) and a Teredo address whose server or client it is (see
597
+ // teredoIpv4), and while the setting names an IPv4 address or range, every
598
+ // address of NAT64's local use prefix is refused, as one can stand for any
599
+ // IPv4 address (see localNat64). An IPv6 entry refuses the IPv6 addresses it
600
+ // covers, and one written as an IPv6 form of an IPv4 address or range (see
601
+ // heldRange) that IPv4 address or range as well, and so every form of it:
602
+ // 2002:b989:d7a3::/48 named only itself, and 185.137.215.163 was opened. An
603
+ // entry that holds every IPv4 address, as 64:ff9b::/96 and 2002::/16 do,
604
+ // stops the run as a value that does not parse does: it would refuse every
605
+ // site, with words that blamed each site's address, and a host can copy
606
+ // such a range from a firewall's list of the IPv6 ranges it refuses whole.
607
+ //
608
+ // A connection to 0.0.0.0 goes to 127.0.0.1 and one to :: to ::1, on
609
+ // Linux, so the list judges each as the address it reaches as well: a
610
+ // list that refuses 127.0.0.1 refuses 0.0.0.0 and every IPv6 form of it, as
611
+ // ::ffff:0.0.0.0, and one that refuses ::1 refuses ::, written so or found
612
+ // for a name. Judged as written, each was opened as the address given, and
613
+ // the program on this machine's loopback at its port was read.
614
+ //
615
+ // match(address) gives the address that the list refuses for an IP address,
616
+ // the IPv4 address it holds or else it, or the loopback address it reaches,
617
+ // or "".
618
+ function refusedAddresses(value = process.env[SETTING]) {
619
+ const v4 = new net.BlockList();
620
+ const v6 = new net.BlockList();
621
+ // size: the entries; fours: those that refuse IPv4 addresses.
622
+ let size = 0;
623
+ let fours = 0;
624
+ for (const item of String(value === undefined ? "" : value).split(",")) {
625
+ const text = item.trim();
626
+ if (!text) continue;
627
+ const range = /^([^/\s]+)(?:\/(\d{1,3}))?$/.exec(text);
628
+ const family = range ? net.isIP(range[1]) : 0;
629
+ const prefix = range && range[2] !== undefined ? Number(range[2]) : family === 6 ? 128 : 32;
630
+ const shown = JSON.stringify(text.length > 60 ? `${text.slice(0, 60)}...` : text);
631
+ if (!family || range[1].includes("%") || prefix > (family === 6 ? 128 : 32)) {
632
+ throw new Error(`${SETTING} holds ${shown}, which is neither an IP address nor a range such as 10.0.0.0/8, so nothing was read. Give IP addresses and ranges parted by commas, or leave it empty.`);
633
+ }
634
+ const held = family === 6 ? heldRange(groupsOf(range[1]) || [], prefix) : null;
635
+ if (held && held[1] === 0) {
636
+ throw new Error(`${SETTING} holds ${shown}, a range of every IPv4 address in an IPv6 form, which would refuse every site, so nothing was read. An IPv6 form of an IPv4 address is judged by that address: give the IPv4 addresses and ranges to refuse, or leave it empty.`);
637
+ }
638
+ if (family === 4) v4.addSubnet(range[1], prefix, "ipv4");
639
+ else v6.addSubnet(range[1], prefix, "ipv6");
640
+ if (held) v4.addSubnet(held[0], held[1], "ipv4");
641
+ if (family === 4 || held) fours++;
642
+ size++;
643
+ }
644
+ return {
645
+ size,
646
+ match(raw) {
647
+ if (!size) return "";
648
+ const address = plainIp(raw);
649
+ const family = net.isIP(address);
650
+ const four = (one) => (v4.check(one, "ipv4") ? one : one === "0.0.0.0" && v4.check("127.0.0.1", "ipv4") ? "127.0.0.1" : "");
651
+ if (family === 4) return four(address);
652
+ const groups = family === 6 ? groupsOf(address) : null;
653
+ if (!groups) return "";
654
+ for (const held of [heldIpv4(address), ...teredoIpv4(groups)]) if (held && four(held)) return four(held);
655
+ if (v6.check(address, "ipv6") || (fours && localNat64(groups))) return address;
656
+ if (groups.every((group) => group === 0) && v6.check("::1", "ipv6")) return "::1";
657
+ return "";
658
+ },
659
+ };
660
+ }
661
+
662
+ // ---- The words ----
663
+
664
+ // What an address that is not opened is, as said after "it" or "which".
665
+ const NOT_PUBLIC = "is not on the public internet";
666
+ const UNRESOLVED = "is on a host whose name could not be looked up";
667
+ // An http or https address that the URL parser here cannot read, as one
668
+ // whose host has a label of broken punycode (xn--a, see readUrl), which the
669
+ // browser reads all the same: where it leads cannot be judged.
670
+ const UNREADABLE = "is not an address launch-film can read";
671
+ const onPort = (port) => `is on port ${port}, not 80 or 443`;
672
+ const atNotPublic = (address) => `is at ${address}, an address not on the public internet`;
673
+ const atRefused = (address) => `is at ${address}, an address ${SETTING} refuses`;
674
+ // An address on the public internet that is this machine's own, or on the
675
+ // IPv6 network of one of its own (see ownIp), as easyscreenshotkit names it.
676
+ const atMachine = (address) => `is at ${address}, an address of this machine`;
677
+ const atNetwork = (address) => `is at ${address}, on a network of this machine`;
678
+
679
+ // Why an address is refused away from the address given, by where it
680
+ // stands (see standingOf).
681
+ const insideWhy = (address, standing) => (standing === "machine" ? atMachine(address) : standing === "network" ? atNetwork(address) : atNotPublic(address));
682
+
683
+ // Behind a proxy in fake-ip mode, as Clash, Surge or sing-box run with a
684
+ // TUN device, every name answers in 198.18.0.0/15, which is not on the
685
+ // public internet: an IPv4 address there or an IPv6 form of one.
686
+ const FAKE_IP = new net.BlockList();
687
+ FAKE_IP.addSubnet("198.18.0.0", 15, "ipv4");
688
+ function inFakeRange(raw) {
689
+ const address = plainIp(raw);
690
+ const v4 = net.isIP(address) === 6 ? heldIpv4(address) : address;
691
+ return net.isIP(v4) === 4 && FAKE_IP.check(v4, "ipv4");
692
+ }
693
+
694
+ // Why a name whose addresses mix is refused, as said after "it" or
695
+ // "which", or "": one that answers both with an address on the public
696
+ // internet and with one that is not, or that is this machine's own or on
697
+ // one of its networks (see standingOf), named by its first answer of each
698
+ // kind. Such a name is refused wherever the run meets it, the address given
699
+ // included, before any work: taken for the user's own, as one of its
700
+ // answers was, its every answer was opened, so a site whose name answered
701
+ // with its public address and with 127.0.0.1 had every request of the run
702
+ // go to a service of this machine on 127.0.0.1, where the system put that
703
+ // address first, as glibc can by the order of RFC 6724, or once the public
704
+ // address had stopped answering, and that service's page was saved as the
705
+ // site's with no note. Away from the address given, such a name is named
706
+ // in the same words, never as one not on the public internet, which it is
707
+ // not alone. As easyscreenshotkit words it.
708
+ function mixedWhy(addresses) {
709
+ const standings = addresses.map((address) => [plainIp(address), standingOf(address)]);
710
+ const outside = standings.find(([, standing]) => !standing);
711
+ const inside = standings.find(([, standing]) => standing);
712
+ if (!outside || !inside) return "";
713
+ const [at, standing] = inside;
714
+ const kind = standing === "network" ? "one on a network of this machine" : standing === "machine" ? "one of this machine's" : inFakeRange(at) ? "one in the range a proxy in fake-ip mode gives every name, 198.18.0.0/15" : "one that is not";
715
+ return `is on a host whose name answers with an address on the public internet, ${outside[0]}, and with ${kind}, ${at}`;
716
+ }
717
+
718
+ // How a name whose addresses mix answers, as said after the name itself,
719
+ // or "": mixedWhy's words, the name said in place of "is on a host whose
720
+ // name", as for a store's host, which the kit names itself (see stores.js
721
+ // judgedFetch).
722
+ const mixedAnswers = (addresses) => mixedWhy(addresses).replace(/^is on a host whose name /, "");
723
+
724
+ // Why a host found at these addresses is refused away from the address
725
+ // given, as said after "it" or "which", or "" for one every address of
726
+ // which is on the public internet and none this machine's own: a name whose
727
+ // answers mix by both (see mixedWhy), else by its first address that is not
728
+ // (see standingOf).
729
+ function awayWhy(addresses) {
730
+ const mixed = mixedWhy(addresses);
731
+ if (mixed) return mixed;
732
+ for (const address of addresses) {
733
+ const standing = standingOf(address);
734
+ if (standing) return insideWhy(plainIp(address), standing);
735
+ }
736
+ return "";
737
+ }
738
+
739
+ // ---- The rule for a run ----
740
+
741
+ // How long a name is looked up for, counted from when its lookup starts: one
742
+ // that gives no answer in this time is not opened. With glibc's own settings
743
+ // the system waits 5 s for a nameserver that does not answer before it asks
744
+ // the next one, so where the machine's first nameserver did not answer every
745
+ // name came just past a wait of 5 s counted from when it was asked, and was
746
+ // taken for one not found. The lookup runs on libuv's threads, at most half
747
+ // of them at once (UV_THREADPOOL_SIZE, 4 unless it is set), and a name whose
748
+ // DNS gives no answer holds a thread as long as the system waits: so the run
749
+ // asks no more names at once than libuv looks up (atOnce), each waits its
750
+ // turn before its time starts, and launch-film sets UV_THREADPOOL_SIZE to
751
+ // 32, 16 names at once (bin/launch-film.js), as easyscreenshotkit 0.1.4
752
+ // does. A lookup that has run out of time keeps its turn until the system
753
+ // has given up on it, as its thread is busy till then.
754
+ const LOOKUP_WAIT = 10_000;
755
+ const waiting = [];
756
+ let looking = 0;
757
+ const atOnce = () => Math.max(1, Math.floor((Math.min(1024, Math.max(1, Number(process.env.UV_THREADPOOL_SIZE) || 4)) + 1) / 2));
758
+
759
+ function nextLookups() {
760
+ while (waiting.length && looking < atOnce()) {
761
+ const { host, resolve } = waiting.shift();
762
+ looking++;
763
+ let over = false;
764
+ const timer = setTimeout(() => {
765
+ over = true;
766
+ resolve({ list: [] });
767
+ }, LOOKUP_WAIT);
768
+ new Promise((asked) => asked(dns.promises.lookup(host, { all: true, verbatim: true })))
769
+ .then((list) => ({ list: list.map((record) => record.address) }))
770
+ .catch(() => ({ list: [] }))
771
+ .then((answer) => {
772
+ looking--;
773
+ clearTimeout(timer);
774
+ if (!over) resolve(answer);
775
+ nextLookups();
776
+ });
777
+ }
778
+ }
779
+
780
+ // A name's addresses, { list }, by the system's lookup in its turn: [] for
781
+ // a name not found or that gave no answer in its time.
782
+ const lookUp = (host) => new Promise((resolve) => {
783
+ waiting.push({ host, resolve });
784
+ nextLookups();
785
+ });
786
+
787
+ // The rule for the addresses a run opens, for the address given (given, a
788
+ // web address, whose scheme, host and port are the run's own; null for a
789
+ // run that has none, as one reading a site another source named, see
790
+ // makeKit), with the addresses refused (refused, from refusedAddresses).
791
+ // Each name is looked up once a run, and every connection the run makes,
792
+ // the browser's through the kit's proxy (see proxy.js) and the kit's own,
793
+ // goes only to an address that lookup found and the rule took, so no name
794
+ // is looked up twice and no later answer is ever used.
795
+ //
796
+ // judge(raw) resolves to "" for an address the run may open, and else to
797
+ // why not, to follow "it" or "which". What is not a web address is not
798
+ // judged here: a page that leads to one fails or is cancelled on its own
799
+ // (see chrome.js). One written with http: or https: that the URL parser
800
+ // here cannot read is not opened: the browser can read it, and go where
801
+ // its host leads.
802
+ //
803
+ // route(raw): { why, addresses }, why as judge gives it, and the addresses
804
+ // a connection to it may go to, for one the run may open: every address
805
+ // the lookup found for its host. For the address given they are looked up
806
+ // too, and none, for a name not found, is no refusal but a connection that
807
+ // cannot be made. For another of this machine's names that is the host
808
+ // given, as localhost from 127.0.0.1, they are the addresses the two share
809
+ // alone (see sharedAddresses).
810
+ //
811
+ // found(host): the addresses a host is at, by the same lookup: an IP
812
+ // address is at itself, and localhost and the names under it are on this
813
+ // machine's loopback, ::1 first (see LOOPBACK). [] for a name not found.
814
+ //
815
+ // inside(url): whether a host is not on the public internet or is this
816
+ // machine's own, by the same lookup, or cannot be told by it, as a name
817
+ // not found.
818
+ //
819
+ // addressesFor(raw): the addresses a request the kit makes itself to raw
820
+ // connects to (see dial.js), those route gives; it fails for one the rule
821
+ // refuses or the URL parser cannot read, and for a name not found.
822
+ function guardFor(givenRaw, { refused = refusedAddresses("") } = {}) {
823
+ const given = givenRaw ? new URL(givenRaw) : null;
824
+ const answers = new Map();
825
+ const lookup = (host) => {
826
+ if (!answers.has(host)) answers.set(host, lookUp(host));
827
+ return answers.get(host);
828
+ };
829
+ const found = async (host) => {
830
+ if (net.isIP(host)) return [host];
831
+ if (localName(host)) return [...LOOPBACK];
832
+ return (await lookup(host)).list;
833
+ };
834
+ // On the scheme, host and port of the address given: its own pages; and
835
+ // https on the host and port of an http address given, the same program,
836
+ // which the browser asks over https by itself for a name that takes only
837
+ // https (HSTS), as every .dev and .app name, keeping the port. A move
838
+ // from https down to http there is not the address given, nor https on
839
+ // port 443 of a host given on port 80, which is another program. The host
840
+ // given is its own name, and of this machine's own names only those that
841
+ // reach an address of it on its port (see sameHost).
842
+ const givenHost = given ? bare(given) : "";
843
+ const own = (url) => Boolean(given) && sameHost(url, given) && (url.protocol === given.protocol || (given.protocol === "http:" && url.protocol === "https:"));
844
+ // The rule for one address. resolve: whether the addresses of one the run
845
+ // may open are wanted, as for a connection; without it, the address given
846
+ // is looked up only to check its answers, at a name, and to check them
847
+ // against the refused addresses.
848
+ async function rule(raw, resolve) {
849
+ const url = readUrl(raw);
850
+ if (!url) return { why: webScheme(raw) ? UNREADABLE : "", addresses: [] };
851
+ if (!/^https?:$/.test(url.protocol)) return { why: "", addresses: [] };
852
+ const mine = own(url);
853
+ if (!mine && !WEB_PORTS.has(portOf(url))) return { why: onPort(portOf(url)), addresses: [] };
854
+ const host = bare(url);
855
+ if (!mine && (localName(host) || linkName(host))) return { why: NOT_PUBLIC, addresses: [] };
856
+ // An IP address away from the address given that is not on the public
857
+ // internet, by its form, or that is this machine's own.
858
+ if (!mine && net.isIP(host)) {
859
+ const standing = standingOf(host);
860
+ if (standing) return { why: standing === "not public" ? NOT_PUBLIC : insideWhy(host, standing), addresses: [] };
861
+ }
862
+ // The address given at an IP address or a name of this machine's own
863
+ // needs no lookup to be judged: no such host has answers that mix.
864
+ const name = !net.isIP(host) && !localName(host);
865
+ if (mine && !refused.size && !resolve && !name) return { why: "", addresses: [] };
866
+ // Another of this machine's names that is the host given goes to the
867
+ // addresses the two share alone: from http://127.0.0.1:4000/, a page's
868
+ // picture at http://localhost:4000/ comes from 127.0.0.1, never from
869
+ // ::1, which can be another program on that port.
870
+ const addresses = (mine && sharedAddresses(host, givenHost)) || (await found(host));
871
+ if (!addresses.length) return { why: mine && !refused.size ? "" : UNRESOLVED, addresses: [] };
872
+ // A name whose answers mix is refused wherever it is, the address given
873
+ // and its own pages included (see mixedWhy).
874
+ const away = mine ? (name ? mixedWhy(addresses) : "") : awayWhy(addresses);
875
+ if (away) return { why: away, addresses: [] };
876
+ for (const address of addresses) if (refused.match(address)) return { why: atRefused(refused.match(address)), addresses: [] };
877
+ return { why: "", addresses: addresses.map(plainIp) };
878
+ }
879
+ const judge = async (raw) => (await rule(raw, false)).why;
880
+ const route = (raw) => rule(raw, true);
881
+ async function inside(url) {
882
+ const addresses = await found(bare(url));
883
+ return !addresses.length || addresses.some((address) => Boolean(standingOf(address)));
884
+ }
885
+ async function addressesFor(raw) {
886
+ const { why, addresses } = await route(raw);
887
+ if (why || !addresses.length) throw Object.assign(new Error(`${String(raw).slice(0, 300)} ${why || UNRESOLVED}`), { code: why ? "ENOTPUBLIC" : "ENOTFOUND" });
888
+ return addresses;
889
+ }
890
+ return { given: given ? given.href : "", refused, judge, route, found, inside, addressesFor };
891
+ }
892
+
893
+ module.exports = { isPublicAddress, heldIpv4, ownIp, kernel, interfacesUnread, notPublicByForm, sameHost, portOf, refusedAddresses, guardFor, readUrl, atRefused, awayWhy, mixedAnswers, UNRESOLVED };