markdown-parity-check 0.2.38 → 0.2.40

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.
@@ -5,7 +5,7 @@ import { gfmFromMarkdown } from 'mdast-util-gfm';
5
5
  import { BLOCK_TAGS, extractHtml, HtmlDepthError, MAX_NESTING_DEPTH, opensExcludedSubtree } from './html.js';
6
6
  import { parseDocument, Parser } from 'htmlparser2';
7
7
  import { Element, Text } from 'domhandler';
8
- import { excerpt, extractNumbers, insideHiddenUrlPart, looseNormalize, normalizeCode, resolveHref, strictNormalize } from './normalize.js';
8
+ import { bareUserinfoSpansOf, excerpt, extractNumbers, insideHiddenUrlPart, insideUserinfoSpan, LinkTargetError, looseNormalize, MAX_LINK_TARGET_CHARS, normalizeCode, resolveHref, shownField, shownNormalize, strictNormalize, userinfoSpansOf } from './normalize.js';
9
9
  export class MarkdownExtractError extends Error {
10
10
  }
11
11
  /** Deepest node nesting of a Markdown tree, counted with an explicit stack. */
@@ -143,7 +143,7 @@ function inlineChildren(ctx, children, run, line) {
143
143
  inlineChildren(ctx, children.slice(i + 1, end), inner, line);
144
144
  const href = tag.attribs['href'];
145
145
  if (href !== undefined)
146
- run.links.push({ text: strictNormalize(inner.text), rawHref: href, resolved: resolveHref(href, ctx.base) });
146
+ run.links.push({ text: strictNormalize(inner.text), ...shownField(inner.text), rawHref: href, resolved: resolveHref(href, ctx.base) });
147
147
  run.links.push(...inner.links);
148
148
  run.text += inner.text;
149
149
  i = end;
@@ -207,7 +207,7 @@ function inline(ctx, node, run) {
207
207
  inlineChildren(ctx, node.children, inner, node.position?.start.line);
208
208
  const def = ctx.definitions.get(node.identifier);
209
209
  if (def) {
210
- run.links.push({ text: strictNormalize(inner.text), rawHref: def.url, resolved: resolveHref(def.url, ctx.base) });
210
+ run.links.push({ text: strictNormalize(inner.text), ...shownField(inner.text), rawHref: def.url, resolved: resolveHref(def.url, ctx.base) });
211
211
  run.links.push(...inner.links);
212
212
  run.text += inner.text;
213
213
  }
@@ -222,12 +222,27 @@ function inline(ctx, node, run) {
222
222
  case 'link': {
223
223
  const inner = { text: '', links: [] };
224
224
  inlineChildren(ctx, node.children, inner, node.position?.start.line);
225
- const link = { text: strictNormalize(inner.text), rawHref: node.url, resolved: resolveHref(node.url, ctx.base) };
225
+ const link = { text: strictNormalize(inner.text), ...shownField(inner.text), rawHref: node.url, resolved: resolveHref(node.url, ctx.base) };
226
226
  // A GFM literal autolink starts with neither [ nor <. One that GFM found inside a hidden part of another URL
227
- // is compared as usual but shown masked (0.2.12).
227
+ // is compared as usual but shown masked (0.2.12). So is one that starts inside the user information of an
228
+ // address, scheme included, which GFM cuts at white space: the head of "https://user:pa ss@host/" is a link of
229
+ // its own, and so is the tail "ss@host" read as an e-mail address. The same holds for the "secret@host.example"
230
+ // that GFM reads out of user:secret@host.example/path, which has no scheme separator (0.2.40).
228
231
  const at = node.position?.start.offset;
229
- if (at !== undefined && ctx.source[at] !== '[' && ctx.source[at] !== '<' && insideHiddenUrlPart(ctx.source, at))
230
- link.masked = true;
232
+ if (at !== undefined && ctx.source[at] !== '[' && ctx.source[at] !== '<') {
233
+ if (insideHiddenUrlPart(ctx.source, at))
234
+ link.masked = true;
235
+ else if (ctx.source.includes('://')) {
236
+ ctx.userinfo ??= userinfoSpansOf(ctx.source);
237
+ if (insideUserinfoSpan(ctx.userinfo, at))
238
+ link.masked = true;
239
+ }
240
+ if (!link.masked && ctx.source.includes('@')) {
241
+ ctx.bareUserinfo ??= bareUserinfoSpansOf(ctx.source);
242
+ if (insideUserinfoSpan(ctx.bareUserinfo, at))
243
+ link.masked = true;
244
+ }
245
+ }
231
246
  run.links.push(link);
232
247
  run.links.push(...inner.links);
233
248
  run.text += inner.text;
@@ -257,27 +272,36 @@ function push(ctx, partial, node) {
257
272
  for (let i = ctx.wrappers.length - 1; i >= 0; i--) {
258
273
  const href = ctx.wrappers[i].href;
259
274
  if (href !== undefined)
260
- block.links.unshift({ text: strictNormalize(block.text), rawHref: href, resolved: resolveHref(href, ctx.base) });
275
+ block.links.unshift({ text: strictNormalize(block.text), ...(block.shown !== undefined ? { shown: block.shown } : {}), rawHref: href, resolved: resolveHref(href, ctx.base) });
261
276
  }
262
277
  ctx.blocks.push(block);
263
278
  }
264
279
  function handleTable(ctx, table, listItem) {
265
280
  const cells = [];
281
+ const cellsShown = [];
282
+ let anyShown = false;
266
283
  const links = [];
267
284
  for (const row of table.children) {
268
285
  const r = [];
286
+ const rShown = [];
269
287
  for (const cell of row.children) {
270
288
  const run = { text: '', links: [] };
271
289
  inlineChildren(ctx, cell.children, run, cell.position?.start.line);
272
290
  r.push(strictNormalize(run.text));
291
+ const shownCell = shownNormalize(run.text);
292
+ if (shownCell !== undefined)
293
+ anyShown = true;
294
+ rShown.push(shownCell ?? r[r.length - 1]);
273
295
  links.push(...run.links);
274
296
  }
275
297
  cells.push(r);
298
+ cellsShown.push(rShown);
276
299
  }
277
300
  if (cells.length === 0)
278
301
  return;
279
302
  const text = cells.map((r) => r.join(' | ')).join(' \n ');
280
- push(ctx, { type: 'table', text: strictNormalize(text), cells, links, ...(listItem ? { list: listItem } : {}) }, table);
303
+ const shownTable = anyShown ? { shown: strictNormalize(cellsShown.map((r) => r.join(' | ')).join(' \n ')), cellsShown } : {};
304
+ push(ctx, { type: 'table', text: strictNormalize(text), ...shownTable, cells, links, ...(listItem ? { list: listItem } : {}) }, table);
281
305
  }
282
306
  const LEADING_TYPES = new Set(['paragraph', 'heading', 'code', 'table', 'html']);
283
307
  function handle(ctx, node, listItem) {
@@ -289,7 +313,7 @@ function handle(ctx, node, listItem) {
289
313
  inlineChildren(ctx, node.children, run, node.position?.start.line);
290
314
  const text = strictNormalize(run.text);
291
315
  if (text !== '')
292
- push(ctx, { type: 'heading', text, depth: node.depth, links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
316
+ push(ctx, { type: 'heading', text, ...shownField(run.text), depth: node.depth, links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
293
317
  return;
294
318
  }
295
319
  case 'paragraph': {
@@ -299,7 +323,7 @@ function handle(ctx, node, listItem) {
299
323
  inlineChildren(ctx, node.children, run, node.position?.start.line);
300
324
  const text = strictNormalize(run.text);
301
325
  if (text !== '')
302
- push(ctx, { type: listItem ? 'listItem' : 'paragraph', text, links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
326
+ push(ctx, { type: listItem ? 'listItem' : 'paragraph', text, ...shownField(run.text), links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
303
327
  return;
304
328
  }
305
329
  case 'code': {
@@ -399,6 +423,9 @@ function handleRawHtml(ctx, value, line, listItem) {
399
423
  // same element tree on the HTML side.
400
424
  if (err instanceof HtmlDepthError)
401
425
  throw new HtmlDepthError(err.depth - 1, ctx.maxDepth);
426
+ // A link target over the limit stops the comparison, as it does on the HTML side.
427
+ if (err instanceof LinkTargetError)
428
+ throw err;
402
429
  parsed = null;
403
430
  }
404
431
  const blocks = parsed?.blocks ?? [];
@@ -483,8 +510,13 @@ function openWrappers(fragment) {
483
510
  onopentag(name, attribs) {
484
511
  const covers = attribs['hidden'] !== undefined || attribs['aria-hidden'] === 'true' || opensExcludedSubtree(name, attribs);
485
512
  const wrapper = { name, covers };
486
- if (name === 'a' && attribs['href'] !== undefined && !covers)
513
+ if (name === 'a' && attribs['href'] !== undefined && !covers) {
514
+ // The href is written into the prefix of every raw HTML block that follows while the anchor is open, so a long
515
+ // one costs its length for each of them (0.2.39), also inside a wrapper that hides the blocks and never resolves it.
516
+ if (attribs['href'].length > MAX_LINK_TARGET_CHARS)
517
+ throw new LinkTargetError(attribs['href'].length);
487
518
  wrapper.href = attribs['href'];
519
+ }
488
520
  stack.push(wrapper);
489
521
  },
490
522
  onclosetag() {
@@ -2,6 +2,9 @@ export type BlockType = 'heading' | 'paragraph' | 'listItem' | 'table' | 'code';
2
2
  export interface Link {
3
3
  /** Visible anchor text, strictly normalized. */
4
4
  text: string;
5
+ /** The anchor text as a report shows it, set only when the credential masking needs the white space the comparison
6
+ * text has lost. Never compared. */
7
+ shown?: string;
5
8
  /** Href as the parser returned it, with character references decoded, before resolution against a base URL. */
6
9
  rawHref: string;
7
10
  /** Href resolved against the document base, or null when it could not be resolved. */
@@ -22,12 +25,17 @@ export interface Block {
22
25
  type: BlockType;
23
26
  /** Comparison text after strictNormalize: case kept, NFC applied, ZERO_WIDTH characters removed, whitespace collapsed. */
24
27
  text: string;
28
+ /** The text as a report shows it, set only when the credential masking needs the white space the comparison text
29
+ * has lost (a credential with a tab or a line break inside it). Never compared, never aligned. */
30
+ shown?: string;
25
31
  /** Loosely normalized text, used for alignment and to classify minor text differences. */
26
32
  loose: string;
27
33
  /** Heading depth 1..6 for headings. */
28
34
  depth?: number;
29
35
  /** Table cells row by row, strictly normalized. Only for type 'table'. */
30
36
  cells?: string[][];
37
+ /** The cells as a report shows them, set together with shown. Never compared. */
38
+ cellsShown?: string[][];
31
39
  /** Only for type 'table', HTML side: a cell carries a rowspan or colspan, so a plain row/column reading cannot
32
40
  * place its value reliably. compare.ts skips the cell-by-cell check for this block and relies on the
33
41
  * EXTRACTION_TABLE_SPAN_NOT_COMPARED issue extraction already raised (0.2.16). */
@@ -12,6 +12,12 @@ export declare function isPublicIPv4(ip: string): boolean;
12
12
  export declare function expandIPv6(ip: string): number[] | null;
13
13
  export declare function isPublicIPv6(ip: string): boolean;
14
14
  export declare function isPublicAddress(ip: string): boolean;
15
- /** Throws when the host name itself is a non-public literal or a local name. */
15
+ /**
16
+ * Throws when the host name itself is a non-public literal or a local name. The argument is the host name as the URL
17
+ * parser writes it, `url.hostname` of a parsed `URL`: the parser has already turned a literal in another notation, such
18
+ * as 2130706433, 0x7f.0.0.1 or 127.1, into dotted decimal. A string that did not go through the parser is not read
19
+ * that way here. The package's own fetch passes `url.hostname` and then checks every resolved address with
20
+ * assertPublicResolved, and a caller that fetches on its own does the same.
21
+ */
16
22
  export declare function assertPublicHost(hostname: string): void;
17
23
  export declare function assertPublicResolved(hostname: string, address: string): void;
@@ -176,7 +176,10 @@ export function isPublicIPv6(ip) {
176
176
  return isPublicIPv4(v4FromGroups(g1, g2)); // 6to4
177
177
  if (g0 === 0x0100 && g1 === 0 && g2 === 0 && g3 === 0)
178
178
  return false; // 100::/64 discard
179
- return true;
179
+ // Only 2000::/3 is global unicast space that the IANA has allocated, so it is the one block that is public unless a
180
+ // check above refused it. Every other block is reserved or special, and a form such as 0:1::1 or 8000::1, which the
181
+ // deny list of up to 0.2.38 let through, has no route on the internet.
182
+ return (g0 & 0xe000) === 0x2000;
180
183
  }
181
184
  /**
182
185
  * 2001::/23 is not globally reachable except for the blocks the IANA IPv6 Special-Purpose Address Registry marks
@@ -208,7 +211,13 @@ export function isPublicAddress(ip) {
208
211
  return isPublicIPv6(ip);
209
212
  return false;
210
213
  }
211
- /** Throws when the host name itself is a non-public literal or a local name. */
214
+ /**
215
+ * Throws when the host name itself is a non-public literal or a local name. The argument is the host name as the URL
216
+ * parser writes it, `url.hostname` of a parsed `URL`: the parser has already turned a literal in another notation, such
217
+ * as 2130706433, 0x7f.0.0.1 or 127.1, into dotted decimal. A string that did not go through the parser is not read
218
+ * that way here. The package's own fetch passes `url.hostname` and then checks every resolved address with
219
+ * assertPublicResolved, and a caller that fetches on its own does the same.
220
+ */
212
221
  export function assertPublicHost(hostname) {
213
222
  let h = hostname.toLowerCase().replace(/\.$/, '');
214
223
  if (h.startsWith('[') && h.endsWith(']'))
@@ -14,7 +14,9 @@ export declare function textKey(text: string): string;
14
14
  * a changed soft hyphen or a composed against a decomposed letter is a change of the code (0.2.22, found by an
15
15
  * outside review 2026-10-02). */
16
16
  export declare function codeWhitespaceKey(code: string): string;
17
- /** Code content: CRLF and CR line endings become LF and every trailing newline is removed; other whitespace is kept. */
17
+ /** Code content: CRLF and CR line endings become LF and every trailing newline is removed; other whitespace is kept.
18
+ * The trailing newlines are counted off from the end. The expression /\n+$/ that did this up to 0.2.38 starts a new
19
+ * scan at every newline of a long run and takes time quadratic in its length. */
18
20
  export declare function normalizeCode(code: string): string;
19
21
  /** Removes the escape character (which starts an ANSI escape sequence), the other C0 and C1 controls and the Unicode
20
22
  * bidi controls from a value that may come from a compared page or a raw argument, so a plain --format text report
@@ -46,10 +48,98 @@ export declare function insideParenUserinfo(text: string, at: number): boolean;
46
48
  * on the side of masking.
47
49
  */
48
50
  export declare function insideHiddenUrlPart(text: string, at: number): boolean;
51
+ /**
52
+ * Masks the user information of every "scheme://authority" in a piece of text, wherever the scheme sits and
53
+ * whatever the user information starts with (0.2.39, found by an outside review 2026-11-14). The run-based masking
54
+ * above reads the text in runs that end at white space and at the characters < > " ' ( ), so a URL whose user name
55
+ * opens with one of them, such as https://"admin":secret@host/ or https://(token)@host/, was cut in two runs, and a
56
+ * URL that follows "=", "," or ":" in the same run, such as redirect_uri=https://u:secret@host/cb?state=1, was read as
57
+ * one run that starts at its first character, where the parser finds no scheme and so no user information. Here the
58
+ * authority is the text after "://" up to the next slash, backslash, question mark, number sign or white space, as
59
+ * the URL parser reads it, and its user information ends at the last "@" in it. The scheme is the run of scheme
60
+ * characters before "://" that holds a letter. The user information becomes ***, so the host, path and query reach
61
+ * the run-based masking as before. One pass: an authority ends at a slash, so no two of them overlap.
62
+ *
63
+ * With whiteSpaceInside, a tab, a line feed or a carriage return inside the authority does not end it, as the URL
64
+ * parser removes them, and nor does any other white space when the text up to the last "@" holds a colon that is not
65
+ * followed by white space ("https://example.com: see me@x.org" is prose), so
66
+ * https://us er:secret@host/ and https://user:pa ss@host/ are masked whole. Without a colon the white space ends the
67
+ * authority, so "visit https://example.com for me@x.org" is prose. The authority does not go on past white
68
+ * space either when the text between its last colon and that white space is a port, one to five digits, or the end
69
+ * of a bracketed host, so "Use https://api.example.com:8443 or write to ops@example.org" keeps the address; a
70
+ * password of digits only that is followed by white space is therefore not masked. Only the report text uses it: the
71
+ * numbers of the comparison are read through hideUrlSecrets, which does not.
72
+ */
73
+ export declare function maskAuthorityUserinfo(text: string, whiteSpaceInside?: boolean): string;
74
+ /** One user information found by findUserinfoSpans: start is the first character of the scheme, from the first
75
+ * character after "://" and at the "@" that ends the user information. */
76
+ export interface UserinfoSpan {
77
+ start: number;
78
+ from: number;
79
+ at: number;
80
+ }
81
+ /** The user information of every "scheme://authority" of a text, in order and without overlap. The rules are the
82
+ * ones maskAuthorityUserinfo describes. */
83
+ export declare function findUserinfoSpans(text: string, whiteSpaceInside?: boolean): UserinfoSpan[];
84
+ /** The text as a report shows it, for a raw text whose white space the credential masking needs: undefined when
85
+ * dropAuthorityControls changes nothing, else the normalized text without the white space inside user information.
86
+ * It is for display only. The comparison keys come from strictNormalize alone, as in 0.2.38, because removing the
87
+ * white space there made two texts that differ only in the kind of white space compare unequal, and the reverse. */
88
+ export declare function shownNormalize(raw: string): string | undefined;
89
+ /** shownNormalize as an object to spread into a block or a link: {} or { shown }. */
90
+ export declare function shownField(raw: string): {
91
+ shown?: string;
92
+ };
93
+ /**
94
+ * Removes a tab, a vertical tab, a form feed, a line feed or a carriage return from the user information of a
95
+ * "scheme://authority" when it is a credential, in a text that is only displayed, before the white space is
96
+ * collapsed into a plain space. It is never part of a comparison key. The URL
97
+ * parser drops a tab, a line feed and a carriage return from an address, and none of the five can stand in a user
98
+ * name or a password a reader sees, but a plain space after the colon of "https://user: secret@host" makes the
99
+ * masking read prose, so the password reached the report. Only an authority that ends at the first white space other
100
+ * than these five is read, and only one that holds a colon in front of the last "@", which is not followed by a plain
101
+ * space and does not end a port: "https://example.com:8443" and a line break and then an address is text. Without
102
+ * a colon only a tab, a vertical tab and a form feed count, because a line break between an address and an e-mail
103
+ * address is ordinary text.
104
+ */
105
+ export declare function dropAuthorityControls(text: string): string;
106
+ /** The user information of a source text, computed once for the positions of its links. The characters that
107
+ * stripControlChars removes are read as a tab, which keeps every position and does not end an authority. */
108
+ export declare function userinfoSpansOf(text: string): UserinfoSpan[];
109
+ /** Whether position at lies in a user information of spans, scheme included, the "@" included. */
110
+ export declare function insideUserinfoSpan(spans: UserinfoSpan[], at: number): boolean;
111
+ /**
112
+ * The credential-shaped "label:name@host" of a text that has no scheme separator, as in user:secret@host.example/p
113
+ * (0.2.40, found by an independent check of 0.2.39). The URL parser reads "user:" as a scheme and the rest as an opaque
114
+ * path, so maskHref found no user information, and GFM read "secret@host.example" as an e-mail address, so the
115
+ * secret reached a report as an excerpt and as the text and the target of a link. A span is found in a run (RUN) when
116
+ * a label, the letters, digits and the characters + . - that start with a letter and follow no scheme character,
117
+ * is followed by a colon and then by text that holds an "@" before the first slash, backslash, question mark or number
118
+ * sign, and that delimiter, which must be there, makes the address a URL-like one: a slash or a backslash, a query that
119
+ * starts with a name and an equals sign, or a number sign with an equals sign later in the run. The text after the
120
+ * last "@" up to the delimiter must be a host name (isBareHostText). The user information is the text between the
121
+ * colon and that "@", and it must not be empty.
122
+ *
123
+ * Not a span, so shown as written: a special scheme (https:user@host/ is masked by the other rules), a scheme of
124
+ * ADDRESS_SCHEMES, a label that follows a slash (the authority rules read //name:secret@host/), an address that
125
+ * no delimiter follows, as in "Contact:jane@example.com", and a question mark or a number sign that is not followed by
126
+ * a value, as in "Did you mean To:jane@example.com?". "label:jane@example.com" with no space is therefore shown
127
+ * unless a path, a query value or a fragment value follows, because text alone cannot tell a label from a user name.
128
+ * A failed candidate is scanned to its own delimiter and a found one to its "@", so the scan stays linear. The result
129
+ * is a display aid and is never part of a comparison key.
130
+ */
131
+ export declare function findBareUserinfoSpans(text: string): UserinfoSpan[];
132
+ /** Masks the user information of every "label:name@host/path" that findBareUserinfoSpans finds, and leaves the label,
133
+ * the host and the rest as they are: user:secret@host.example/p?x=1 reads user:***@host.example/p?x=1. Display only. */
134
+ export declare function maskBareUserinfo(text: string): string;
135
+ /** The spans of findBareUserinfoSpans for a source text, with the characters that stripControlChars removes read as
136
+ * a letter, which keeps every position and does not end a run or a label. */
137
+ export declare function bareUserinfoSpansOf(text: string): UserinfoSpan[];
49
138
  /** Masks user information, query values and fragments of every URL-like run in a piece of report text.
50
- * maskParenUserinfo runs first for the parenthesized-userinfo shape RUN cannot see as one run, and
51
- * stripControlChars runs last so a raw ANSI escape from a compared page or an argument cannot reach a plain
52
- * --format text report (0.2.16, found by an outside review 2026-09-28). */
139
+ * maskParenUserinfo and maskAuthorityUserinfo run first, for the shapes the runs of RUN cannot see as one URL, and
140
+ * maskBareUserinfo for the name:secret@host shape without a scheme separator. stripControlChars runs last so a raw
141
+ * ANSI escape from a compared page or an argument cannot reach a plain --format text report (0.2.16, found by an
142
+ * outside review 2026-09-28). */
53
143
  export declare function redactText(text: string): string;
54
144
  /**
55
145
  * The text with the parts that maskHref hides taken out of every URL-like run: user information, query values
@@ -68,7 +158,19 @@ export declare function visibleNumbers(text: string): string[];
68
158
  * Unicode spaces, which the URL parser keeps as part of the address, so a target that differs by one of them
69
159
  * compared equal (MP-16). */
70
160
  export declare function trimHref(href: string): string;
71
- /** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. */
161
+ /** The longest link target the comparison accepts, in characters of the href as the page or the Markdown wrote it.
162
+ * Up to 0.2.38 the length had no bound, and the time of the comparison grew with the length times the number of
163
+ * links, blocks or references that handle it again (minutes for a few thousand links against a 100 000 character
164
+ * target). 8192 is the longest request line the Apache default accepts and is far above any link a page needs;
165
+ * a data: URI longer than this is not a link a reader follows. */
166
+ export declare const MAX_LINK_TARGET_CHARS = 8192;
167
+ /** A link target is longer than MAX_LINK_TARGET_CHARS. It names the length and never repeats the target. */
168
+ export declare class LinkTargetError extends Error {
169
+ readonly length: number;
170
+ constructor(length: number);
171
+ }
172
+ /** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. Throws a
173
+ * LinkTargetError for a target longer than MAX_LINK_TARGET_CHARS. */
72
174
  export declare function resolveHref(rawHref: string, base: string | null): string | null;
73
175
  /** Masks query values, drops the fragment and removes user information for display in reports and logs.
74
176
  * Never returns the raw query or the credentials of an unparseable input either. */