turva-llms-txt-validator 0.7.4 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -84,13 +84,18 @@ npx --yes turva-llms-txt-validator example.com --json --strict
84
84
 
85
85
  Completed validation returns `{ target, summary, checks }`, where `target` is `https://<host>/llms.txt`. Each check contains `{ id, status, label, detail }`. Read `id` and `status` in a script, because the wording of `detail` can change between versions. The `input-path` check, which reports a path given with the domain and then ignored, also carries `value`, that path cut to 120 characters.
86
86
 
87
+ The validator removes C0 and C1 control characters, bidirectional controls and invisible characters from the `detail` text, which can quote the checked site. The invisible characters are chosen by Unicode class, not from a list: every format character, which is General_Category Cf, every Default_Ignorable_Code_Point and the line and paragraph separators U+2028 and U+2029. That covers the zero-width characters, the left-to-right and right-to-left marks, the Arabic letter mark, the word joiner and the invisible math operators, the soft hyphen, the byte-order mark, the variation selectors, the combining grapheme joiner, the Hangul fillers and the tag characters U+E0000 to U+E007F. Spaces stay: the no-break space and U+2000 to U+200A. The zero-width non-joiner and joiner go too, so a quoted Persian, Malayalam or Devanagari word loses its joining marks and reads without them. The Arabic number signs U+0600 to U+0605 go as well. Until 0.8.0 only the bidi controls and the C0 and C1 controls were removed, and the invisible characters stayed in the text and in the JSON. An emoji sequence in quoted text loses its zero-width joiners and its variation selector: a family emoji reads as its members side by side, a heart written with U+FE0F shows in text style, a keycap sequence loses the selector, and a tag flag shows as its black flag. The emoji themselves, skin tone modifiers, regional indicators and combining marks stay.
88
+
87
89
  With `--json`, an invalid domain or a failed fetch returns `{ "error": "...", "target": "..." }` and exits with code `2`. A network error adds `code`, such as `EAI_AGAIN`. An unknown option, a second domain and a missing domain return `{ "error": "..." }` only, with no target, and also exit with code `2`.
88
90
 
89
91
  In an error report the `target` is the address given on the command line. When it parses as a URL with a host, the user name and password are removed and each query value becomes `***`. Other values follow these cases:
90
92
 
91
- - In a value such as `user:secret@example.com`, the part before the colon reads as a URL scheme and is shown as `user:***@example.com`.
92
- - A value with no scheme and no slash is read as user information when a colon comes before its last `@`, so `user_name:secret@example.com` is shown as `***@example.com`.
93
+ - In a value such as `user:secret@example.com` or `example.org:8443#a@b`, the part before the colon reads as a URL scheme and no authority follows it, so only `//***` is shown.
94
+ - A value with no scheme and no slash is read as user information when a colon comes before its last `@` and before its first `?` or `#`. So `user_name:secret@example.com` and `user_name:se#cret@example.com` are shown as `***@example.com`. A backslash counts as part of the user name, as in a Windows domain account, so `CORP\erik:se#cret@example.com` is shown as `***@example.com` too. The same reading holds when such a value is a relative redirect target that is resolved against the request address, so the password does not come back in the path of the shown address. There a `?` or `#` before the last `@` shows only `***`, because the text after it could also be read as a query or a fragment. When a `?` or `#` comes before the colon, as in `user?x:secret@example.com`, the text from that character on is masked or cut, so the part before it is shown and the password is not.
93
95
  - Without that colon, as in `path@2x.png` or an e-mail address, the value is shown as given and holds no password.
96
+ - An address that holds an `@` shows only `***`, with the scheme in front when a slash follows its colon and with no host, when a URL parser and a person would read it differently. That covers a backslash, a `?` or a `#` before the `@` and before any `/`, and a start that is not exactly a scheme, two slashes and a character other than a slash. `https://user:pa?ss@example.com/`, `https://example.org?e=a@b.com` and `https:///host?e=a@b.com` are shown as `https://***`. `user:secret@host.example://dd`, where no slash follows the scheme colon, is shown as `//***`. The same holds for a word that a URL parser refuses as a scheme when a slash or a backslash follows its colon, as in `my_app:/user:secret@host`, and for an address that the parser refuses when a `?` or `#` comes before its last `@`, as in `https://user:pa/ss?secret@example.com`. A redirect to such an address is reported as "a different host that this report does not name". A `/` before the `@` makes it a path, and a relative reference such as `/a@b` or `docs/@name` is masked as before.
97
+ - Spaces, C0 control characters, Unicode spaces and invisible characters such as U+200B at either end of a value are removed before it is read, so a value that starts with U+2003 before `https:/user:secret@example.com` is read as `https:/user:secret@example.com` and shown as `https://***`.
98
+ - Text before `://` that a URL parser does not accept as a scheme, such as `my_app://user:secret@host/p`, `1app://user:secret@host/p` or `ht tps://user:secret@host/p`, is masked from the text: everything up to the last `@` is shown as `***`.
94
99
 
95
100
  ## What it checks
96
101
 
@@ -99,7 +104,7 @@ In an error report the `target` is the address given on the command line. When i
99
104
  | # | Check | Failure | Warning |
100
105
  | --- | --- | --- | --- |
101
106
  | 1 | `/llms.txt` returns HTTP 200 | Non-200 response, rejected or excessive redirects | none |
102
- | 2 | Response is plain text | Body looks like an HTML page | The media type, read without its parameters, is neither `text/plain` nor `text/markdown` |
107
+ | 2 | Response is plain text | Body looks like an HTML page | The media type, read without its parameters, with only spaces, tabs and line breaks removed from its ends and only ASCII letters lowercased, is neither `text/plain` nor `text/markdown` |
103
108
  | 3 | First non-empty line is a Markdown H1, written `# Title` or as one line of text underlined with `=` | Missing H1, a title indented as a code block, or an H1 with no text | none |
104
109
  | 4 | Blockquote summary follows the title | none | Missing summary, a blockquote block in which no line has text after the `>`, or a blockquote after other text but before the first H2, named by its line |
105
110
  | 5 | H2 sections group the content | none | No H2 sections, no section with a Markdown link list, a heading between the title and the first H2, or a second H1 |
@@ -121,18 +126,18 @@ Links are read the way CommonMark reads them for the forms listed here.
121
126
  - An unbracketed target keeps balanced parentheses, so `https://example.org/docs_(v2)` is read whole. A target with an unbalanced parenthesis is not a link, and neither is a reference definition whose destination is unbalanced. Write a target with an unbalanced parenthesis in angle brackets or escape the parenthesis. The nesting depth is not limited, where CommonMark stops at 32.
122
127
  - A link reference definition or label that spans several lines is not handled. A reference image whose label has a definition is skipped like an inline image. An empty target, `[Guide]()` or `[Guide](<>)`, is a link with an empty target and counts as a relative link.
123
128
  - A link written inside the description text of an image, as in `![alt [Guide](https://example.org/a)](https://example.org/img.png)`, does not count. An image without a target (`![alt [Guide](https://example.org/a)]`) is read the way CommonMark reads it: the inner link counts.
