@a2f0/agent-tool 0.1.71 → 0.1.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Which hosts `seo probe` may request when a URL comes from fetched markup or a
3
+ * redirect rather than the command line: a hostile page could otherwise point
4
+ * the probe at this machine or its network (`og:image` on `169.254.169.254`, a
5
+ * sitemap entry on `localhost`) and print what answers.
6
+ */
7
+ import { lookup as dnsLookup } from "node:dns/promises";
8
+ import { isIP } from "node:net";
9
+
10
+ /** Every address a hostname resolves to; an unresolvable name has none. */
11
+ export type Lookup = (hostname: string) => Promise<string[]>;
12
+ /** Why a URL must not be requested, or undefined when it may be, deciding within `milliseconds`. */
13
+ export type Guard = (url: URL, milliseconds: number) => Promise<string | undefined>;
14
+
15
+ const systemLookup: Lookup = async hostname => (await dnsLookup(hostname, { all: true, verbatim: true })).map(entry => entry.address);
16
+
17
+ /**
18
+ * IPv4 ranges outside the public internet: this network, private, shared
19
+ * (CGNAT), loopback, link-local, IETF protocol assignments, documentation,
20
+ * benchmarking, and multicast or reserved.
21
+ */
22
+ const V4_RANGES: [string, number][] = [
23
+ ["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], ["172.16.0.0", 12], ["192.0.0.0", 24],
24
+ ["192.0.2.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24], ["203.0.113.0", 24], ["224.0.0.0", 3],
25
+ ];
26
+
27
+ function ipv4(address: string): number {
28
+ return address.split(".").reduce((value, part) => value * 256 + Number(part), 0);
29
+ }
30
+
31
+ const inRange = (value: number, [base, bits]: [string, number]) => Math.floor(value / 2 ** (32 - bits)) === Math.floor(ipv4(base) / 2 ** (32 - bits));
32
+ const nonPublicV4 = (address: string) => V4_RANGES.some(range => inRange(ipv4(address), range));
33
+
34
+ /** The eight 16-bit groups of an IPv6 address, with a trailing dotted IPv4 part expanded. */
35
+ function ipv6Groups(address: string): number[] {
36
+ let text = address.replace(/%.*$/, "");
37
+ const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
38
+ if (dotted) {
39
+ const value = ipv4(dotted[1]!);
40
+ text = `${text.slice(0, dotted.index)}${Math.floor(value / 65536).toString(16)}:${(value % 65536).toString(16)}`;
41
+ }
42
+ const [head = "", tail] = text.split("::");
43
+ const parse = (part: string) => part ? part.split(":").map(group => parseInt(group, 16)) : [];
44
+ const left = parse(head), right = tail === undefined ? [] : parse(tail);
45
+ return [...left, ...Array<number>(8 - left.length - right.length).fill(0), ...right];
46
+ }
47
+
48
+ const embeddedV4 = (high: number, low: number) => `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
49
+
50
+ /** Loopback, link-local, private, unspecified, multicast, or reserved: anything that is not a public unicast address. */
51
+ export function isNonPublicAddress(address: string): boolean {
52
+ const family = isIP(address.replace(/%.*$/, ""));
53
+ if (family === 4) return nonPublicV4(address);
54
+ if (family !== 6) return true;
55
+ const groups = ipv6Groups(address);
56
+ const [a = 0, b = 0, , , , f = 0, g = 0, h = 0] = groups;
57
+ const zeros = (count: number) => groups.slice(0, count).every(group => group === 0);
58
+ // IPv4-mapped ::ffff:a.b.c.d and IPv4-translated ::ffff:0:a.b.c.d are that IPv4 address; the rest of ::/96 is unspecified, loopback, or deprecated.
59
+ if ((zeros(5) && f === 0xffff) || (zeros(4) && groups[4] === 0xffff && f === 0)) return nonPublicV4(embeddedV4(g, h));
60
+ if (zeros(6)) return true;
61
+ // NAT64 well-known prefix 64:ff9b::/96, and 6to4 2002::/16, which carry an IPv4 address.
62
+ if (a === 0x64 && b === 0xff9b && groups.slice(2, 6).every(group => group === 0)) return nonPublicV4(embeddedV4(g, h));
63
+ if (a === 0x2002) return nonPublicV4(embeddedV4(b, groups[2] ?? 0));
64
+ // Unique local fc00::/7, link-local fe80::/10, site-local fec0::/10, multicast ff00::/8, local-use NAT64 64:ff9b:1::/48,
65
+ // discard 100::/64, Teredo 2001::/32, and documentation 2001:db8::/32.
66
+ return (a & 0xfe00) === 0xfc00 || (a & 0xffc0) === 0xfe80 || (a & 0xffc0) === 0xfec0 || (a & 0xff00) === 0xff00 || (a === 0x64 && b === 0xff9b && groups[2] === 1)
67
+ || (a === 0x100 && groups.slice(1, 4).every(group => group === 0)) || (a === 0x2001 && (b === 0 || b === 0xdb8));
68
+ }
69
+
70
+ /** The promise's value, or undefined when it takes longer than `milliseconds`. */
71
+ async function within<T>(promise: Promise<T>, milliseconds: number): Promise<T | undefined> {
72
+ let timer: ReturnType<typeof setTimeout> | undefined;
73
+ try {
74
+ return await Promise.race([promise, new Promise<undefined>(resolve => { timer = setTimeout(resolve, Math.max(0, milliseconds), undefined); })]);
75
+ } finally { clearTimeout(timer); }
76
+ }
77
+
78
+ /** How long the named host's own lookup may take before the guard assumes it is public. */
79
+ const NAMED_LOOKUP_MILLISECONDS = 15_000;
80
+
81
+ /**
82
+ * The guard for URLs that markup or redirects supply, or undefined when every
83
+ * address of the named host is non-public (probing a local server), since then
84
+ * every target is the user's own network. Otherwise a host that is, or resolves
85
+ * to, any non-public address is refused, except the named host itself, which
86
+ * the user chose: a page cannot switch the guard off, or reach this network
87
+ * through another name, by publishing a private record beside a public one.
88
+ * Names resolve once per run through the system resolver, as `fetch` resolves
89
+ * them. A name that does not resolve is left to the request, which fails or
90
+ * goes through a proxy; one that does not resolve within the request's time
91
+ * limit is refused. The check runs just before each request, so a name that
92
+ * resolves differently by the time `fetch` connects (DNS rebinding) is not
93
+ * caught.
94
+ */
95
+ export async function addressGuard(namedHost: string, lookup: Lookup = systemLookup, namedMilliseconds = NAMED_LOOKUP_MILLISECONDS): Promise<Guard | undefined> {
96
+ const cache = new Map<string, Promise<string[]>>();
97
+ const bare = (hostname: string) => hostname.replace(/^\[|\]$/g, "");
98
+ const addresses = (hostname: string) => {
99
+ let found = cache.get(hostname);
100
+ if (!found) {
101
+ found = isIP(hostname) ? Promise.resolve([hostname]) : lookup(hostname).catch(() => []);
102
+ cache.set(hostname, found);
103
+ }
104
+ return found;
105
+ };
106
+ const named = bare(new URL(`http://${namedHost}/`).hostname);
107
+ const own = await within(addresses(named), namedMilliseconds);
108
+ if (own?.length && own.every(isNonPublicAddress)) return undefined;
109
+ return async (url, milliseconds) => {
110
+ const hostname = bare(url.hostname);
111
+ if (hostname === named) return undefined;
112
+ const found = await within(addresses(hostname), milliseconds);
113
+ if (found === undefined) return `refused ${hostname}: it did not resolve within the request's time limit`;
114
+ const address = found.find(isNonPublicAddress);
115
+ return address === undefined ? undefined : `refused ${hostname} (${address}): a non-public address that the command line did not name`;
116
+ };
117
+ }
package/src/seo/html.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  /**
2
- * Regular-expression readers for `seo probe`, over HTML with its newlines,
3
- * carriage returns, and tabs collapsed to spaces. They match the way the
4
- * original shell probe's `grep -oiE` pipelines did: double-quoted attributes
5
- * only, first match or every match in document order, and no HTML parser, so
6
- * a surprising result needs a look at the raw response.
2
+ * Markup readers for `seo probe`, over HTML with its newlines, carriage
3
+ * returns, and tabs collapsed to spaces. They match what the original shell
4
+ * probe's `grep -oiE` patterns matched (`<meta[^>]+name="description"[^>]*>`
5
+ * and the like): double-quoted attributes only, ASCII case-insensitive, first
6
+ * match or every match in document order, and no HTML parser, so a surprising
7
+ * result needs a look at the raw response. They scan with `indexOf` instead of
8
+ * regular expressions, reading each character a bounded number of times, since
9
+ * a backtracking pattern takes quadratic time on a hostile page with many
10
+ * unterminated tags.
7
11
  */
8
12
 
9
13
  /** The body as one line: `\n`, `\r`, and `\t` become spaces. */
@@ -11,57 +15,206 @@ export function collapse(body: string): string {
11
15
  return body.replace(/[\n\r\t]/g, " ");
12
16
  }
13
17
 
14
- const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
18
+ /** ASCII-only lowercase, so every index still points at the same character of the original. */
19
+ const lower = (text: string) => text.replace(/[A-Z]+/g, run => run.toLowerCase());
15
20
 
16
- /** Every case-insensitive match of `pattern` in `text`, in order. */
17
- export function matches(text: string, pattern: string): string[] {
18
- return [...text.matchAll(new RegExp(pattern, "gi"))].map(match => match[0]);
19
- }
21
+ /** Distinct values in code-unit order, each followed by one space. */
22
+ const spaced = (values: string[]) => [...new Set(values)].sort().map(value => `${value} `).join("");
20
23
 
21
- /** The first case-insensitive match, or "". */
22
- export function first(text: string, pattern: string): string {
23
- return new RegExp(pattern, "i").exec(text)?.[0] ?? "";
24
- }
24
+ interface Span { start: number; end: number }
25
25
 
26
- /** Distinct matches in code-unit order, each followed by one space. */
27
- export function names(text: string, pattern: string): string {
28
- return [...new Set(matches(text, pattern))].sort().map(name => `${name} `).join("");
26
+ /**
27
+ * The tags the pattern `<name[^>]+needle[^>]*>` matches, as spans from `<name`
28
+ * through its first `>`: one of `needles` must start at least one character
29
+ * after the name. Of several `<name` before the same `>`, only the first can
30
+ * match (a later one's text is a suffix of it), so the scan resumes after that
31
+ * `>` whether or not the tag matched.
32
+ */
33
+ function tags(text: string, name: string, needles: string[], limit = Infinity): Span[] {
34
+ const open = `<${name}`, found: Span[] = [];
35
+ for (let from = 0; found.length < limit;) {
36
+ const start = text.indexOf(open, from);
37
+ if (start < 0) break;
38
+ const end = text.indexOf(">", start + open.length);
39
+ if (end < 0) break;
40
+ const inside = text.slice(start + open.length + 1, end);
41
+ if (needles.some(needle => inside.includes(needle))) found.push({ start, end: end + 1 });
42
+ from = end + 1;
43
+ }
44
+ return found;
29
45
  }
30
46
 
31
- /** Every `name="value"` value in `text`, in order. */
47
+ /** Every `name="value"` value in `text`, in order, as the pattern `name="[^"]*"` finds them. */
32
48
  export function attrValues(text: string, name: string): string[] {
33
- return matches(text, `${escapeRegExp(name)}="[^"]*"`).map(match => match.slice(match.indexOf('"') + 1, -1));
49
+ const lowered = lower(text), opening = `${name}="`, values: string[] = [];
50
+ for (let at = lowered.indexOf(opening); at >= 0; at = lowered.indexOf(opening, at)) {
51
+ const close = lowered.indexOf('"', at + opening.length);
52
+ if (close < 0) break;
53
+ values.push(text.slice(at + opening.length, close));
54
+ at = close + 1;
55
+ }
56
+ return values;
34
57
  }
35
58
 
36
59
  /** The same values, one per line. */
37
60
  export const attr = (text: string, name: string) => attrValues(text, name).join("\n");
38
61
 
62
+ /**
63
+ * The `attribute` values in each tag that the pattern
64
+ * `<name[^>]+attribute="[^"]*"` (`[^>]*` when `gap` is 0) matches, as
65
+ * `attrValues` reads them from the match. The pattern needs no closing `>`, so
66
+ * a tag that never closes runs to the end of the text. Its greedy middle ends
67
+ * at the last value that starts before the tag's first `>` and has a closing
68
+ * quote, which may lie past that `>`; the tag matches when that value starts
69
+ * at least `gap` characters after the name. Of several `<name` before the
70
+ * same `>`, only the first can match.
71
+ */
72
+ function tagValues(text: string, name: string, attribute: string, gap: 0 | 1, limit = Infinity): string[][] {
73
+ const lowered = lower(text), open = `<${name}`, opening = `${attribute}="`, found: string[][] = [];
74
+ for (let from = 0; found.length < limit;) {
75
+ const start = lowered.indexOf(open, from);
76
+ if (start < 0) break;
77
+ const inside = start + open.length, close = lowered.indexOf(">", inside), end = close < 0 ? text.length : close;
78
+ const segment = lowered.slice(inside, end);
79
+ let last = segment.lastIndexOf(opening);
80
+ // Only the final value can lack a closing quote, and then the one before it has one.
81
+ if (last >= 0 && lowered.indexOf('"', inside + last + opening.length) < 0) last = last > 0 ? segment.lastIndexOf(opening, last - 1) : -1;
82
+ from = end + 1;
83
+ if (last >= gap) {
84
+ const values: string[] = [];
85
+ for (let at = segment.indexOf(opening); at >= 0 && at <= last; at = segment.indexOf(opening, at)) {
86
+ const quote = lowered.indexOf('"', inside + at + opening.length);
87
+ values.push(text.slice(inside + at + opening.length, quote));
88
+ at = quote + 1 - inside;
89
+ }
90
+ found.push(values);
91
+ // The match ends at that last value's closing quote, which can lie past the `>`.
92
+ from = Math.max(from, lowered.indexOf('"', inside + last + opening.length) + 1);
93
+ }
94
+ if (close < 0) break;
95
+ }
96
+ return found;
97
+ }
98
+
39
99
  /** Decode the predefined XML entities; `&amp;` goes last so `&amp;lt;` stays `&lt;`. */
40
100
  export function unescape(value: string): string {
41
101
  return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#39;/g, "'").replace(/&amp;/g, "&");
42
102
  }
43
103
 
44
- /** The content of the first `<meta>` whose property or name is `key`. */
45
- export function contentOf(body: string, key: string): string {
46
- return attr(first(body, `<meta[^>]+(property|name)="${escapeRegExp(key)}"[^>]*>`), "content");
104
+ /** The `content` values of every `<meta>` whose `name` (or `property`) is one of `keys`. */
105
+ function metaContents(body: string, keys: string[], properties: boolean, limit = Infinity): string[] {
106
+ const needles = keys.flatMap(key => [`name="${key}"`, ...(properties ? [`property="${key}"`] : [])]);
107
+ return tags(lower(body), "meta", needles, limit).flatMap(({ start, end }) => attrValues(body.slice(start, end), "content"));
47
108
  }
48
109
 
110
+ /** The content of the first `<meta>` whose property or name is `key`. */
111
+ export const contentOf = (body: string, key: string) => metaContents(body, [key], true, 1).join("\n");
112
+
113
+ /** The content of each robots and googlebot meta tag, in order. */
114
+ export const robotsMetaContents = (body: string) => metaContents(body, ["robots", "googlebot"], false);
115
+
49
116
  /** Every robots and googlebot meta directive, lowercase, joined with spaces. */
50
- export function robotsMeta(body: string): string {
51
- return matches(body, '<meta[^>]+name="(robots|googlebot)"[^>]*>').flatMap(tag => attrValues(tag, "content")).join(" ").toLowerCase();
52
- }
117
+ export const robotsMeta = (body: string) => robotsMetaContents(body).join(" ").toLowerCase();
118
+
119
+ /** Each `theme-color` meta tag's content, each followed by one space. */
120
+ export const themeColors = (body: string) => metaContents(body, ["theme-color"], false).map(value => `${value} `).join("");
53
121
 
54
122
  export function titleOf(body: string): string {
55
- return first(body, "<title[^>]*>[^<]*</title>").replace(/<[^>]*>/g, "");
123
+ const lowered = lower(body);
124
+ for (let from = 0; ;) {
125
+ const start = lowered.indexOf("<title", from);
126
+ if (start < 0) return "";
127
+ const close = lowered.indexOf(">", start + 6);
128
+ if (close < 0) return "";
129
+ const next = lowered.indexOf("<", close + 1);
130
+ if (next < 0) return "";
131
+ if (lowered.startsWith("</title>", next)) return body.slice(close + 1, next);
132
+ from = close + 1;
133
+ }
56
134
  }
57
135
 
58
136
  export function canonicalOf(body: string): string {
59
- return unescape(attr(first(body, '<link[^>]+rel="canonical"[^>]*>'), "href"));
137
+ const [tag] = tags(lower(body), "link", ['rel="canonical"'], 1);
138
+ return tag ? unescape(attr(body.slice(tag.start, tag.end), "href")) : "";
139
+ }
140
+
141
+ /** The `lang` values of the first `<html>` tag that has one, one per line. */
142
+ export const langOf = (body: string) => (tagValues(body, "html", "lang", 0, 1)[0] ?? []).join("\n");
143
+
144
+ const isLetter = (code: number) => (code >= 97 && code <= 122) || (code >= 65 && code <= 90);
145
+
146
+ /** The distinct `og:` properties present, as `"og:name"`, each followed by one space: the pattern `property="og:[a-z_:]+"`. */
147
+ export function ogProperties(body: string): string {
148
+ const lowered = lower(body), opening = 'property="og:', found: string[] = [];
149
+ for (let from = 0; ;) {
150
+ const start = lowered.indexOf(opening, from);
151
+ if (start < 0) break;
152
+ let end = start + opening.length;
153
+ for (let code = lowered.charCodeAt(end); isLetter(code) || code === 95 || code === 58; code = lowered.charCodeAt(++end));
154
+ if (end > start + opening.length && lowered[end] === '"') { found.push(body.slice(start, end + 1)); from = end + 1; }
155
+ else from = start + 1;
156
+ }
157
+ return spaced(found).replace(/property=/g, "");
158
+ }
159
+
160
+ /** How many times `needle` occurs, ASCII case-insensitively. */
161
+ function count(body: string, needle: string, after?: (next: string | undefined) => boolean): number {
162
+ const lowered = lower(body);
163
+ let total = 0;
164
+ for (let at = lowered.indexOf(needle); at >= 0; at = lowered.indexOf(needle, at + needle.length)) {
165
+ if (!after || after(lowered[at + needle.length])) total++;
166
+ }
167
+ return total;
168
+ }
169
+
170
+ export const jsonLdBlocks = (body: string) => count(body, "application/ld+json");
171
+ export const h1Count = (body: string) => count(body, "<h1", next => next === " " || next === ">");
172
+
173
+ /** The distinct JSON-LD `@type` values, as `"Name"` or `["A","B"]`, each followed by one space: the pattern `"@type": *("[A-Za-z]+"|\[[^\]]*\])`. */
174
+ export function jsonLdTypes(body: string): string {
175
+ const lowered = lower(body), opening = '"@type":', found: string[] = [];
176
+ let noBracket = false;
177
+ for (let from = 0; ;) {
178
+ const start = lowered.indexOf(opening, from);
179
+ if (start < 0) break;
180
+ let at = start + opening.length;
181
+ while (body[at] === " ") at++;
182
+ let end = -1;
183
+ if (body[at] === '"') {
184
+ let letters = at + 1;
185
+ while (isLetter(body.charCodeAt(letters))) letters++;
186
+ if (letters > at + 1 && body[letters] === '"') end = letters + 1;
187
+ } else if (body[at] === "[" && !noBracket) {
188
+ const close = body.indexOf("]", at + 1);
189
+ if (close < 0) noBracket = true;
190
+ else end = close + 1;
191
+ }
192
+ if (end > 0) { found.push(body.slice(start, end)); from = end; }
193
+ else from = start + 1;
194
+ }
195
+ return spaced(found).replace(/"@type": */g, "");
196
+ }
197
+
198
+ /** Leading and trailing spaces removed, without a pattern that backtracks over a long run of spaces. */
199
+ function trimSpaces(value: string): string {
200
+ let start = 0, end = value.length;
201
+ while (start < end && value[start] === " ") start++;
202
+ while (end > start && value[end - 1] === " ") end--;
203
+ return value.slice(start, end);
60
204
  }
61
205
 
62
206
  /** The `<loc>` values of a sitemap, trimmed and decoded. */
63
207
  export function locs(body: string): string[] {
64
- return [...collapse(body).matchAll(/<loc>[^<]+<\/loc>/g)].map(match => unescape(match[0].replace(/<\/?loc>/g, "").replace(/^ +/, "").replace(/ +$/, "")));
208
+ const text = collapse(body), found: string[] = [];
209
+ for (let from = 0; ;) {
210
+ const start = text.indexOf("<loc>", from);
211
+ if (start < 0) break;
212
+ const next = text.indexOf("<", start + 5);
213
+ if (next < 0) break;
214
+ if (next > start + 5 && text.startsWith("</loc>", next)) { found.push(unescape(trimSpaces(text.slice(start + 5, next)))); from = next + 6; }
215
+ else from = start + 1;
216
+ }
217
+ return found;
65
218
  }
66
219
 
67
220
  /** A sitemap or sitemap index document, by its root element. */
@@ -89,6 +242,32 @@ export function lines(text: string): string[] {
89
242
  return all;
90
243
  }
91
244
 
245
+ /** Valued robots directives, whose value can be `none` without blocking indexing. */
246
+ const VALUED_DIRECTIVES = new Set(["max-snippet", "max-image-preview", "max-video-preview", "unavailable_after"]);
247
+
248
+ /**
249
+ * Whether a robots value keeps a page out of search: a whole `noindex` or
250
+ * `none` directive, in a list separated by commas or spaces. A valued
251
+ * directive such as `max-image-preview:none` never counts, nor does its value
252
+ * after a space (`max-image-preview: none`). In an
253
+ * `X-Robots-Tag` header (`agentPrefix`), an element may begin with any other
254
+ * `name:`, which names a crawler, as in `googlebot: none` or
255
+ * `googlebot:noindex`; robots meta tags name the crawler in the tag instead.
256
+ */
257
+ export function blocksIndexing(value: string, agentPrefix: boolean): boolean {
258
+ return value.toLowerCase().split(",").some(element => {
259
+ const tokens = element.trim().split(/\s+/);
260
+ const colon = tokens[0]!.indexOf(":");
261
+ if (agentPrefix && colon >= 0 && !VALUED_DIRECTIVES.has(tokens[0]!.slice(0, colon))) tokens[0] = tokens[0]!.slice(colon + 1);
262
+ for (let index = 0; index < tokens.length; index++) {
263
+ const token = tokens[index]!;
264
+ if (token.endsWith(":") && VALUED_DIRECTIVES.has(token.slice(0, -1))) index++; // the next token is its value
265
+ else if (token === "noindex" || token === "none") return true;
266
+ }
267
+ return false;
268
+ });
269
+ }
270
+
92
271
  /**
93
272
  * Resolve a relative reference (no scheme, not protocol-relative) against the
94
273
  * final document path: a query-only reference against the page itself, any
@@ -115,6 +294,11 @@ export function resolvePath(reference: string, page: string): string {
115
294
  return resolved + query;
116
295
  }
117
296
 
297
+ /** Every `href` value of an `<a>` tag, in order, as the pattern `<a[^>]+href="[^"]*"` finds them. */
298
+ export const hrefValues = (body: string) => tagValues(body, "a", "href", 1).flat();
299
+
300
+ const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
301
+
118
302
  /**
119
303
  * The page's links to its own host, as URLs to request: absolute ones exactly
120
304
  * as written, protocol-relative ones with the page's scheme, and relative ones
@@ -124,14 +308,14 @@ export function resolvePath(reference: string, page: string): string {
124
308
  export function internalLinks(body: string, finalUrl: URL): string[] {
125
309
  const origin = `${finalUrl.protocol}//${finalUrl.host}`;
126
310
  const host = escapeRegExp(finalUrl.host);
127
- const hrefs = matches(body, '<a[^>]+href="[^"]*"')
128
- .flatMap(tag => attrValues(tag, "href"))
129
- .map(href => unescape(href).replace(/#.*/, ""))
311
+ const absolute = new RegExp(`^https?://${host}(?:[/?]|$)`, "i"), relative = new RegExp(`^//${host}(?:[/?]|$)`, "i");
312
+ const hrefs = hrefValues(body)
313
+ .map(href => { const value = unescape(href), hash = value.indexOf("#"); return hash < 0 ? value : value.slice(0, hash); })
130
314
  .filter(href => href !== "");
131
315
  const links = new Set<string>();
132
316
  for (const href of hrefs) {
133
- if (new RegExp(`^https?://${host}([/?]|$)`, "i").test(href)) links.add(href);
134
- else if (new RegExp(`^//${host}([/?]|$)`, "i").test(href)) links.add(`${finalUrl.protocol}${href}`);
317
+ if (absolute.test(href)) links.add(href);
318
+ else if (relative.test(href)) links.add(`${finalUrl.protocol}${href}`);
135
319
  else if (!/^[a-zA-Z][a-zA-Z0-9+.-]*:|^\/\//.test(href)) links.add(origin + resolvePath(href, finalUrl.pathname));
136
320
  }
137
321
  return [...links].sort();
package/src/seo/http.ts CHANGED
@@ -3,9 +3,11 @@
3
3
  * honors the proxy variables a sandboxed harness sets. Only `http:` and `https:`
4
4
  * URLs are ever requested, including redirect targets, because URLs come from
5
5
  * remote markup (`og:image`, sitemap entries, links, `Location`), and `fetch`
6
- * itself would also read `file:` and `s3:` URLs. Redirects are followed by hand
7
- * so each hop is checked and the first one can be reported.
6
+ * itself would also read `file:` and `s3:` URLs. A URL the command line did not
7
+ * name, and every redirect target, also passes the address guard. Redirects are
8
+ * followed by hand so each hop is checked and the first one can be reported.
8
9
  */
10
+ import type { Guard } from "./address";
9
11
 
10
12
  export interface Reply {
11
13
  /** The URL requested. */
@@ -31,6 +33,10 @@ export interface RequestOptions {
31
33
  seconds: number;
32
34
  /** Read the body; false cancels it once the headers arrive. */
33
35
  body?: boolean;
36
+ /** Refuses non-public hosts that markup or redirects supply. */
37
+ guard?: Guard;
38
+ /** The URL is built from the command line's host and path, so the guard skips it (but not its redirects). */
39
+ named?: boolean;
34
40
  }
35
41
 
36
42
  /** curl's default `--max-redirs` with `-L`. */
@@ -76,9 +82,11 @@ async function readBody(response: Response): Promise<Uint8Array> {
76
82
  return body;
77
83
  }
78
84
 
79
- async function get(target: string, options: RequestOptions, deadline: number): Promise<Reply> {
85
+ async function get(target: string, options: RequestOptions, deadline: number, guarded: boolean): Promise<Reply> {
80
86
  const url = webUrl(target);
81
87
  if (!url) return failed(target, `refused a URL that is not HTTP or HTTPS: ${target}`);
88
+ const refused = guarded ? await options.guard?.(url, deadline - performance.now()) : undefined;
89
+ if (refused) return failed(target, refused);
82
90
  const remaining = deadline - performance.now();
83
91
  if (remaining <= 0) return failed(target, `timed out after ${options.seconds} seconds`);
84
92
  try {
@@ -105,20 +113,23 @@ async function get(target: string, options: RequestOptions, deadline: number): P
105
113
 
106
114
  /** One request; redirects are reported, not followed. */
107
115
  export function request(target: string, options: RequestOptions): Promise<Reply> {
108
- return get(target, options, performance.now() + options.seconds * 1000);
116
+ return get(target, options, performance.now() + options.seconds * 1000, !options.named);
109
117
  }
110
118
 
111
119
  /**
112
120
  * Follow redirects (not 304) up to curl's limit within one deadline. The final
113
- * reply is the last response received; a redirect to a refused scheme ends the
114
- * chain at that redirect, and a hop that gets no response ends it with "000".
121
+ * reply is the last response received; a redirect to a refused scheme or host
122
+ * ends the chain at that redirect, and a hop that gets no response ends it
123
+ * with "000".
115
124
  */
116
125
  export async function follow(target: string, options: RequestOptions): Promise<Followed> {
117
126
  const deadline = performance.now() + options.seconds * 1000;
118
- const first = await get(target, options, deadline);
127
+ const first = await get(target, options, deadline, !options.named);
119
128
  let final = first;
120
- for (let hops = 0; hops < MAX_REDIRECTS && final.location && final.code !== "304" && webUrl(final.location); hops++) {
121
- final = await get(final.location, options, deadline);
129
+ for (let hops = 0; hops < MAX_REDIRECTS && final.location && final.code !== "304"; hops++) {
130
+ const next = webUrl(final.location);
131
+ if (!next || await options.guard?.(next, deadline - performance.now())) break;
132
+ final = await get(final.location, options, deadline, false);
122
133
  }
123
134
  return { first, final };
124
135
  }