turva-llms-txt-validator 0.7.3 → 0.8.0
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 +44 -12
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +320 -54
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -84,13 +84,17 @@ 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
|
|
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.
|
|
92
94
|
- 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
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 `//***`. 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
|
+
- 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
98
|
|
|
95
99
|
## What it checks
|
|
96
100
|
|
|
@@ -114,25 +118,25 @@ Some failures stop the file checks early. For example, an HTML response is repor
|
|
|
114
118
|
Links are read the way CommonMark reads them for the forms listed here.
|
|
115
119
|
|
|
116
120
|
- A link inside inline code, after an escaped bracket or in an image does not count.
|
|
117
|
-
- Inline code pairs only inside one block, the way CommonMark reads blocks. A blank line, a heading, a list item, a block quote line, a thematic break and a setext underline each end a block. The lines of one block quote belong to one block
|
|
118
|
-
- A fence inside a list item counts as a fence, closed or not, in either fence character
|
|
121
|
+
- Inline code pairs only inside one block, the way CommonMark reads blocks. A blank line, a heading, a list item, a block quote line, a thematic break and a setext underline each end a block. The lines of one block quote belong to one block. An empty quote line ends it, and a lazy line after a quote line goes on with it. A backtick pair inside one quote is therefore inline code, and a pair across the edge of a quote is not. An empty list item or a numbered item that does not start at 1 does not end a paragraph, unless the line closes an open list item. A backtick pair across such a line is therefore inline code. The content of a quote is not read further. Raw HTML blocks are not blocks for the HTML check, so there a backtick pair across one is still inline code. The links check treats the lines of an HTML block as blank and the block as the end of the paragraph before it.
|
|
122
|
+
- A fence inside a list item counts as a fence, closed or not, in either fence character. It may sit on the marker line or up to three columns past the item's content column. It ends when the item closes. Four or more columns past that column is indented code.
|
|
119
123
|
- A link in an ordered list, a target in angle brackets and a target with a title in double or single quotes do count.
|
|
120
124
|
- A title in parentheses is not read, so `[Guide](https://example.org/guide (Overview))` is not collected.
|
|
121
125
|
- 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
126
|
- 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
127
|
- A link written inside the description text of an image, as in `](https://example.org/img.png)`, does not count. An image without a target (`]`) 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,
|
|
128
|
+
- 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
129
|
- 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
|
-
- A link reference definition opens only where a block starts, for example after a blank line, a heading, a fence or a thematic break
|
|
130
|
+
- 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
131
|
- Labels match by Unicode case folding. Character references in a target need their semicolon: `https://example.org` decodes, `https://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
|
-
-
|
|
132
|
+
- 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
133
|
- 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: `#  `, `` [` `](https://example.org/a) ``, `>>` and `> >`. A line with only a no-break or ideographic space is not a blank line.
|
|
130
134
|
- 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
135
|
- 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
136
|
- 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
137
|
- 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
138
|
|
|
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.
|
|
139
|
+
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
140
|
|
|
137
141
|
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
142
|
|
|
@@ -152,7 +156,11 @@ These checks are labelled **v2** in the output. They look for link relations in
|
|
|
152
156
|
| 9 | Home page points to its llms.txt | `rel="describedby"` has a non-empty target | `info` |
|
|
153
157
|
| 10 | Home page points to a Markdown version | `rel="alternate"` has media type `text/markdown` and a non-empty target | `info` |
|
|
154
158
|
|
|
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.
|
|
159
|
+
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.
|
|
160
|
+
|
|
161
|
+
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.
|
|
162
|
+
|
|
163
|
+
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.
|
|
156
164
|
|
|
157
165
|
The validator does not follow the links inside `llms.txt`, crawl the site or test whether an AI agent can complete a task there.
|
|
158
166
|
|
|
@@ -181,6 +189,28 @@ for (const check of problems) {
|
|
|
181
189
|
|
|
182
190
|
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.
|
|
183
191
|
|
|
192
|
+
### Options for library callers
|
|
193
|
+
|
|
194
|
+
`validateHost(input, options)` and `fetchLlmsTxt(host, options)` take the same `ValidateHostOptions`. The command line sets none of them.
|
|
195
|
+
|
|
196
|
+
| Option | Meaning | Accepted values |
|
|
197
|
+
| --- | --- | --- |
|
|
198
|
+
| `timeoutMs` | Time budget for one document, shared across its redirect chain. The default is `8000`. | An integer from 1 to 2,147,483,647. |
|
|
199
|
+
| `cap` | Read limit in bytes per response. The default is `262144`, which is 256 KiB. | An integer from 1 to 2,097,152. |
|
|
200
|
+
| `userAgent` | Value of the `user-agent` request header. | A string that the platform accepts as a header value. |
|
|
201
|
+
| `accept` | Value of the `accept` request header, read by `fetchLlmsTxt`. | A string that the platform accepts as a header value. |
|
|
202
|
+
| `path` | Path and query of the request, read by `fetchLlmsTxt`. The default is `/llms.txt`. | A string that starts with a single `/`. |
|
|
203
|
+
|
|
204
|
+
`validateHost` pins its two reads to `/llms.txt` and `/`, each with its own `accept` value, so it ignores `path` and `accept`.
|
|
205
|
+
|
|
206
|
+
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.
|
|
207
|
+
|
|
208
|
+
`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.
|
|
209
|
+
|
|
210
|
+
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.
|
|
211
|
+
|
|
212
|
+
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.
|
|
213
|
+
|
|
184
214
|
## Use in CI
|
|
185
215
|
|
|
186
216
|
Add this step to a GitHub Actions job that already has Node.js 22 or newer available. Replace `your-domain.com` with your domain:
|
|
@@ -197,7 +227,7 @@ Any CI runner with Node.js 22 or newer can run the same command. Omit `--strict`
|
|
|
197
227
|
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.
|
|
198
228
|
|
|
199
229
|
- Timeout: eight seconds per document, shared across its redirect chain.
|
|
200
|
-
- Read limit: 256 KiB, which is 262,144 bytes, per response. A file cut there gets the size note "over 256 KiB, read truncated".
|
|
230
|
+
- 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.
|
|
201
231
|
- 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.
|
|
202
232
|
- 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.
|
|
203
233
|
|
|
@@ -209,7 +239,7 @@ For vulnerability reporting and supported versions, see [SECURITY.md](https://gi
|
|
|
209
239
|
|
|
210
240
|
The source is TypeScript under `src/` and `bin/`, compiled with `tsc` to `dist/`. The tarball ships only `dist/src/index.js`, `dist/src/index.d.ts`, `dist/bin/cli.js`, the README, the license, the third-party notices and `package.json`, which npm always includes. `dist/` is generated, and `npm pack` builds it through the `prepack` script.
|
|
211
241
|
|
|
212
|
-
GitHub Actions tests Node.js 22, 24 and 26 on Ubuntu and Node.js 22 on Windows. A version tag starts the release workflow, `.github/workflows/publish.yml`. It runs the type check and the tests, fails when the tag and `package.json` name different versions
|
|
242
|
+
GitHub Actions tests Node.js 22, 24 and 26 on Ubuntu and Node.js 22 on Windows. A version tag starts the release workflow, `.github/workflows/publish.yml`. It runs the type check and the tests, and it fails when the tag and `package.json` name different versions. It then publishes with npm trusted publishing over OIDC and creates the GitHub release from the CHANGELOG section. npm writes a provenance attestation. No npm token is stored in the repository or in the workflow.
|
|
213
243
|
|
|
214
244
|
## From JavaScript to TypeScript
|
|
215
245
|
|
|
@@ -222,10 +252,12 @@ The strict type check found two inputs that could leave `undefined` in a check's
|
|
|
222
252
|
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.
|
|
223
253
|
|
|
224
254
|
```sh
|
|
225
|
-
mkdir verify-llms && cd verify-llms && npm init -y && npm install turva-llms-txt-validator@0.
|
|
255
|
+
mkdir verify-llms && cd verify-llms && npm init -y && npm install turva-llms-txt-validator@0.8.0 --ignore-scripts && npm audit signatures
|
|
226
256
|
```
|
|
227
257
|
|
|
228
|
-
`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.
|
|
258
|
+
`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.
|
|
259
|
+
|
|
260
|
+
Tag `v0.8.0` must point at that same commit, and `gh api repos/erekola/llms-txt-validator/commits/v0.8.0 --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.
|
|
229
261
|
|
|
230
262
|
## Development
|
|
231
263
|
|
package/dist/src/index.d.ts
CHANGED
|
@@ -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,79 @@ 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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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.
|
|
44
|
+
const text = String(href).replace(/[\t\n\r]/g, "");
|
|
45
|
+
// Where an authority starts in a text, read from the text and not from the parser: after a scheme and two slashes, the
|
|
46
|
+
// scheme being whatever stands before "://" with no / \ ? or # in it. invalid is true when that "scheme" is not one.
|
|
47
|
+
const shapeOf = (t) => {
|
|
48
|
+
const m = /^[a-z][a-z0-9+.-]*:/i.exec(t);
|
|
49
|
+
let start = m ? m[0].length : 0;
|
|
50
|
+
let invalid = false;
|
|
51
|
+
const sep = t.indexOf("://");
|
|
52
|
+
if (sep >= 0 && !(m && m[0].length === sep + 1) && !/[\/\\?#]/.test(t.slice(0, sep))) {
|
|
53
|
+
start = sep + 1;
|
|
54
|
+
invalid = true;
|
|
55
|
+
}
|
|
56
|
+
let from = start;
|
|
57
|
+
while (from < t.length && (t[from] === "/" || t[from] === "\\"))
|
|
58
|
+
from++;
|
|
59
|
+
return { start, from, scheme: m !== null || invalid, invalid };
|
|
60
|
+
};
|
|
61
|
+
// Ambiguity is decided once, from the written text alone, before any branch below reads it. A text that holds an @ is
|
|
62
|
+
// read the same way by a URL parser and by a person only when it starts exactly as "<scheme>://" or "//" followed by a
|
|
63
|
+
// character that is no slash, and no backslash, ? or # stands between that start and the first slash or the last @. Any
|
|
64
|
+
// other start is read differently by each reader (three slashes, a backslash, a scheme colon with no or one slash, a
|
|
65
|
+
// later "://" after the @, an @ before the scheme colon), and so is a ? or # in front of the @ (the parser reads the host
|
|
66
|
+
// before it and a query after it, a person reads the text before the @ as user information). Such a text shows only its
|
|
67
|
+
// scheme, or nothing, and no host. A start with no scheme-like word and no leading // is a relative reference and is
|
|
68
|
+
// not decided here: "/a@b", "docs/@name", "?e=a@b.com" and "#x@y" keep the reading they have below.
|
|
69
|
+
const ambiguous = (t) => {
|
|
70
|
+
if (!t.includes("@"))
|
|
71
|
+
return false;
|
|
72
|
+
const m = /^[a-z][a-z0-9+.-]*:/i.exec(t);
|
|
73
|
+
const sep = t.indexOf("://");
|
|
74
|
+
const lead = m ? m[0] : sep >= 0 && !/[\/\\?#]/.test(t.slice(0, sep)) ? t.slice(0, t.indexOf(":") + 1) : "";
|
|
75
|
+
if (lead.includes("@"))
|
|
76
|
+
return true;
|
|
77
|
+
if (lead === "" && !/^[\/\\]{2}/.test(t))
|
|
78
|
+
return false;
|
|
79
|
+
const p = lead.length;
|
|
80
|
+
if (t[p] !== "/" || t[p + 1] !== "/" || p + 2 >= t.length || t[p + 2] === "/" || t[p + 2] === "\\")
|
|
81
|
+
return true;
|
|
82
|
+
const lastAt = t.lastIndexOf("@");
|
|
83
|
+
if (lastAt < p + 2)
|
|
84
|
+
return false;
|
|
85
|
+
const slash = t.indexOf("/", p + 2);
|
|
86
|
+
return /[\\?#]/.test(t.slice(p + 2, slash >= 0 && slash < lastAt ? slash : lastAt));
|
|
87
|
+
};
|
|
88
|
+
if (written !== undefined) {
|
|
89
|
+
const w = String(written).replace(/[\t\n\r]/g, "");
|
|
90
|
+
if (ambiguous(w) || shapeOf(w).invalid)
|
|
91
|
+
return maskLocation(written, base);
|
|
38
92
|
}
|
|
39
|
-
|
|
40
|
-
|
|
93
|
+
if (ambiguous(text)) {
|
|
94
|
+
// The scheme is shown when a slash follows its colon; with no slash the text before the colon may be a user name.
|
|
95
|
+
const scheme = /^([\w+.-]{1,32}):[\/\\]/.exec(text);
|
|
96
|
+
return (scheme ? scheme[1] + ":" : "") + "//***";
|
|
97
|
+
}
|
|
98
|
+
const shape = shapeOf(text);
|
|
99
|
+
let u = null;
|
|
100
|
+
if (!shape.invalid) {
|
|
101
|
+
try {
|
|
102
|
+
u = new URL(href, base);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
u = null;
|
|
106
|
+
}
|
|
41
107
|
}
|
|
42
108
|
// An opaque URL (no authority, e.g. "u:name@host/") parses without throwing but has no
|
|
43
109
|
// host, so clearing u.username/u.password is a silent no-op: WHATWG has nowhere to put
|
|
@@ -61,15 +127,26 @@ export function maskLocation(href, base) {
|
|
|
61
127
|
u.hash = "";
|
|
62
128
|
return u.href;
|
|
63
129
|
}
|
|
64
|
-
let s =
|
|
130
|
+
let s = text;
|
|
65
131
|
const stop = s.search(/[?#]/);
|
|
132
|
+
// A ? or # before the last @ can still belong to the user information of a text that has no scheme-like start
|
|
133
|
+
// ("user_name:pa?ss@host"). When a colon and no slash stands before that ?, everything up to the last @ is shown as ***,
|
|
134
|
+
// and the cut at the ? or # applies to what follows it. A scheme or an authority with a ? before the @ is ambiguous and
|
|
135
|
+
// has returned above.
|
|
136
|
+
if (stop >= 0 && stop >= shape.from) {
|
|
137
|
+
const lastAt = s.lastIndexOf("@");
|
|
138
|
+
if (lastAt > stop && shape.from === shape.start && s.slice(0, stop).includes(":") && !/[\/\\]/.test(s.slice(shape.from, stop))) {
|
|
139
|
+
const rest = s.slice(lastAt + 1);
|
|
140
|
+
const rs = rest.search(/[?#]/);
|
|
141
|
+
return s.slice(0, shape.from) + "***@" + (rs >= 0 ? rest.slice(0, rs) + (rest[rs] === "?" ? "?***" : "") : rest);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
66
144
|
if (stop >= 0)
|
|
67
145
|
s = s.slice(0, stop) + (s[stop] === "?" ? "?***" : "");
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
from++;
|
|
146
|
+
const after = shapeOf(s);
|
|
147
|
+
const hasScheme = after.scheme;
|
|
148
|
+
const start = after.start;
|
|
149
|
+
const from = after.from;
|
|
73
150
|
// Without a scheme and two slashes there is normally no authority, and an @ is part of a
|
|
74
151
|
// path ("path@2x.png" stays unmasked below). But when an @ still appears before the first
|
|
75
152
|
// /, the text ahead of it reads as userinfo even when the parser here does not recognise it
|
|
@@ -79,7 +156,7 @@ export function maskLocation(href, base) {
|
|
|
79
156
|
// user:password and is masked, while "path@2x.png" has no ":" ahead of its @ and stays as
|
|
80
157
|
// given (outside review V13, D5-1: the slashless shape used to return early and print the
|
|
81
158
|
// password).
|
|
82
|
-
if (!
|
|
159
|
+
if (!hasScheme && from - start < 2) {
|
|
83
160
|
const firstSlash = s.indexOf("/");
|
|
84
161
|
const firstAt = s.indexOf("@");
|
|
85
162
|
if (firstAt < 0)
|
|
@@ -113,6 +190,23 @@ export function stripBidi(s) {
|
|
|
113
190
|
export function stripControls(s) {
|
|
114
191
|
return String(s).replace(/[\u0000-\u001F\u007F-\u009F]/g, "");
|
|
115
192
|
}
|
|
193
|
+
// Invisible characters leave a check's detail too, by Unicode class and not from a list kept by hand: every
|
|
194
|
+
// format character (General_Category Cf: the zero-width characters, the left-to-right and right-to-left marks
|
|
195
|
+
// and the Arabic letter mark, the bidi controls, the invisible math operators, the soft hyphen, the byte-order
|
|
196
|
+
// mark, the tag characters U+E0000 to U+E007F), every Default_Ignorable_Code_Point (also the variation
|
|
197
|
+
// selectors U+FE00 to U+FE0F and U+E0100 to U+E01EF, the combining grapheme joiner and the Hangul fillers),
|
|
198
|
+
// and the line and paragraph separators U+2028 and U+2029 (Zl and Zp). They reorder or hide text that a
|
|
199
|
+
// reader sees differently from a program. Ordinary spaces (U+00A0, U+2000 to U+200A, U+202F, U+205F,
|
|
200
|
+
// U+3000) are not in the class and stay. Cost: an emoji sequence loses its zero-width joiners and its
|
|
201
|
+
// variation selector, so a family emoji reads as its members side by side, a heart written with U+FE0F shows
|
|
202
|
+
// in text style, and a tag flag shows as its black flag. The same class takes the zero-width non-joiner and
|
|
203
|
+
// joiner out of words that need them to join or to stay apart, so a quoted Persian, Malayalam or Devanagari
|
|
204
|
+
// word loses its joining mark and reads without it, and it takes the soft hyphen, the Arabic number signs
|
|
205
|
+
// U+0600 to U+0605 and the end-of-ayah mark U+06DD, which show as glyphs. Mirrors worker.ts stripInvisible();
|
|
206
|
+
// it is not exported, and validateHost applies it with the two functions above.
|
|
207
|
+
function stripInvisible(s) {
|
|
208
|
+
return String(s).replace(/[\p{Cf}\p{Default_Ignorable_Code_Point}\p{Zl}\p{Zp}]/gu, "");
|
|
209
|
+
}
|
|
116
210
|
export function normalizeHostInput(raw) {
|
|
117
211
|
// The hosted validator removes tab, CR and LF from the typed address before it reads it, then trims
|
|
118
212
|
// (worker.ts, the /llms-txt-validator route). The URL parser would remove the same three characters
|
|
@@ -180,6 +274,42 @@ export function isValidPublicHost(host) {
|
|
|
180
274
|
return false;
|
|
181
275
|
return true;
|
|
182
276
|
}
|
|
277
|
+
// The largest read limit a caller may ask for, and the largest timeout the platform timer takes. The HTML
|
|
278
|
+
// check reads the whole body with one pattern, and a body of attribute-like text that is several megabytes
|
|
279
|
+
// long overflowed the engine's stack inside it, so a larger limit could end in an internal RangeError. 2 MiB
|
|
280
|
+
// is eight times the default and below the smallest size where that was measured.
|
|
281
|
+
const MAX_CAP = 2097152;
|
|
282
|
+
const MAX_TIMEOUT_MS = 2147483647;
|
|
283
|
+
// opts.timeoutMs and opts.cap come from the caller. A value that is not a whole number in range used to
|
|
284
|
+
// switch the limit off (NaN and Infinity made the size test false for every chunk) or to throw from inside
|
|
285
|
+
// the read loop, so it is refused before the first request instead.
|
|
286
|
+
function requestLimits(opts) {
|
|
287
|
+
const timeoutMs = opts.timeoutMs ?? 8000;
|
|
288
|
+
const cap = opts.cap ?? 262144;
|
|
289
|
+
if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_TIMEOUT_MS)
|
|
290
|
+
throw new RangeError("opts.timeoutMs must be an integer from 1 to " + MAX_TIMEOUT_MS + " (milliseconds)");
|
|
291
|
+
if (typeof cap !== "number" || !Number.isInteger(cap) || cap < 1 || cap > MAX_CAP)
|
|
292
|
+
throw new RangeError("opts.cap must be an integer from 1 to " + MAX_CAP + " (bytes)");
|
|
293
|
+
return { timeoutMs, cap };
|
|
294
|
+
}
|
|
295
|
+
// opts.path is joined to a host that was checked already, so it may carry a path and a query and nothing else.
|
|
296
|
+
// A path that does not start with a slash can change the port or the end of the host name (":8443/x",
|
|
297
|
+
// ".other.example/x", "x"), and one that starts with two slashes or a slash and a backslash is an address with
|
|
298
|
+
// another host in the eyes of a URL parser. Control characters are refused as well: a parser removes tab, CR
|
|
299
|
+
// and LF silently, and that changes what the text means.
|
|
300
|
+
function requestPath(path) {
|
|
301
|
+
if (path === undefined || path === null)
|
|
302
|
+
return "/llms.txt";
|
|
303
|
+
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'); };
|
|
304
|
+
if (typeof path !== "string" || path[0] !== "/" || path[1] === "/" || path[1] === "\\")
|
|
305
|
+
return refuse();
|
|
306
|
+
for (let i = 0; i < path.length; i++) {
|
|
307
|
+
const c = path.charCodeAt(i);
|
|
308
|
+
if (c < 32 || c === 127)
|
|
309
|
+
return refuse();
|
|
310
|
+
}
|
|
311
|
+
return path;
|
|
312
|
+
}
|
|
183
313
|
// opts.path and opts.accept were added for the v2 discovery checks, which need the
|
|
184
314
|
// site's home page as well as its llms.txt. Nothing else moved: the redirect budget,
|
|
185
315
|
// the same-host rule, the credential and port rejections and the 256 KiB cap are the
|
|
@@ -195,10 +325,16 @@ export async function fetchLlmsTxt(host, opts = {}) {
|
|
|
195
325
|
if (!normalized || !isValidPublicHost(normalized))
|
|
196
326
|
return { redirect: true, reason: "unsafe-target", status: 0, location: "" };
|
|
197
327
|
host = normalized;
|
|
198
|
-
const timeoutMs = opts
|
|
199
|
-
const cap = opts.cap ?? 262144;
|
|
328
|
+
const { timeoutMs, cap } = requestLimits(opts);
|
|
200
329
|
const reqApex = host.startsWith("www.") ? host.slice(4) : host;
|
|
201
|
-
let url = "https://" + host + (opts.path
|
|
330
|
+
let url = "https://" + host + requestPath(opts.path);
|
|
331
|
+
// The address is parsed once before the first request: it must still name the https scheme, the checked host,
|
|
332
|
+
// the default port and no credentials. A path that passed requestPath cannot change that, so this is a second lock.
|
|
333
|
+
{
|
|
334
|
+
const first = new URL(url);
|
|
335
|
+
if (first.protocol !== "https:" || first.hostname !== host || first.port !== "" || first.username !== "" || first.password !== "")
|
|
336
|
+
throw new Error("the request address does not keep the host that was checked");
|
|
337
|
+
}
|
|
202
338
|
let redirectedFrom = null;
|
|
203
339
|
// One budget for the whole redirect chain, not one per hop. Mirrors the hosted validator
|
|
204
340
|
// (turva.dev/llms-txt-validator), which is canonical: with five hops a per-hop signal made
|
|
@@ -239,9 +375,9 @@ export async function fetchLlmsTxt(host, opts = {}) {
|
|
|
239
375
|
const safeTarget = next.protocol === "https:" && !next.port && !next.username && !next.password && isValidPublicHost(next.hostname);
|
|
240
376
|
const twin = (next.hostname.startsWith("www.") ? next.hostname.slice(4) : next.hostname) === reqApex;
|
|
241
377
|
if (!safeTarget)
|
|
242
|
-
return { redirect: true, reason: "unsafe-target", status: res.status, location: cut(maskLocation(next.href), 120) };
|
|
378
|
+
return { redirect: true, reason: "unsafe-target", status: res.status, location: cut(maskLocation(next.href, undefined, loc), 120) };
|
|
243
379
|
if (!twin)
|
|
244
|
-
return { redirect: true, reason: "off-host", status: res.status, location: cut(maskLocation(next.href), 120) };
|
|
380
|
+
return { redirect: true, reason: "off-host", status: res.status, location: cut(maskLocation(next.href, undefined, loc), 120) };
|
|
245
381
|
if (!redirectedFrom)
|
|
246
382
|
redirectedFrom = url;
|
|
247
383
|
url = next.href;
|
|
@@ -666,20 +802,34 @@ function collectLinkDefinitions(text, lineBlocks, defAt) {
|
|
|
666
802
|
// 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
803
|
// resolved or inline target is decoded for backslash escapes and complete character references (":", "&", ...), the
|
|
668
804
|
// 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
|
|
670
|
-
//
|
|
805
|
+
// ">", quote, "]" and line end are looked up in a list of every position of that character, built on its first use and
|
|
806
|
+
// searched by bisection, so a look-up costs the same in whatever order the queries come, and the parenthesis pairs of a
|
|
807
|
+
// plain target are built once, so a file that repeats "[a](", " {
|
|
672
809
|
const out = [];
|
|
673
810
|
const code = codeSpanMask(text, lineBlocks);
|
|
674
811
|
const refs = defs || collectLinkDefinitions(text, lineBlocks);
|
|
675
|
-
|
|
812
|
+
// The index of the first c at or after from, or -1. A cache of the last answer only helped queries that move
|
|
813
|
+
// forward; a query that moves back made the next one scan from the start again, which is quadratic on a text of
|
|
814
|
+
// "![" openers whose labels and targets are looked up from the inside out.
|
|
815
|
+
const positions = Object.create(null);
|
|
676
816
|
const nextIdx = (c, from) => {
|
|
677
|
-
|
|
678
|
-
if (
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
817
|
+
let p = positions[c];
|
|
818
|
+
if (!p) {
|
|
819
|
+
p = [];
|
|
820
|
+
for (let k = text.indexOf(c); k !== -1; k = text.indexOf(c, k + 1))
|
|
821
|
+
p.push(k);
|
|
822
|
+
positions[c] = p;
|
|
823
|
+
}
|
|
824
|
+
let lo = 0, hi = p.length;
|
|
825
|
+
while (lo < hi) {
|
|
826
|
+
const mid = (lo + hi) >> 1;
|
|
827
|
+
if (p[mid] < from)
|
|
828
|
+
lo = mid + 1;
|
|
829
|
+
else
|
|
830
|
+
hi = mid;
|
|
831
|
+
}
|
|
832
|
+
return lo < p.length ? p[lo] : -1;
|
|
683
833
|
};
|
|
684
834
|
const isBlank = (c) => c === " " || c === "\t";
|
|
685
835
|
// 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 +963,12 @@ function collectLinks(text, defs, lineBlocks) {
|
|
|
813
963
|
return e < text.length ? afterTarget(text.slice(k, e), e) : null;
|
|
814
964
|
};
|
|
815
965
|
// 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
|
|
966
|
+
// inside a code span is code and neither closes nor opens. A backslash before a line break is a hard
|
|
967
|
+
// line break and escapes nothing, so the break still ends the paragraph it ends (CommonMark); the label scan and closeOf
|
|
968
|
+
// below used to step over it, and a link label then ran on into the next list item or heading.
|
|
817
969
|
const scanLabel = (j) => {
|
|
818
970
|
while (j < text.length && (code[j] || (text[j] !== "]" && text[j] !== "[" && !blankAt(j))))
|
|
819
|
-
j += !code[j] && text[j] === "\\" ? 2 : 1;
|
|
971
|
+
j += !code[j] && text[j] === "\\" && text[j + 1] !== "\n" ? 2 : 1;
|
|
820
972
|
return j;
|
|
821
973
|
};
|
|
822
974
|
// A definition is decoded once, however many references use it: a long destination used by many labels would otherwise be
|
|
@@ -843,7 +995,7 @@ function collectLinks(text, defs, lineBlocks) {
|
|
|
843
995
|
if (code[k])
|
|
844
996
|
continue;
|
|
845
997
|
const c = text[k];
|
|
846
|
-
if (c === "\\")
|
|
998
|
+
if (c === "\\" && text[k + 1] !== "\n")
|
|
847
999
|
k++;
|
|
848
1000
|
else if (c === "[")
|
|
849
1001
|
stack.push(k);
|
|
@@ -862,6 +1014,16 @@ function collectLinks(text, defs, lineBlocks) {
|
|
|
862
1014
|
// unescaped "!". The alt text is read to the "]" that balances the "[" (S3, LV-08), so a link written inside it is image text
|
|
863
1015
|
// and no link. Returns the index after the image, or null for a malformed one (no closing "]", no target, a label without a
|
|
864
1016
|
// definition), which the callers treat as an ordinary bracket, the way CommonMark reads it.
|
|
1017
|
+
// The text between an image's "[" at k and its "]" at m, as a reference label, or "" when it cannot be one. A
|
|
1018
|
+
// definition label holds no "]" (collectLinkDefinitions reads it with a class that excludes the closing
|
|
1019
|
+
// bracket), so a text that holds one names no definition and is not worth normalizing. With nested openers, as
|
|
1020
|
+
// many "![" and then "]", every level would otherwise normalize everything inside it, which is quadratic. The
|
|
1021
|
+
// first "]" after the opener comes from the position list, and the texts that are normalized end at that first
|
|
1022
|
+
// "]", so no two of them overlap.
|
|
1023
|
+
const imageLabelText = (k, m) => {
|
|
1024
|
+
const c = nextIdx("]", k + 1);
|
|
1025
|
+
return c !== -1 && c < m ? "" : text.slice(k + 1, m);
|
|
1026
|
+
};
|
|
865
1027
|
const skipImage = (k) => {
|
|
866
1028
|
const m = closeOf()[k];
|
|
867
1029
|
if (m < 0)
|
|
@@ -877,10 +1039,10 @@ function collectLinks(text, defs, lineBlocks) {
|
|
|
877
1039
|
if (n >= text.length || text[n] !== "]")
|
|
878
1040
|
return null;
|
|
879
1041
|
const raw = text.slice(m + 2, n);
|
|
880
|
-
const label = normalizeLinkLabel(raw === "" ?
|
|
1042
|
+
const label = normalizeLinkLabel(raw === "" ? imageLabelText(k, m) : raw);
|
|
881
1043
|
return label && refs.has(label) ? n + 1 : null;
|
|
882
1044
|
}
|
|
883
|
-
const own = normalizeLinkLabel(
|
|
1045
|
+
const own = normalizeLinkLabel(imageLabelText(k, m));
|
|
884
1046
|
return own && refs.has(own) ? m + 1 : null;
|
|
885
1047
|
};
|
|
886
1048
|
// True when the "[" at i sits where a link reference definition would start its line: only quote markers and a list marker
|
|
@@ -1077,7 +1239,7 @@ function isSetextH1(line, next) {
|
|
|
1077
1239
|
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
1240
|
const LINK_REF_DEF = /^ {0,3}\[[^\]]+\]:/;
|
|
1079
1241
|
// 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
|
|
1242
|
+
// 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
1243
|
function hasRawEnd(s, ends) { const t = s.toLowerCase(); return ends.some((e) => t.includes(e)); }
|
|
1082
1244
|
const RAW_HTML_BLOCKS = [
|
|
1083
1245
|
[/^ {0,3}<(?:pre|script|style|textarea)(?:[ \t>]|$)/i, ['</pre>', '</script>', '</style>', '</textarea>']],
|
|
@@ -1088,20 +1250,68 @@ const RAW_HTML_BLOCKS = [
|
|
|
1088
1250
|
];
|
|
1089
1251
|
// 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
1252
|
// 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
|
|
1092
|
-
// while the no-html check still reads them. A block
|
|
1253
|
+
// The lines of a block hold no Markdown, so the links and definitions are read from a text where they are blank,
|
|
1254
|
+
// while the no-html check still reads them. A block is read only where its start is certain (see htmlBlockLines).
|
|
1093
1255
|
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
1256
|
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]
|
|
1257
|
+
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;
|
|
1258
|
+
// The columns a line is indented by, a tab going to the next multiple of four.
|
|
1259
|
+
function indentColumns(l) {
|
|
1260
|
+
let col = 0;
|
|
1261
|
+
for (let p = 0; p < l.length; p++) {
|
|
1262
|
+
if (l[p] === " ")
|
|
1263
|
+
col++;
|
|
1264
|
+
else if (l[p] === "\t")
|
|
1265
|
+
col += 4 - (col % 4);
|
|
1266
|
+
else
|
|
1267
|
+
break;
|
|
1268
|
+
}
|
|
1269
|
+
return col;
|
|
1270
|
+
}
|
|
1271
|
+
// 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
|
|
1272
|
+
// 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
|
|
1273
|
+
// belong to the offset, and five or more, or none, leave it at marker width plus one.
|
|
1274
|
+
function listItemOffset(l, col) {
|
|
1275
|
+
const m = /^[ \t]*([-*+]|\d{1,9}[.)])([ \t]*)/.exec(l);
|
|
1276
|
+
if (!m)
|
|
1277
|
+
return 0;
|
|
1278
|
+
const after = l.slice(m[0].length);
|
|
1279
|
+
if (m[2] === "" && after !== "")
|
|
1280
|
+
return 0;
|
|
1281
|
+
if (/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/.test(l))
|
|
1282
|
+
return 0;
|
|
1283
|
+
const gap = m[2].replace(/\t/g, " ").length;
|
|
1284
|
+
return col + m[1].length + (after === "" || gap > 4 ? 1 : gap);
|
|
1285
|
+
}
|
|
1286
|
+
// 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
|
|
1287
|
+
// ATX heading that itself stood at such a place, is indented at most three columns and is outside every open list item.
|
|
1288
|
+
// Directly under a paragraph line, a quote line, a list item line or another HTML line a CommonMark reader may take the line
|
|
1289
|
+
// 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
|
|
1290
|
+
// here, so nothing is masked there and the lines keep the reading they have without this function. An item counts as open from
|
|
1291
|
+
// its marker line until a line after a blank line is indented less than its content offset; a line that follows text and is
|
|
1292
|
+
// indented less may be a lazy continuation, so it drops nothing and the item stays on the list, which only ever hides less. A
|
|
1293
|
+
// 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
|
|
1294
|
+
// 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
|
|
1295
|
+
// never comes.
|
|
1096
1296
|
function htmlBlockLines(lines, blocks) {
|
|
1097
1297
|
const out = new Array(lines.length).fill(false);
|
|
1098
1298
|
let open = false, ends = null;
|
|
1299
|
+
// The end markers of an opener that was left unread, while its end has not been seen.
|
|
1300
|
+
let pending = null;
|
|
1301
|
+
// The content offsets of the list items that may be open above the line.
|
|
1302
|
+
const items = [];
|
|
1303
|
+
// True when a block can start at the line for certain: at the start, after a blank line, after such a heading.
|
|
1304
|
+
let clean = true;
|
|
1099
1305
|
for (let i = 0; i < lines.length; i++) {
|
|
1100
1306
|
const l = lines[i];
|
|
1307
|
+
const here = clean;
|
|
1308
|
+
clean = false;
|
|
1101
1309
|
if (open) {
|
|
1102
1310
|
if (ends === null) {
|
|
1103
|
-
if (isMdBlank(l))
|
|
1311
|
+
if (isMdBlank(l)) {
|
|
1104
1312
|
open = false;
|
|
1313
|
+
clean = true;
|
|
1314
|
+
}
|
|
1105
1315
|
else
|
|
1106
1316
|
out[i] = true;
|
|
1107
1317
|
continue;
|
|
@@ -1111,24 +1321,49 @@ function htmlBlockLines(lines, blocks) {
|
|
|
1111
1321
|
open = false;
|
|
1112
1322
|
continue;
|
|
1113
1323
|
}
|
|
1114
|
-
if (blocks[i] < 0
|
|
1324
|
+
if (blocks[i] < 0)
|
|
1325
|
+
continue;
|
|
1326
|
+
if (isMdBlank(l)) {
|
|
1327
|
+
clean = true;
|
|
1328
|
+
continue;
|
|
1329
|
+
}
|
|
1330
|
+
const col = indentColumns(l);
|
|
1331
|
+
if (here)
|
|
1332
|
+
while (items.length > 0 && col < items[items.length - 1])
|
|
1333
|
+
items.pop();
|
|
1334
|
+
const offset = listItemOffset(l, col);
|
|
1335
|
+
if (offset > 0)
|
|
1336
|
+
items.push(offset);
|
|
1337
|
+
if (pending !== null) {
|
|
1338
|
+
if (hasRawEnd(l, pending))
|
|
1339
|
+
pending = null;
|
|
1340
|
+
continue;
|
|
1341
|
+
}
|
|
1342
|
+
if (offset > 0)
|
|
1115
1343
|
continue;
|
|
1344
|
+
clean = here && /^ {0,3}#{1,6}(?:[ \t]|$)/.test(l);
|
|
1345
|
+
const certain = here && items.length === 0;
|
|
1116
1346
|
let matched = false;
|
|
1117
1347
|
for (const [start, end] of RAW_HTML_BLOCKS) {
|
|
1118
1348
|
const m = start.exec(l);
|
|
1119
1349
|
if (!m)
|
|
1120
1350
|
continue;
|
|
1121
1351
|
matched = true;
|
|
1122
|
-
|
|
1123
|
-
if (
|
|
1124
|
-
|
|
1125
|
-
|
|
1352
|
+
const closed = hasRawEnd(l, end);
|
|
1353
|
+
if (certain) {
|
|
1354
|
+
out[i] = true;
|
|
1355
|
+
if (!closed) {
|
|
1356
|
+
open = true;
|
|
1357
|
+
ends = end;
|
|
1358
|
+
}
|
|
1126
1359
|
}
|
|
1360
|
+
else if (!closed)
|
|
1361
|
+
pending = end;
|
|
1127
1362
|
break;
|
|
1128
1363
|
}
|
|
1129
1364
|
if (matched)
|
|
1130
1365
|
continue;
|
|
1131
|
-
if (HTML_TYPE6.test(l) ||
|
|
1366
|
+
if (certain && (HTML_TYPE6.test(l) || HTML_TYPE7.test(l))) {
|
|
1132
1367
|
out[i] = true;
|
|
1133
1368
|
open = true;
|
|
1134
1369
|
ends = null;
|
|
@@ -1226,7 +1461,7 @@ function laterSetextH1(lines, fenced) {
|
|
|
1226
1461
|
for (const [start, end] of RAW_HTML_BLOCKS) {
|
|
1227
1462
|
const m = start.exec(l);
|
|
1228
1463
|
if (m) {
|
|
1229
|
-
if (!hasRawEnd(l
|
|
1464
|
+
if (!hasRawEnd(l, end))
|
|
1230
1465
|
rawEnd = end;
|
|
1231
1466
|
break;
|
|
1232
1467
|
}
|
|
@@ -1399,8 +1634,9 @@ function isAbsoluteHttpUrl(t) {
|
|
|
1399
1634
|
return (u.protocol === "http:" || u.protocol === "https:") && u.hostname !== "";
|
|
1400
1635
|
}
|
|
1401
1636
|
function redirectFailDetail(f) {
|
|
1637
|
+
// A location shown as only its scheme (maskLocation, ambiguous address) gives no host to validate.
|
|
1402
1638
|
if (f.reason === "off-host")
|
|
1403
|
-
return "redirects to " + f.location + ", a different host. llms.txt is host-scoped, so validate that host directly";
|
|
1639
|
+
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
1640
|
if (f.reason === "unsafe-target" && !f.location)
|
|
1405
1641
|
return "the host is not a public domain name, so no request was made";
|
|
1406
1642
|
if (f.reason === "unsafe-target")
|
|
@@ -1569,7 +1805,10 @@ export function validateLlmsTxt(f) {
|
|
|
1569
1805
|
linkedLineIdx.add(idx);
|
|
1570
1806
|
}
|
|
1571
1807
|
}
|
|
1572
|
-
|
|
1808
|
+
// A line inside a raw HTML block is no heading either: CommonMark reads "<?x", "## Docs", "?>" as one block of type 3
|
|
1809
|
+
// and ends it at the "?>", not at the heading, so the lines of the blocks that htmlBlockLines finds are masked like fences.
|
|
1810
|
+
const h2Mask = fenced.map((f, i) => f || htmlLine[i]);
|
|
1811
|
+
const hm = h2Lines(lines, h2Mask);
|
|
1573
1812
|
const sx = laterSetextH1(lines, fenced);
|
|
1574
1813
|
const h2Count = hm.h2.filter(Boolean).length;
|
|
1575
1814
|
// A section counts when it carries a file list. An H2 followed by a paragraph satisfied
|
|
@@ -1730,7 +1969,18 @@ export function validateLlmsTxt(f) {
|
|
|
1730
1969
|
add("links", "pass", "Markdown links an agent can follow", named.length + " link" + (named.length === 1 ? "" : "s") + ", all absolute URLs");
|
|
1731
1970
|
}
|
|
1732
1971
|
else {
|
|
1733
|
-
|
|
1972
|
+
// The scheme test reads a target to its end, so it runs once per distinct target, as isAbs does: many
|
|
1973
|
+
// references to one long definition would otherwise repeat it for each of them.
|
|
1974
|
+
const schemeMemo = new Map();
|
|
1975
|
+
const hasScheme = (t) => {
|
|
1976
|
+
let r = schemeMemo.get(t);
|
|
1977
|
+
if (r === undefined) {
|
|
1978
|
+
r = /^[a-z][a-z0-9+.-]*:/i.test(t);
|
|
1979
|
+
schemeMemo.set(t, r);
|
|
1980
|
+
}
|
|
1981
|
+
return r;
|
|
1982
|
+
};
|
|
1983
|
+
const relativeCount = named.filter((m) => !hasScheme(m.target)).length;
|
|
1734
1984
|
const hostless = named.length - absolute - relativeCount;
|
|
1735
1985
|
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
1986
|
}
|
|
@@ -2407,7 +2657,18 @@ function rawTextEnd(lower, name, from) {
|
|
|
2407
2657
|
function scriptEnd(lower, from) {
|
|
2408
2658
|
let i = from, escaped = false, doubleEscaped = false, close = -2;
|
|
2409
2659
|
while (i < lower.length) {
|
|
2410
|
-
if (lower.startsWith("<!--", i)) {
|
|
2660
|
+
if (!escaped && lower.startsWith("<!--", i)) {
|
|
2661
|
+
// "<!-->" and "<!--->" are over at once: the tokenizer reads the ">" that follows the two or three dashes as the end of
|
|
2662
|
+
// the escape start, so the script is not in the escaped state. Already escaped, "<!--" means nothing, and the "-->" that
|
|
2663
|
+
// overlaps it ends the escape through the search below.
|
|
2664
|
+
if (lower.startsWith("<!-->", i)) {
|
|
2665
|
+
i += 5;
|
|
2666
|
+
continue;
|
|
2667
|
+
}
|
|
2668
|
+
if (lower.startsWith("<!--->", i)) {
|
|
2669
|
+
i += 6;
|
|
2670
|
+
continue;
|
|
2671
|
+
}
|
|
2411
2672
|
escaped = true;
|
|
2412
2673
|
i += 4;
|
|
2413
2674
|
continue;
|
|
@@ -2496,7 +2757,10 @@ function templateEnd(lower, from) {
|
|
|
2496
2757
|
// Round S3 (Tek-546): every tag is read whole with the tokenizer's own states (tagEnd), so a "<"
|
|
2497
2758
|
// or a ">" inside a quoted attribute value is part of the tag and not markup (LV-26, U-8,
|
|
2498
2759
|
// WL-16), and the attributes of an end tag are read the same way (LV-25).
|
|
2499
|
-
|
|
2760
|
+
// A template inside svg or math is an ordinary foreign element, not an HTML template: it opens no level of depth, and
|
|
2761
|
+
// its end tag closes it (through the scope stack below) and not the HTML template this scan is looking for.
|
|
2762
|
+
const foreign = scopes.length > 0 && !scopes[scopes.length - 1].html;
|
|
2763
|
+
if (lower.startsWith("</template", lt) && !(foreign && open.get("template"))) {
|
|
2500
2764
|
const gt = tagEnd(lower, lt);
|
|
2501
2765
|
if (gt === -1)
|
|
2502
2766
|
return -1;
|
|
@@ -2510,7 +2774,7 @@ function templateEnd(lower, from) {
|
|
|
2510
2774
|
i = gt + 1;
|
|
2511
2775
|
continue;
|
|
2512
2776
|
}
|
|
2513
|
-
if (lower.startsWith("<template", lt) && isTagBoundary(lower[lt + 9])) {
|
|
2777
|
+
if (lower.startsWith("<template", lt) && isTagBoundary(lower[lt + 9]) && !foreign) {
|
|
2514
2778
|
const gt = tagEnd(lower, lt);
|
|
2515
2779
|
if (gt === -1)
|
|
2516
2780
|
return -1;
|
|
@@ -2986,9 +3250,11 @@ export async function validateHost(input, opts = {}) {
|
|
|
2986
3250
|
// back out of a message meant for people.
|
|
2987
3251
|
if (unusedPath)
|
|
2988
3252
|
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 (
|
|
2990
|
-
//
|
|
2991
|
-
//
|
|
2992
|
-
|
|
3253
|
+
// Text quoted from the fetched file leaves without bidirectional controls (mirrored from
|
|
3254
|
+
// worker.ts), without C0 and C1 controls and without the invisible
|
|
3255
|
+
// formatting characters of stripInvisible: a site's own H1 or summary could otherwise read in
|
|
3256
|
+
// another order here than in the file itself, or carry text no reader sees. Up to 0.7.4 the
|
|
3257
|
+
// line and paragraph separators, the marks, the zero-width characters and the tag characters stayed.
|
|
3258
|
+
const stripped = checks.map((c) => (typeof c.detail === "string" ? { ...c, detail: stripInvisible(stripControls(stripBidi(c.detail))) } : c));
|
|
2993
3259
|
return { target: "https://" + host + "/llms.txt", summary: summarizeChecks(stripped), checks: stripped };
|
|
2994
3260
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "turva-llms-txt-validator",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
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",
|