124
- - A pair of brackets inside a code span, as in `` [`Array[T]` reference](https://example.org/a) ``, neither closes nor opens a label. A link label ends where its paragraph ends. A heading, a bullet or a number starting at 1, a quote or a fence that can interrupt the paragraph therefore means there is no link.
129
+ - A pair of brackets inside a code span, as in `` [`Array[T]` reference](https://example.org/a) ``, neither closes nor opens a label. A link label ends where its paragraph ends. A line that can interrupt the paragraph, such as a heading, a bullet, a number starting at 1, a quote or a fence, therefore means there is no link. A backslash at the end of a line is a hard line break and escapes nothing, so the label does not continue into the next line: `- [Guide\` followed by `- more](https://example.org/a)` is two list items and no link. Until 0.8.0 the label continued into the next list item or heading.
125
130
  - A shortcut reference `[Guide]` counts after a colon in the same line and after an inline target that did not parse, as in `[Guide](not a link)`. A `[Guide]:` at the start of a definition line does not resolve against itself.
126
131
  - A link reference definition opens only where a block starts. It can open, for example, after a blank line, a heading, a fence or a thematic break. It can also open at the start of a quote, as a list item or right after another definition. A line that continues a paragraph or a list item is not a definition. A definition indented four columns or more inside a list item is not read. A link written in the destination of a definition line is still counted as a link.
127
132
  - Labels match by Unicode case folding. Character references in a target need their semicolon: `https&#58;//example.org` decodes, `https&#58//example.org` stays as written. A no-break or ideographic space is part of a target. Only an ASCII space, a tab or another control character ends one.
128
- - Here a raw HTML block is one of types 1 to 7 of CommonMark, written at the start of the line and outside quotes and list items. Its lines hold no links, definitions or list items for the checks. The no-HTML check still reads them. A fence opener inside an HTML block is still read as a fence.
133
+ - In this validator a raw HTML block is one of types 1 to 7 of CommonMark, and it is read only where its start is certain. The opener must be on the first line, after a blank line, or after a heading that itself stood at such a place. It must be indented at most three columns and stand outside every open list item. Under a paragraph line, a quote line, a list item line or another HTML line the opener hides nothing, and the lines after it keep their ordinary reading. The lines of a block hold no links, definitions, list items or headings for the checks. A `## Docs` line inside such a block is part of the block and no H2 section. Examples are the line between `<?x` and `?>` and the line directly under a `<div>` that stands after a blank line, with no blank line between them. Until 0.8.0 such a line counted as a section. The no-HTML check still reads them. A fence opener inside an HTML block is still read as a fence.
129
134
  - A title, a link name or a summary whose text is only character references to white space, code spans of white space or empty quote markers counts as empty: `# &#32;`, `` [` `](https://example.org/a) ``, `>>` and `> >`. A line with only a no-break or ideographic space is not a blank line.
130
135
  - A quote escaped with a backslash inside a link title, as in `[A](https://example.org/a "Ti\"tle\"")`, is not recognised, so that link is dropped. A title that spans a line break is dropped the same way.
131
136
  - Nested brackets in a link label, as in `[A [x] B](https://example.org/a)`, drop the link. A link label cannot span a blank line.
132
137
  - A backslash escape in a target is resolved before the URL test, so `https\://example.org/guide` is read as `https://example.org/guide`.
133
138
  - CR and CRLF line endings are read as LF. A setext title, which is a text line underlined with `=`, is read only when it is a single line.
134
139
 
135
- A heading is an H2 when `##` is followed by a space or a tab, or when it is one line of text underlined with hyphens. The text line must follow a blank line or the start of the file. A list item above a line of hyphens is not an H2, and neither is a line of hyphens after a blank line.
140
+ A heading is an H2 when `##` is followed by a space or a tab, or when it is one line of text underlined with hyphens. The text line must follow a blank line or the start of the file. A list item above a line of hyphens is not an H2, and neither is a line of hyphens after a blank line. A line inside a raw HTML block is not a heading either.
136
141
 
137
142
  A link in a four-space indented code block counts as a link unless a backtick pair encloses it. Such a block does not count as a file list under an H2, inside a list item (five or more spaces after the marker, or six columns after a blank line under `- item`) or outside one.
138
143
 
@@ -152,9 +157,9 @@ These checks are labelled **v2** in the output. They look for link relations in
152
157
  | 9 | Home page points to its llms.txt | `rel="describedby"` has a non-empty target | `info` |
153
158
  | 10 | Home page points to a Markdown version | `rel="alternate"` has media type `text/markdown` and a non-empty target | `info` |
154
159
 
155
- The validator detects these declarations without fetching their targets. It reads the first 65,536 UTF-16 code units of the head after comments and the contents of script, style, title, noscript, noframes and template elements have been set aside. When a relation is missing from a longer head, the result says that only that part was read.
160
+ The validator detects these declarations without fetching their targets. It reads the first 65,536 UTF-16 code units of the head after comments and the contents of script, style, title, noscript, noframes and template elements have been set aside. When a relation is missing from a longer head, the result says that only that part was read. Inside a script, `<!-->` and `<!--->` end the comment escape at once, as the HTML tokenizer reads them, and a `<template>` inside `<svg>` or `<math>` is an ordinary element that opens no template level. Until 0.8.0 both shapes made the scan skip a relation that the parser puts in the head, or read one that it moves into the body.
156
161
 
157
- The home page itself is read up to 256 KiB. When it was cut there and no relation is found in the part that was read, the info text says "in the first 256 KiB of the home page, the part that was read, or in the Link header". A target is shown with its credentials and fragment removed and its query values masked.
162
+ The home page itself is read up to 256 KiB. When a relation is missing, the info text names at most one of the two limits. If the head is longer than 65,536 characters, it names that limit, "in the first 65,536 characters of the head, the part that was read, or in the Link header", even when the page was also cut at 256 KiB. If the head is within the limit and the page was cut at 256 KiB, it says "in the first 256 KiB of the home page, the part that was read, or in the Link header". With neither limit reached it says "in the head or the Link header". A relation found in the part that was read is reported as found. A target is shown with its credentials and fragment removed and its query values masked.
158
163
 
159
164
  A `Link` header value that has an `anchor` parameter is used only when the anchor is empty or resolves to the home page address. This is because an anchored value describes another resource.
160
165
 
@@ -185,6 +190,28 @@ for (const check of problems) {
185
190
 
186
191
  The package also exports the helper functions and types behind `validateHost`, such as `fetchLlmsTxt`, `validateLlmsTxt` and `maskLocation`. The hosted validator keeps its own copies of the same logic. These exports are not documented here as a stable interface. Treat `validateHost` and the types above as the supported surface.
187
192
 
193
+ ### Options for library callers
194
+
195
+ `validateHost(input, options)` and `fetchLlmsTxt(host, options)` take the same `ValidateHostOptions`. The command line sets none of them.
196
+
197
+ | Option | Meaning | Accepted values |
198
+ | --- | --- | --- |
199
+ | `timeoutMs` | Time budget for one document, shared across its redirect chain. The default is `8000`. | An integer from 1 to 2,147,483,647. |
200
+ | `cap` | Read limit in bytes per response. The default is `262144`, which is 256 KiB. | An integer from 1 to 2,097,152. |
201
+ | `userAgent` | Value of the `user-agent` request header. | A string that the platform accepts as a header value. |
202
+ | `accept` | Value of the `accept` request header, read by `fetchLlmsTxt`. | A string that the platform accepts as a header value. |
203
+ | `path` | Path and query of the request, read by `fetchLlmsTxt`. The default is `/llms.txt`. | A string that starts with a single `/`. |
204
+
205
+ `validateHost` pins its two reads to `/llms.txt` and `/`, each with its own `accept` value, so it ignores `path` and `accept`.
206
+
207
+ A call rejects before any request is sent when an option is outside these values. `undefined` and `null` mean the default for `timeoutMs`, `cap` and `path`. `timeoutMs` and `cap` reject with a `RangeError`: `NaN`, `Infinity`, `0`, a negative number, a fraction, a string and a value above the maximum are all refused. Until 0.8.0, `NaN` and `Infinity` as `cap` switched the read limit off, and a `cap` of several megabytes could end in an internal `RangeError`. The maximum of `cap` is there because the HTML check reads the whole body with one pattern, and a body of several megabytes of attribute-like text made it run out of stack.
208
+
209
+ `path` rejects with a `TypeError` when it does not start with a single `/` or holds a C0 control character or DEL. C1 control characters are accepted. This covers an empty string, `x`, `:8443/x`, `@host/x`, `//host/x`, a backslash right after the slash, an absolute URL and a query or fragment alone. Such a path could change the port or the host of the request. A path that starts with a single `/` can carry only a path and a query, and the request keeps the host that was checked.
210
+
211
+ The size note of check 7 says "over 256 KiB, read truncated" whatever `cap` is, because the check only reads whether the body was cut.
212
+
213
+ The package calls the `fetch` of the process it runs in. A replaced global `fetch`, a proxy or disabled certificate checks in that process change what the guarantees on this page mean.
214
+
188
215
  ## Use in CI
189
216
 
190
217
  Add this step to a GitHub Actions job that already has Node.js 22 or newer available. Replace `your-domain.com` with your domain:
@@ -201,7 +228,7 @@ Any CI runner with Node.js 22 or newer can run the same command. Omit `--strict`
201
228
  The default validation requests two documents: `https://<host>/llms.txt` and `https://<host>/`. Redirects may add requests, but linked pages and discovery targets are never fetched. The validator stores no results.
202
229
 
203
230
  - Timeout: eight seconds per document, shared across its redirect chain.
204
- - Read limit: 256 KiB, which is 262,144 bytes, per response. A file cut there gets the size note "over 256 KiB, read truncated".
231
+ - Read limit: 256 KiB, which is 262,144 bytes, per response by default. A file cut there gets the size note "over 256 KiB, read truncated". A library caller can change the limit, see the options above.
205
232
  - Redirects: up to four hops, over HTTPS, to the same host or its `www`/apex equivalent. Off-site redirects, embedded credentials and unsupported ports are rejected. A redirect target is reported with its credentials and fragment removed and its query values masked, whether the redirect was followed or rejected.
206
233
  - Host checks: IP literals, bracketed IPv6 addresses, localhost and the internal-use TLDs `localdomain`, `local`, `internal`, `home`, `lan`, `corp`, `test`, `invalid`, `arpa` and `onion` are rejected before a request is sent. An address that holds `@`, `?` or `#` is not repeated in the error message, because it can carry a user name, a password or a query value. One trailing dot on the host you give, as in `example.com.`, is removed first. Redirect targets are checked too, and one trailing dot on a redirect target is removed the same way.
207
234
 
@@ -226,12 +253,12 @@ The strict type check found two inputs that could leave `undefined` in a check's
226
253
  GitHub Actions publishes every version from 0.1.3 on with npm trusted publishing, and each one carries a provenance attestation. To check one, install it in an empty directory and ask npm to verify the signatures. Replace the version with the one you want to check.
227
254
 
228
255
  ```sh
229
- mkdir verify-llms && cd verify-llms && npm init -y && npm install turva-llms-txt-validator@0.7.4 --ignore-scripts && npm audit signatures
256
+ mkdir verify-llms && cd verify-llms && npm init -y && npm install turva-llms-txt-validator@0.8.1 --ignore-scripts && npm audit signatures
230
257
  ```
231
258
 
232
259
  `npm audit signatures` checks the registry signature and the provenance attestation of each installed package that has one. The attestation of this package names three things to compare with what you expect: the repository `github.com/erekola/llms-txt-validator`, the workflow file `.github/workflows/publish.yml` and the commit that produced the tarball. The npm version page shows them under Provenance.
233
260
 
234
- Tag `v0.7.4` must point at that same commit, and `gh api repos/erekola/llms-txt-validator/commits/v0.7.4 --jq .sha` prints it. A mismatch is a reason not to use that version. Provenance proves which workflow built a release and from which commit. It does not prove that the code is safe, so reading the source and the dependencies stays your job.
261
+ Tag `v0.8.1` must point at that same commit, and `gh api repos/erekola/llms-txt-validator/commits/v0.8.1 --jq .sha` prints it. A mismatch is a reason not to use that version. Provenance proves which workflow built a release and from which commit. It does not prove that the code is safe, so reading the source and the dependencies stays your job.
235
262
 
236
263
  ## Development
237
264
 
@@ -46,7 +46,7 @@ export type FetchOptions = ValidateHostOptions;
46
46
  export type LlmsTxtInput = FetchRedirect | (Partial<FetchedLlmsTxt> & Pick<FetchedLlmsTxt, "status" | "contentType" | "text" | "bytes" | "truncated">);
47
47
  export declare const VERSION: string;
48
48
  export declare function cut(s: string | number, n: number): string;
49
- export declare function maskLocation(href: string, base?: string): string;
49
+ export declare function maskLocation(href: string, base?: string, written?: string): string;
50
50
  export declare function stripBidi(s: unknown): string;
51
51
  export declare function stripControls(s: unknown): string;
52
52
  export declare function normalizeHostInput(raw: unknown): string | null;
package/dist/src/index.js CHANGED
@@ -31,13 +31,176 @@ export function cut(s, n) {
31
31
  // review, 2026-09-22). A target the URL parser refuses is masked by hand: nothing after the first ?
32
32
  // or # survives, and when the target has a scheme or starts with two slashes, everything up to the
33
33
  // last @ before them is shown as ***. Mirrors worker.ts maskLocation().
34
- export function maskLocation(href, base) {
35
- let u = null;
36
- try {
37
- u = new URL(href, base);
34
+ // User information is also recognised from the text, not only from the parser: a ? or # inside it ends the
35
+ // authority for the parser, which then reads "https://user:pa?ss@host/" as host "user", port "pa" and a query
36
+ // (or refuses it), and a scheme the parser refuses ("my_app://", "1app://", "ht tps://") lets it resolve the text
37
+ // as a relative path. In both cases the text before the last @ is still user information to a reader, so it is
38
+ // masked from the text. The optional third argument is the text an address was written as, when href is its
39
+ // parsed form: if that text hides user information the parser moved, it is masked instead of the parsed form.
40
+ // When a parser and a reader would disagree about where the user information ends, only the scheme and "//***" are
41
+ // shown, so no host is named either. The decision is made once, from the written text, at the top of the function.
42
+ export function maskLocation(href, base, written) {
43
+ // The characters a URL parser drops before it reads anything: tab, CR and LF wherever they stand, and C0 controls
44
+ // and spaces at either end. Until 2026-11-22 only the first three went, so a leading space or control character hid
45
+ // a scheme from the ambiguity test below, and " https:/user:pw@@host" against a base printed the password in the
46
+ // resolved path (V4-3, outside fuzz run 2026-11-22).
47
+ // The same reading also removes, at either end, the invisible characters that a URL parser keeps: the Unicode
48
+ // white space, U+0085, U+180E, U+200B and U+FFFD. A reader does not see them, so a value that starts with U+2003
49
+ // and then https:/user:pw@host is read as the address it shows (L3 of the third independent check).
50
+ const edge = "[\\x00-\\x20\\s" + String.fromCharCode(0x85, 0x180e, 0x200b, 0xfffd) + "]+";
51
+ const parserInput = (t) => t.replace(/[\t\n\r]/g, "").replace(new RegExp("^" + edge + "|" + edge + "$", "g"), "");
52
+ const text = parserInput(String(href));
53
+ // Where an authority starts in a text, read from the text and not from the parser: after a scheme and two slashes, the
54
+ // scheme being whatever stands before "://" with no / \ ? or # in it. invalid is true when that "scheme" is not one.
55
+ const shapeOf = (t) => {
56
+ const m = /^[a-z][a-z0-9+.-]*:/i.exec(t);
57
+ let start = m ? m[0].length : 0;
58
+ let invalid = false;
59
+ const sep = t.indexOf("://");
60
+ if (sep >= 0 && !(m && m[0].length === sep + 1) && !/[\/\\?#]/.test(t.slice(0, sep))) {
61
+ start = sep + 1;
62
+ invalid = true;
63
+ }
64
+ let from = start;
65
+ while (from < t.length && (t[from] === "/" || t[from] === "\\"))
66
+ from++;
67
+ return { start, from, scheme: m !== null || invalid, invalid };
68
+ };
69
+ // Ambiguity is decided once, from the written text alone, before any branch below reads it. A text that holds an @ is
70
+ // read the same way by a URL parser and by a person only when it starts exactly as "<scheme>://" or "//" followed by a
71
+ // character that is no slash, and no backslash, ? or # stands between that start and the first slash or the last @. Any
72
+ // other start is read differently by each reader (three slashes, a backslash, a scheme colon with no or one slash, a
73
+ // later "://" after the @, an @ before the scheme colon), and so is a ? or # in front of the @ (the parser reads the host
74
+ // before it and a query after it, a person reads the text before the @ as user information). Such a text shows only its
75
+ // scheme, or nothing, and no host. A start with no scheme-like word and no leading // is a relative reference and is
76
+ // not decided here: "/a@b", "docs/@name", "?e=a@b.com" and "#x@y" keep the reading they have below.
77
+ const ambiguous = (t) => {
78
+ if (!t.includes("@"))
79
+ return false;
80
+ const m = /^[a-z][a-z0-9+.-]*:/i.exec(t);
81
+ const sep = t.indexOf("://");
82
+ // A word the URL parser refuses as a scheme, followed directly by a slash or a backslash, as in my_app:/user:pw@host,
83
+ // reads as a scheme to a person and as a relative path to the parser (L2 of the third independent check).
84
+ const lead = m ? m[0] : sep >= 0 && !/[\/\\?#]/.test(t.slice(0, sep)) ? t.slice(0, t.indexOf(":") + 1) : ((/^[^\/\\?#@:]+:(?=[\/\\])/.exec(t)) || [""])[0];
85
+ if (lead.includes("@"))
86
+ return true;
87
+ if (lead === "" && !/^[\/\\]{2}/.test(t))
88
+ return false;
89
+ const p = lead.length;
90
+ if (t[p] !== "/" || t[p + 1] !== "/" || p + 2 >= t.length || t[p + 2] === "/" || t[p + 2] === "\\")
91
+ return true;
92
+ const lastAt = t.lastIndexOf("@");
93
+ if (lastAt < p + 2)
94
+ return false;
95
+ const slash = t.indexOf("/", p + 2);
96
+ return /[\\?#]/.test(t.slice(p + 2, slash >= 0 && slash < lastAt ? slash : lastAt));
97
+ };
98
+ if (written !== undefined) {
99
+ const w = parserInput(String(written));
100
+ // A written form that lost invisible characters at its ends was resolved by the parser with them, so href is not the
101
+ // address the reading sees, and the written form is masked instead (differential fuzz against 3.260.6).
102
+ const parserOwn = String(written).replace(/[\t\n\r]/g, "").replace(/^[\x00-\x20]+|[\x00-\x20]+$/g, "");
103
+ if (ambiguous(w) || shapeOf(w).invalid || (w !== parserOwn && w.includes("@")))
104
+ return maskLocation(written, base);
105
+ }
106
+ if (ambiguous(text)) {
107
+ // The scheme is shown when a slash follows its colon; with no slash the text before the colon may be a user name.
108
+ const scheme = /^([\w+.-]{1,32}):[\/\\]/.exec(text);
109
+ return (scheme ? scheme[1] + ":" : "") + "//***";
110
+ }
111
+ const shape = shapeOf(text);
112
+ // The reading from the text alone. It is the answer when the URL parser finds no host, and for a text with no
113
+ // scheme-like start and no authority start (two leading slashes or backslashes) it is tried before the parser, below.
114
+ // masked records whether it hid user information.
115
+ let masked = false;
116
+ const fromText = () => {
117
+ let s = text;
118
+ const stop = s.search(/[?#]/);
119
+ // A ? or # before the last @ can still belong to the user information of a text that has no scheme-like start
120
+ // ("user_name:pa?ss@host"). When a colon and no slash stands before that ?, everything up to the last @ is shown as
121
+ // ***, and the cut at the ? or # applies to what follows it. A backslash is no slash here: in a text with no scheme a
122
+ // person reads a backslash between a Windows domain and a user name as part of the user name, and until 2026-11-22
123
+ // a backslash before the # showed the text up to it, the start of the password included (V4-1, outside fuzz run
124
+ // 2026-11-22). A scheme or an authority with a ? before the @ is ambiguous and has returned above.
125
+ if (stop >= 0 && stop >= shape.from) {
126
+ const lastAt = s.lastIndexOf("@");
127
+ if (lastAt > stop && shape.from - shape.start < 2 && s.slice(0, stop).includes(":") && !s.slice(shape.start, stop).includes("/")) {
128
+ const rest = s.slice(lastAt + 1);
129
+ const rs = rest.search(/[?#]/);
130
+ masked = true;
131
+ return s.slice(0, shape.from) + "***@" + (rs >= 0 ? rest.slice(0, rs) + (rest[rs] === "?" ? "?***" : "") : rest);
132
+ }
133
+ }
134
+ if (stop >= 0)
135
+ s = s.slice(0, stop) + (s[stop] === "?" ? "?***" : "");
136
+ const after = shapeOf(s);
137
+ const hasScheme = after.scheme;
138
+ const start = after.start;
139
+ const from = after.from;
140
+ // Without a scheme and two slashes there is normally no authority, and an @ is part of a
141
+ // path ("path@2x.png" stays unmasked below). But when an @ still appears before the first
142
+ // /, the text ahead of it reads as userinfo even when the parser here does not recognise it
143
+ // as a scheme (an underscore, a leading digit or space, a stray control character), so that
144
+ // shape is masked too instead of let through (VN1, round 3 Tek-542). With no slash at all
145
+ // the same holds when a ":" comes before the last @: "user_name:secret@example.com" is
146
+ // user:password and is masked, while "path@2x.png" has no ":" ahead of its @ and stays as
147
+ // given (outside review V13, D5-1: the slashless shape used to return early and print the
148
+ // password).
149
+ if (!hasScheme && from - start < 2) {
150
+ const firstSlash = s.indexOf("/");
151
+ const firstAt = s.indexOf("@");
152
+ if (firstAt < 0)
153
+ return s;
154
+ if (firstSlash < 0) {
155
+ if (!s.slice(0, s.lastIndexOf("@")).includes(":"))
156
+ return s;
157
+ }
158
+ else if (firstAt > firstSlash) {
159
+ return s;
160
+ }
161
+ }
162
+ // Nothing tells which @ of a refused target ends the user information, so everything up to the
163
+ // last one is shown as ***. The mask is visible on purpose: three review rounds on 2026-09-22
164
+ // measured every rule that guessed, and each one either returned a password that holds a slash
165
+ // or made the host vanish without a trace.
166
+ const at = s.lastIndexOf("@");
167
+ if (at < from)
168
+ return s;
169
+ masked = true;
170
+ return s.slice(0, from) + "***@" + s.slice(at + 1);
171
+ };
172
+ // A text with no scheme-like start and no authority start is a relative reference to a URL parser, and against a base
173
+ // it resolves into a path: "user_name:pw@host" became "https://<base host>/user_name:pw@host", and a redirect refused
174
+ // as one hop too many passes the request URL as that base (outside fuzz run 2026-11-22, the base form of V4-1). A
175
+ // person reads such a text as user information and a host, so when the reading from the text hides user
176
+ // information that answer stands with or without a base. A ? or # before the last @ with a colon between them hides
177
+ // user information that the parser reads as a query name or a fragment ("user?x:pw@host" against a base showed
178
+ // "x:pw@host" as the query name), so the cut form from the text is shown then too. A relative reference with no colon
179
+ // before its last @, such as "path@2x.png", "@scope/pkg" or "p?mail=a@b.com", is still resolved against the base
180
+ // below, as before.
181
+ const lastAtText = text.lastIndexOf("@");
182
+ if (!shape.scheme && shape.from - shape.start < 2 && lastAtText > 0 && text.slice(0, lastAtText).includes(":")) {
183
+ const shown = fromText();
184
+ const cut = text.search(/[?#]/);
185
+ const cutBeforeAt = cut >= 0 && cut < lastAtText;
186
+ // With a base the URL reading puts the text after a ? or # into a query or a fragment and masks it, while the text
187
+ // reading shows the text after the last @ as a host, so only *** is shown and neither reading shows the other's part
188
+ // (differential fuzz against 3.260.6).
189
+ if (masked)
190
+ return base !== undefined && cutBeforeAt ? "***" : shown;
191
+ if (cutBeforeAt && text.slice(cut, lastAtText).includes(":"))
192
+ return shown;
38
193
  }
39
- catch {
40
- u = null;
194
+ let u = null;
195
+ if (!shape.invalid) {
196
+ // The parser reads the same text as the reading above. Given href, it kept a leading U+00A0 or U+2003 and resolved
197
+ // "<U+00A0>https://user:pw@host/p" against a base as a relative path with the password in it (fifth check).
198
+ try {
199
+ u = new URL(text, base);
200
+ }
201
+ catch {
202
+ u = null;
203
+ }
41
204
  }
42
205
  // An opaque URL (no authority, e.g. "u:name@host/") parses without throwing but has no
43
206
  // host, so clearing u.username/u.password is a silent no-op: WHATWG has nowhere to put
@@ -61,43 +224,17 @@ export function maskLocation(href, base) {
61
224
  u.hash = "";
62
225
  return u.href;
63
226
  }
64
- let s = String(href).replace(/[\t\n\r]/g, "");
65
- const stop = s.search(/[?#]/);
66
- if (stop >= 0)
67
- s = s.slice(0, stop) + (s[stop] === "?" ? "?***" : "");
68
- const scheme = /^[a-z][a-z0-9+.-]*:/i.exec(s);
69
- const start = scheme ? scheme[0].length : 0;
70
- let from = start;
71
- while (from < s.length && (s[from] === "/" || s[from] === "\\"))
72
- from++;
73
- // Without a scheme and two slashes there is normally no authority, and an @ is part of a
74
- // path ("path@2x.png" stays unmasked below). But when an @ still appears before the first
75
- // /, the text ahead of it reads as userinfo even when the parser here does not recognise it
76
- // as a scheme (an underscore, a leading digit or space, a stray control character), so that
77
- // shape is masked too instead of let through (VN1, round 3 Tek-542). With no slash at all
78
- // the same holds when a ":" comes before the last @: "user_name:secret@example.com" is
79
- // user:password and is masked, while "path@2x.png" has no ":" ahead of its @ and stays as
80
- // given (outside review V13, D5-1: the slashless shape used to return early and print the
81
- // password).
82
- if (!scheme && from - start < 2) {
83
- const firstSlash = s.indexOf("/");
84
- const firstAt = s.indexOf("@");
85
- if (firstAt < 0)
86
- return s;
87
- if (firstSlash < 0) {
88
- if (!s.slice(0, s.lastIndexOf("@")).includes(":"))
89
- return s;
90
- }
91
- else if (firstAt > firstSlash) {
92
- return s;
93
- }
227
+ // A scheme and an authority start that the URL parser refuses, as with the port "pa" in https://user:pa/ss?pw@host,
228
+ // and a ? or # before the last @: no parse tells where the user information ends, and the cut at the ? showed part
229
+ // of the password, so only the scheme is shown (fourth independent check). A refused target with no ? or # before
230
+ // its last @ keeps the reading below, everything up to the last @ shown as ***.
231
+ const qAt = text.slice(shape.from).search(/[?#]/);
232
+ if (!shape.invalid && shape.from - shape.start >= 2 && qAt >= 0 && text.lastIndexOf("@") > shape.from + qAt) {
233
+ const sc = /^[a-z][a-z0-9+.-]*:/i.exec(text);
234
+ if (sc)
235
+ return sc[0] + "//***";
94
236
  }
95
- // Nothing tells which @ of a refused target ends the user information, so everything up to the
96
- // last one is shown as ***. The mask is visible on purpose: three review rounds on 2026-09-22
97
- // measured every rule that guessed, and each one either returned a password that holds a slash
98
- // or made the host vanish without a trace.
99
- const at = s.lastIndexOf("@");
100
- return at < from ? s : s.slice(0, from) + "***@" + s.slice(at + 1);
237
+ return fromText();
101
238
  }
102
239
  // Unicode bidi controls (U+202A to U+202E, U+2066 to U+2069) have no place in a check's
103
240
  // detail: text quoted from the fetched file could otherwise read in a different order here
@@ -113,6 +250,23 @@ export function stripBidi(s) {
113
250
  export function stripControls(s) {
114
251
  return String(s).replace(/[\u0000-\u001F\u007F-\u009F]/g, "");
115
252
  }
253
+ // Invisible characters leave a check's detail too, by Unicode class and not from a list kept by hand: every
254
+ // format character (General_Category Cf: the zero-width characters, the left-to-right and right-to-left marks
255
+ // and the Arabic letter mark, the bidi controls, the invisible math operators, the soft hyphen, the byte-order
256
+ // mark, the tag characters U+E0000 to U+E007F), every Default_Ignorable_Code_Point (also the variation
257
+ // selectors U+FE00 to U+FE0F and U+E0100 to U+E01EF, the combining grapheme joiner and the Hangul fillers),
258
+ // and the line and paragraph separators U+2028 and U+2029 (Zl and Zp). They reorder or hide text that a
259
+ // reader sees differently from a program. Ordinary spaces (U+00A0, U+2000 to U+200A, U+202F, U+205F,
260
+ // U+3000) are not in the class and stay. Cost: an emoji sequence loses its zero-width joiners and its
261
+ // variation selector, so a family emoji reads as its members side by side, a heart written with U+FE0F shows
262
+ // in text style, and a tag flag shows as its black flag. The same class takes the zero-width non-joiner and
263
+ // joiner out of words that need them to join or to stay apart, so a quoted Persian, Malayalam or Devanagari
264
+ // word loses its joining mark and reads without it, and it takes the soft hyphen, the Arabic number signs
265
+ // U+0600 to U+0605 and the end-of-ayah mark U+06DD, which show as glyphs. Mirrors worker.ts stripInvisible();
266
+ // it is not exported, and validateHost applies it with the two functions above.
267
+ function stripInvisible(s) {
268
+ return String(s).replace(/[\p{Cf}\p{Default_Ignorable_Code_Point}\p{Zl}\p{Zp}]/gu, "");
269
+ }
116
270
  export function normalizeHostInput(raw) {
117
271
  // The hosted validator removes tab, CR and LF from the typed address before it reads it, then trims
118
272
  // (worker.ts, the /llms-txt-validator route). The URL parser would remove the same three characters
@@ -180,6 +334,42 @@ export function isValidPublicHost(host) {
180
334
  return false;
181
335
  return true;
182
336
  }
337
+ // The largest read limit a caller may ask for, and the largest timeout the platform timer takes. The HTML
338
+ // check reads the whole body with one pattern, and a body of attribute-like text that is several megabytes
339
+ // long overflowed the engine's stack inside it, so a larger limit could end in an internal RangeError. 2 MiB
340
+ // is eight times the default and below the smallest size where that was measured.
341
+ const MAX_CAP = 2097152;
342
+ const MAX_TIMEOUT_MS = 2147483647;
343
+ // opts.timeoutMs and opts.cap come from the caller. A value that is not a whole number in range used to
344
+ // switch the limit off (NaN and Infinity made the size test false for every chunk) or to throw from inside
345
+ // the read loop, so it is refused before the first request instead.
346
+ function requestLimits(opts) {
347
+ const timeoutMs = opts.timeoutMs ?? 8000;
348
+ const cap = opts.cap ?? 262144;
349
+ if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_TIMEOUT_MS)
350
+ throw new RangeError("opts.timeoutMs must be an integer from 1 to " + MAX_TIMEOUT_MS + " (milliseconds)");
351
+ if (typeof cap !== "number" || !Number.isInteger(cap) || cap < 1 || cap > MAX_CAP)
352
+ throw new RangeError("opts.cap must be an integer from 1 to " + MAX_CAP + " (bytes)");
353
+ return { timeoutMs, cap };
354
+ }
355
+ // opts.path is joined to a host that was checked already, so it may carry a path and a query and nothing else.
356
+ // A path that does not start with a slash can change the port or the end of the host name (":8443/x",
357
+ // ".other.example/x", "x"), and one that starts with two slashes or a slash and a backslash is an address with
358
+ // another host in the eyes of a URL parser. Control characters are refused as well: a parser removes tab, CR
359
+ // and LF silently, and that changes what the text means.
360
+ function requestPath(path) {
361
+ if (path === undefined || path === null)
362
+ return "/llms.txt";
363
+ const refuse = () => { throw new TypeError('opts.path must start with a single "/" (not "//" or "/\\") and hold no control character: only a path and a query can be given, never a host or a port'); };
364
+ if (typeof path !== "string" || path[0] !== "/" || path[1] === "/" || path[1] === "\\")
365
+ return refuse();
366
+ for (let i = 0; i < path.length; i++) {
367
+ const c = path.charCodeAt(i);
368
+ if (c < 32 || c === 127)
369
+ return refuse();
370
+ }
371
+ return path;
372
+ }
183
373
  // opts.path and opts.accept were added for the v2 discovery checks, which need the
184
374
  // site's home page as well as its llms.txt. Nothing else moved: the redirect budget,
185
375
  // the same-host rule, the credential and port rejections and the 256 KiB cap are the
@@ -195,10 +385,16 @@ export async function fetchLlmsTxt(host, opts = {}) {
195
385
  if (!normalized || !isValidPublicHost(normalized))
196
386
  return { redirect: true, reason: "unsafe-target", status: 0, location: "" };
197
387
  host = normalized;
198
- const timeoutMs = opts.timeoutMs ?? 8000;
199
- const cap = opts.cap ?? 262144;
388
+ const { timeoutMs, cap } = requestLimits(opts);
200
389
  const reqApex = host.startsWith("www.") ? host.slice(4) : host;
201
- let url = "https://" + host + (opts.path ?? "/llms.txt");
390
+ let url = "https://" + host + requestPath(opts.path);
391
+ // The address is parsed once before the first request: it must still name the https scheme, the checked host,
392
+ // the default port and no credentials. A path that passed requestPath cannot change that, so this is a second lock.
393
+ {
394
+ const first = new URL(url);
395
+ if (first.protocol !== "https:" || first.hostname !== host || first.port !== "" || first.username !== "" || first.password !== "")
396
+ throw new Error("the request address does not keep the host that was checked");
397
+ }
202
398
  let redirectedFrom = null;
203
399
  // One budget for the whole redirect chain, not one per hop. Mirrors the hosted validator
204
400
  // (turva.dev/llms-txt-validator), which is canonical: with five hops a per-hop signal made
@@ -239,9 +435,9 @@ export async function fetchLlmsTxt(host, opts = {}) {
239
435
  const safeTarget = next.protocol === "https:" && !next.port && !next.username && !next.password && isValidPublicHost(next.hostname);
240
436
  const twin = (next.hostname.startsWith("www.") ? next.hostname.slice(4) : next.hostname) === reqApex;
241
437
  if (!safeTarget)
242
- return { redirect: true, reason: "unsafe-target", status: res.status, location: cut(maskLocation(next.href), 120) };
438
+ return { redirect: true, reason: "unsafe-target", status: res.status, location: cut(maskLocation(next.href, undefined, loc), 120) };
243
439
  if (!twin)
244
- return { redirect: true, reason: "off-host", status: res.status, location: cut(maskLocation(next.href), 120) };
440
+ return { redirect: true, reason: "off-host", status: res.status, location: cut(maskLocation(next.href, undefined, loc), 120) };
245
441
  if (!redirectedFrom)
246
442
  redirectedFrom = url;
247
443
  url = next.href;
@@ -666,20 +862,34 @@ function collectLinkDefinitions(text, lineBlocks, defAt) {
666
862
  // is read as plain brackets, and so is a shortcut reference "[text]" after an inline attempt that did not parse (S3, LV-11). A
667
863
  // resolved or inline target is decoded for backslash escapes and complete character references ("&#58;", "&amp;", ...), the
668
864
  // way CommonMark does and not like an HTML attribute (S3, LV-18). The scan carries no bound and no backtracking: the closing
669
- // ">", quote and line end are looked up through a cache that only moves forward, and the parenthesis pairs of a plain target
670
- // are built once, so a file that repeats "[a](" or "[a](x \"" stays linear.
865
+ // ">", quote, "]" and line end are looked up in a list of every position of that character, built on its first use and
866
+ // searched by bisection, so a look-up costs the same in whatever order the queries come, and the parenthesis pairs of a
867
+ // plain target are built once, so a file that repeats "[a](", "![" or "[a](x \"" stays linear.
671
868
  function collectLinks(text, defs, lineBlocks) {
672
869
  const out = [];
673
870
  const code = codeSpanMask(text, lineBlocks);
674
871
  const refs = defs || collectLinkDefinitions(text, lineBlocks);
675
- const cache = Object.create(null);
872
+ // The index of the first c at or after from, or -1. A cache of the last answer only helped queries that move
873
+ // forward; a query that moves back made the next one scan from the start again, which is quadratic on a text of
874
+ // "![" openers whose labels and targets are looked up from the inside out.
875
+ const positions = Object.create(null);
676
876
  const nextIdx = (c, from) => {
677
- const h = cache[c];
678
- if (h && h.from <= from && (h.at === -1 || h.at >= from))
679
- return h.at;
680
- const at = text.indexOf(c, from);
681
- cache[c] = { from, at };
682
- return at;
877
+ let p = positions[c];
878
+ if (!p) {
879
+ p = [];
880
+ for (let k = text.indexOf(c); k !== -1; k = text.indexOf(c, k + 1))
881
+ p.push(k);
882
+ positions[c] = p;
883
+ }
884
+ let lo = 0, hi = p.length;
885
+ while (lo < hi) {
886
+ const mid = (lo + hi) >> 1;
887
+ if (p[mid] < from)
888
+ lo = mid + 1;
889
+ else
890
+ hi = mid;
891
+ }
892
+ return lo < p.length ? p[lo] : -1;
683
893
  };
684
894
  const isBlank = (c) => c === " " || c === "\t";
685
895
  // A blank line ends a paragraph, and a link label cannot reach across one (Tek-560); neither can it reach across a line that
@@ -813,10 +1023,12 @@ function collectLinks(text, defs, lineBlocks) {
813
1023
  return e < text.length ? afterTarget(text.slice(k, e), e) : null;
814
1024
  };
815
1025
  // The text of a link label from j on, up to the "]" or "[" that ends it or the line break that ends the paragraph. A bracket
816
- // inside a code span is code and neither closes nor opens (S3, LV-05 and U-7).
1026
+ // inside a code span is code and neither closes nor opens. A backslash before a line break is a hard
1027
+ // line break and escapes nothing, so the break still ends the paragraph it ends (CommonMark); the label scan and closeOf
1028
+ // below used to step over it, and a link label then ran on into the next list item or heading.
817
1029
  const scanLabel = (j) => {
818
1030
  while (j < text.length && (code[j] || (text[j] !== "]" && text[j] !== "[" && !blankAt(j))))
819
- j += !code[j] && text[j] === "\\" ? 2 : 1;
1031
+ j += !code[j] && text[j] === "\\" && text[j + 1] !== "\n" ? 2 : 1;
820
1032
  return j;
821
1033
  };
822
1034
  // A definition is decoded once, however many references use it: a long destination used by many labels would otherwise be
@@ -843,7 +1055,7 @@ function collectLinks(text, defs, lineBlocks) {
843
1055
  if (code[k])
844
1056
  continue;
845
1057
  const c = text[k];
846
- if (c === "\\")
1058
+ if (c === "\\" && text[k + 1] !== "\n")
847
1059
  k++;
848
1060
  else if (c === "[")
849
1061
  stack.push(k);
@@ -862,6 +1074,16 @@ function collectLinks(text, defs, lineBlocks) {
862
1074
  // unescaped "!". The alt text is read to the "]" that balances the "[" (S3, LV-08), so a link written inside it is image text
863
1075
  // and no link. Returns the index after the image, or null for a malformed one (no closing "]", no target, a label without a
864
1076
  // definition), which the callers treat as an ordinary bracket, the way CommonMark reads it.
1077
+ // The text between an image's "[" at k and its "]" at m, as a reference label, or "" when it cannot be one. A
1078
+ // definition label holds no "]" (collectLinkDefinitions reads it with a class that excludes the closing
1079
+ // bracket), so a text that holds one names no definition and is not worth normalizing. With nested openers, as
1080
+ // many "![" and then "]", every level would otherwise normalize everything inside it, which is quadratic. The
1081
+ // first "]" after the opener comes from the position list, and the texts that are normalized end at that first
1082
+ // "]", so no two of them overlap.
1083
+ const imageLabelText = (k, m) => {
1084
+ const c = nextIdx("]", k + 1);
1085
+ return c !== -1 && c < m ? "" : text.slice(k + 1, m);
1086
+ };
865
1087
  const skipImage = (k) => {
866
1088
  const m = closeOf()[k];
867
1089
  if (m < 0)
@@ -877,10 +1099,10 @@ function collectLinks(text, defs, lineBlocks) {
877
1099
  if (n >= text.length || text[n] !== "]")
878
1100
  return null;
879
1101
  const raw = text.slice(m + 2, n);
880
- const label = normalizeLinkLabel(raw === "" ? text.slice(k + 1, m) : raw);
1102
+ const label = normalizeLinkLabel(raw === "" ? imageLabelText(k, m) : raw);
881
1103
  return label && refs.has(label) ? n + 1 : null;
882
1104
  }
883
- const own = normalizeLinkLabel(text.slice(k + 1, m));
1105
+ const own = normalizeLinkLabel(imageLabelText(k, m));
884
1106
  return own && refs.has(own) ? m + 1 : null;
885
1107
  };
886
1108
  // True when the "[" at i sits where a link reference definition would start its line: only quote markers and a list marker
@@ -1077,7 +1299,7 @@ function isSetextH1(line, next) {
1077
1299
  const HTML_BLOCK_START = /^ {0,3}<(?:[A-Za-z][A-Za-z0-9-]*(?:[\s\/>]|$)|\/[A-Za-z][A-Za-z0-9-]*(?:[\s>]|$)|!--|\?|![A-Za-z]|!\[CDATA\[)/;
1078
1300
  const LINK_REF_DEF = /^ {0,3}\[[^\]]+\]:/;
1079
1301
  // HTML blocks of CommonMark types 1 to 5 end at a marker, not at a blank line. The end markers are plain substrings matched case-insensitively, as CommonMark defines them, and not a tag regexp (CodeQL js/bad-tag-filter): type 2 ends at "-->" only, never at "--!>".
1080
- // Entry is [start, ends]: </pre>, </script>, </style>, </textarea> after <pre> and kin, "-->" after "<!--", "?>" after "<?", "]]>" after "<![CDATA[", ">" after "<!X"; the marker is looked for after the start on the same line.
1302
+ // Entry is [start, ends]: </pre>, </script>, </style>, </textarea> after <pre> and kin, "-->" after "<!--", "?>" after "<?", "]]>" after "<![CDATA[", ">" after "<!X"; the marker is looked for on the whole opener line, as CommonMark does, so "<!-->", "<!--->" and "<?>" open and close on that line.
1081
1303
  function hasRawEnd(s, ends) { const t = s.toLowerCase(); return ends.some((e) => t.includes(e)); }
1082
1304
  const RAW_HTML_BLOCKS = [
1083
1305
  [/^ {0,3}<(?:pre|script|style|textarea)(?:[ \t>]|$)/i, ['</pre>', '</script>', '</style>', '</textarea>']],
@@ -1088,20 +1310,68 @@ const RAW_HTML_BLOCKS = [
1088
1310
  ];
1089
1311
  // The lines of raw HTML blocks, by the start conditions of CommonMark: types 1 to 5 end at their marker (RAW_HTML_BLOCKS), type
1090
1312
  // 6 (a block-level tag name) and type 7 (a complete tag alone on a line, which cannot interrupt a paragraph) end at a blank line.
1091
- // The lines of a block hold no Markdown (S3, LV-19), so the links and definitions are read from a text where they are blank,
1092
- // while the no-html check still reads them. A block inside a quote or a list item, or indented four columns, is not read.
1313
+ // The lines of a block hold no Markdown, so the links and definitions are read from a text where they are blank,
1314
+ // while the no-html check still reads them. A block is read only where its start is certain (see htmlBlockLines).
1093
1315
  const HTML_BLOCK_NAMES = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
1094
1316
  const HTML_TYPE6 = new RegExp("^ {0,3}</?(?:" + HTML_BLOCK_NAMES + ")(?:[ \\t]|/?>|$)", "i");
1095
- const HTML_TYPE7 = /^ {0,3}(?:<[A-Za-z][A-Za-z0-9-]*(?:[ \t]+[A-Za-z_:][A-Za-z0-9_.:-]*(?:[ \t]*=[ \t]*(?:[^ \t"'=<>`]+|'[^']*'|"[^"]*"))?)*[ \t]*\/?>|<\/[A-Za-z][A-Za-z0-9-]*[ \t]*>)[ \t]*$/;
1317
+ const HTML_TYPE7 = /^ {0,3}(?:<(?!(?:pre|script|style|textarea)(?![A-Za-z0-9-]))[A-Za-z][A-Za-z0-9-]*(?:[ \t]+[A-Za-z_:][A-Za-z0-9_.:-]*(?:[ \t]*=[ \t]*(?:[^ \t"'=<>`]+|'[^']*'|"[^"]*"))?)*[ \t]*\/?>|<\/(?!(?:pre|script|style|textarea)(?![A-Za-z0-9-]))[A-Za-z][A-Za-z0-9-]*[ \t]*>)[ \t]*$/i;
1318
+ // The columns a line is indented by, a tab going to the next multiple of four.
1319
+ function indentColumns(l) {
1320
+ let col = 0;
1321
+ for (let p = 0; p < l.length; p++) {
1322
+ if (l[p] === " ")
1323
+ col++;
1324
+ else if (l[p] === "\t")
1325
+ col += 4 - (col % 4);
1326
+ else
1327
+ break;
1328
+ }
1329
+ return col;
1330
+ }
1331
+ // The content offset (in columns) of the list item that a line opens, or 0 when it opens none: a bullet or an ordinary number
1332
+ // marker followed by a space, a tab or the end of the line, and not a thematic break. One to four spaces after the marker
1333
+ // belong to the offset, and five or more, or none, leave it at marker width plus one.
1334
+ function listItemOffset(l, col) {
1335
+ const m = /^[ \t]*([-*+]|\d{1,9}[.)])([ \t]*)/.exec(l);
1336
+ if (!m)
1337
+ return 0;
1338
+ const after = l.slice(m[0].length);
1339
+ if (m[2] === "" && after !== "")
1340
+ return 0;
1341
+ if (/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/.test(l))
1342
+ return 0;
1343
+ const gap = m[2].replace(/\t/g, " ").length;
1344
+ return col + m[1].length + (after === "" || gap > 4 ? 1 : gap);
1345
+ }
1346
+ // A raw HTML block is read only where its start is certain. The opener line is the first line, or follows a blank line or an
1347
+ // ATX heading that itself stood at such a place, is indented at most three columns and is outside every open list item.
1348
+ // Directly under a paragraph line, a quote line, a list item line or another HTML line a CommonMark reader may take the line
1349
+ // as a lazy continuation, as part of an item or as the start of a block, and the answer depends on rules that are not followed
1350
+ // here, so nothing is masked there and the lines keep the reading they have without this function. An item counts as open from
1351
+ // its marker line until a line after a blank line is indented less than its content offset; a line that follows text and is
1352
+ // indented less may be a lazy continuation, so it drops nothing and the item stays on the list, which only ever hides less. A
1353
+ // block ends as CommonMark says for its type. An opener of type 1 to 5 in an uncertain place may still be a block that runs on
1354
+ // over blank lines up to its end marker, so no opener is read after it until that marker has been seen, or for good when it
1355
+ // never comes.
1096
1356
  function htmlBlockLines(lines, blocks) {
1097
1357
  const out = new Array(lines.length).fill(false);
1098
1358
  let open = false, ends = null;
1359
+ // The end markers of an opener that was left unread, while its end has not been seen.
1360
+ let pending = null;
1361
+ // The content offsets of the list items that may be open above the line.
1362
+ const items = [];
1363
+ // True when a block can start at the line for certain: at the start, after a blank line, after such a heading.
1364
+ let clean = true;
1099
1365
  for (let i = 0; i < lines.length; i++) {
1100
1366
  const l = lines[i];
1367
+ const here = clean;
1368
+ clean = false;
1101
1369
  if (open) {
1102
1370
  if (ends === null) {
1103
- if (isMdBlank(l))
1371
+ if (isMdBlank(l)) {
1104
1372
  open = false;
1373
+ clean = true;
1374
+ }
1105
1375
  else
1106
1376
  out[i] = true;
1107
1377
  continue;
@@ -1111,24 +1381,49 @@ function htmlBlockLines(lines, blocks) {
1111
1381
  open = false;
1112
1382
  continue;
1113
1383
  }
1114
- if (blocks[i] < 0 || isMdBlank(l))
1384
+ if (blocks[i] < 0)
1115
1385
  continue;
1386
+ if (isMdBlank(l)) {
1387
+ clean = true;
1388
+ continue;
1389
+ }
1390
+ const col = indentColumns(l);
1391
+ if (here)
1392
+ while (items.length > 0 && col < items[items.length - 1])
1393
+ items.pop();
1394
+ const offset = listItemOffset(l, col);
1395
+ if (offset > 0)
1396
+ items.push(offset);
1397
+ if (pending !== null) {
1398
+ if (hasRawEnd(l, pending))
1399
+ pending = null;
1400
+ continue;
1401
+ }
1402
+ if (offset > 0)
1403
+ continue;
1404
+ clean = here && /^ {0,3}#{1,6}(?:[ \t]|$)/.test(l);
1405
+ const certain = here && items.length === 0;
1116
1406
  let matched = false;
1117
1407
  for (const [start, end] of RAW_HTML_BLOCKS) {
1118
1408
  const m = start.exec(l);
1119
1409
  if (!m)
1120
1410
  continue;
1121
1411
  matched = true;
1122
- out[i] = true;
1123
- if (!hasRawEnd(l.slice(m[0].length), end)) {
1124
- open = true;
1125
- ends = end;
1412
+ const closed = hasRawEnd(l, end);
1413
+ if (certain) {
1414
+ out[i] = true;
1415
+ if (!closed) {
1416
+ open = true;
1417
+ ends = end;
1418
+ }
1126
1419
  }
1420
+ else if (!closed)
1421
+ pending = end;
1127
1422
  break;
1128
1423
  }
1129
1424
  if (matched)
1130
1425
  continue;
1131
- if (HTML_TYPE6.test(l) || (HTML_TYPE7.test(l) && (i === 0 || blocks[i] !== blocks[i - 1]))) {
1426
+ if (certain && (HTML_TYPE6.test(l) || HTML_TYPE7.test(l))) {
1132
1427
  out[i] = true;
1133
1428
  open = true;
1134
1429
  ends = null;
@@ -1226,7 +1521,7 @@ function laterSetextH1(lines, fenced) {
1226
1521
  for (const [start, end] of RAW_HTML_BLOCKS) {
1227
1522
  const m = start.exec(l);
1228
1523
  if (m) {
1229
- if (!hasRawEnd(l.slice(m[0].length), end))
1524
+ if (!hasRawEnd(l, end))
1230
1525
  rawEnd = end;
1231
1526
  break;
1232
1527
  }
@@ -1399,8 +1694,9 @@ function isAbsoluteHttpUrl(t) {
1399
1694
  return (u.protocol === "http:" || u.protocol === "https:") && u.hostname !== "";
1400
1695
  }
1401
1696
  function redirectFailDetail(f) {
1697
+ // A location shown as only its scheme (maskLocation, ambiguous address) gives no host to validate.
1402
1698
  if (f.reason === "off-host")
1403
- return "redirects to " + f.location + ", a different host. llms.txt is host-scoped, so validate that host directly";
1699
+ return "redirects to " + f.location + (f.location.endsWith("//***") ? ", a different host that this report does not name. llms.txt is host-scoped, so find the host that this redirect points to and validate it directly" : ", a different host. llms.txt is host-scoped, so validate that host directly");
1404
1700
  if (f.reason === "unsafe-target" && !f.location)
1405
1701
  return "the host is not a public domain name, so no request was made";
1406
1702
  if (f.reason === "unsafe-target")
@@ -1434,7 +1730,10 @@ export function validateLlmsTxt(f) {
1434
1730
  // CR-only and CRLF line endings become LF here (Tek-560): a file written with bare CR was one
1435
1731
  // line for the old split and read as a title with the whole document in it.
1436
1732
  const text = (f.text.charCodeAt(0) === 0xFEFF ? f.text.slice(1) : f.text).replace(/\r\n?/g, "\n");
1437
- const ct = (f.contentType || "").toLowerCase();
1733
+ // ASCII lower case and HTTP white space only (CT-1, outside fuzz run 2026-11-22). toLowerCase() turned the Kelvin sign
1734
+ // U+212A in "text/mar<U+212A>down" into a k, and trim() removed a leading no-break space, which HTTP carries as an
1735
+ // obs-text byte, so a media type that a MIME type parser refuses passed as text/plain or text/markdown.
1736
+ const ct = (f.contentType || "").replace(/[A-Z]+/g, (c) => c.toLowerCase());
1438
1737
  const looksHtml = /^\s*(<!doctype|<html|<head|<body)/i.test(text);
1439
1738
  if (looksHtml) {
1440
1739
  add("content-type", "fail", "Response is plain text", "the body looks like an HTML page, not an llms.txt file");
@@ -1442,7 +1741,7 @@ export function validateLlmsTxt(f) {
1442
1741
  }
1443
1742
  // The media type is compared whole, without its parameters. A substring test passed
1444
1743
  // application/x-text/plain and text/markdownish until 2026-09-27 (Tek-496).
1445
- const mediaType = ct.split(";")[0].trim();
1744
+ const mediaType = ct.split(";")[0].replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
1446
1745
  if (mediaType === "text/plain" || mediaType === "text/markdown") {
1447
1746
  add("content-type", "pass", "Response is plain text", mediaType);
1448
1747
  }
@@ -1569,7 +1868,10 @@ export function validateLlmsTxt(f) {
1569
1868
  linkedLineIdx.add(idx);
1570
1869
  }
1571
1870
  }
1572
- const hm = h2Lines(lines, fenced);
1871
+ // A line inside a raw HTML block is no heading either: CommonMark reads "<?x", "## Docs", "?>" as one block of type 3
1872
+ // and ends it at the "?>", not at the heading, so the lines of the blocks that htmlBlockLines finds are masked like fences.
1873
+ const h2Mask = fenced.map((f, i) => f || htmlLine[i]);
1874
+ const hm = h2Lines(lines, h2Mask);
1573
1875
  const sx = laterSetextH1(lines, fenced);
1574
1876
  const h2Count = hm.h2.filter(Boolean).length;
1575
1877
  // A section counts when it carries a file list. An H2 followed by a paragraph satisfied
@@ -1730,7 +2032,18 @@ export function validateLlmsTxt(f) {
1730
2032
  add("links", "pass", "Markdown links an agent can follow", named.length + " link" + (named.length === 1 ? "" : "s") + ", all absolute URLs");
1731
2033
  }
1732
2034
  else {
1733
- const relativeCount = named.filter((m) => !/^[a-z][a-z0-9+.-]*:/i.test(m.target)).length;
2035
+ // The scheme test reads a target to its end, so it runs once per distinct target, as isAbs does: many
2036
+ // references to one long definition would otherwise repeat it for each of them.
2037
+ const schemeMemo = new Map();
2038
+ const hasScheme = (t) => {
2039
+ let r = schemeMemo.get(t);
2040
+ if (r === undefined) {
2041
+ r = /^[a-z][a-z0-9+.-]*:/i.test(t);
2042
+ schemeMemo.set(t, r);
2043
+ }
2044
+ return r;
2045
+ };
2046
+ const relativeCount = named.filter((m) => !hasScheme(m.target)).length;
1734
2047
  const hostless = named.length - absolute - relativeCount;
1735
2048
  add("links", "warn", "Markdown links an agent can follow", named.length + " link" + (named.length === 1 ? "" : "s") + ", " + relativeCount + " relative" + (hostless > 0 ? " and " + hostless + " that are not valid http or https URLs" : "") + ". Absolute URLs travel better when the file is read out of context");
1736
2049
  }
@@ -2407,7 +2720,18 @@ function rawTextEnd(lower, name, from) {
2407
2720
  function scriptEnd(lower, from) {
2408
2721
  let i = from, escaped = false, doubleEscaped = false, close = -2;
2409
2722
  while (i < lower.length) {
2410
- if (lower.startsWith("<!--", i)) {
2723
+ if (!escaped && lower.startsWith("<!--", i)) {
2724
+ // "<!-->" and "<!--->" are over at once: the tokenizer reads the ">" that follows the two or three dashes as the end of
2725
+ // the escape start, so the script is not in the escaped state. Already escaped, "<!--" means nothing, and the "-->" that
2726
+ // overlaps it ends the escape through the search below.
2727
+ if (lower.startsWith("<!-->", i)) {
2728
+ i += 5;
2729
+ continue;
2730
+ }
2731
+ if (lower.startsWith("<!--->", i)) {
2732
+ i += 6;
2733
+ continue;
2734
+ }
2411
2735
  escaped = true;
2412
2736
  i += 4;
2413
2737
  continue;
@@ -2496,7 +2820,10 @@ function templateEnd(lower, from) {
2496
2820
  // Round S3 (Tek-546): every tag is read whole with the tokenizer's own states (tagEnd), so a "<"
2497
2821
  // or a ">" inside a quoted attribute value is part of the tag and not markup (LV-26, U-8,
2498
2822
  // WL-16), and the attributes of an end tag are read the same way (LV-25).
2499
- if (lower.startsWith("</template", lt)) {
2823
+ // A template inside svg or math is an ordinary foreign element, not an HTML template: it opens no level of depth, and
2824
+ // its end tag closes it (through the scope stack below) and not the HTML template this scan is looking for.
2825
+ const foreign = scopes.length > 0 && !scopes[scopes.length - 1].html;
2826
+ if (lower.startsWith("</template", lt) && !(foreign && open.get("template"))) {
2500
2827
  const gt = tagEnd(lower, lt);
2501
2828
  if (gt === -1)
2502
2829
  return -1;
@@ -2510,7 +2837,7 @@ function templateEnd(lower, from) {
2510
2837
  i = gt + 1;
2511
2838
  continue;
2512
2839
  }
2513
- if (lower.startsWith("<template", lt) && isTagBoundary(lower[lt + 9])) {
2840
+ if (lower.startsWith("<template", lt) && isTagBoundary(lower[lt + 9]) && !foreign) {
2514
2841
  const gt = tagEnd(lower, lt);
2515
2842
  if (gt === -1)
2516
2843
  return -1;
@@ -2986,9 +3313,11 @@ export async function validateHost(input, opts = {}) {
2986
3313
  // back out of a message meant for people.
2987
3314
  if (unusedPath)
2988
3315
  checks.unshift({ id: "input-path", status: "info", label: "Path in the address you entered", value: cut(unusedPath, 120), detail: "This path is not used, because the validator always reads /llms.txt at the root of the host." });
2989
- // Text quoted from the fetched file leaves without bidirectional controls (round 19,
2990
- // V6-U1, mirrored from worker.ts v3.164.0): a site's own H1 or summary could otherwise
2991
- // read in another order here than in the file itself.
2992
- const stripped = checks.map((c) => (typeof c.detail === "string" ? { ...c, detail: stripControls(stripBidi(c.detail)) } : c));
3316
+ // Text quoted from the fetched file leaves without bidirectional controls (mirrored from
3317
+ // worker.ts), without C0 and C1 controls and without the invisible
3318
+ // formatting characters of stripInvisible: a site's own H1 or summary could otherwise read in
3319
+ // another order here than in the file itself, or carry text no reader sees. Up to 0.7.4 the
3320
+ // line and paragraph separators, the marks, the zero-width characters and the tag characters stayed.
3321
+ const stripped = checks.map((c) => (typeof c.detail === "string" ? { ...c, detail: stripInvisible(stripControls(stripBidi(c.detail))) } : c));
2993
3322
  return { target: "https://" + host + "/llms.txt", summary: summarizeChecks(stripped), checks: stripped };
2994
3323
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "turva-llms-txt-validator",
3
- "version": "0.7.4",
3
+ "version": "0.8.1",
4
4
  "description": "Validate a site's llms.txt structure: eight checks as pass/warn/fail plus two llms.txt v2 discovery checks that read pass or info and never move the summary, JSON output. Same checks as the hosted validator at turva.dev/llms-txt-validator.",
5
5
  "type": "module",
6
6
  "main": "./dist/src/index.js",