markdown-parity-check 0.2.38 → 0.2.39

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 { 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,21 @@ 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.
228
230
  const at = node.position?.start.offset;
229
- if (at !== undefined && ctx.source[at] !== '[' && ctx.source[at] !== '<' && insideHiddenUrlPart(ctx.source, at))
230
- link.masked = true;
231
+ if (at !== undefined && ctx.source[at] !== '[' && ctx.source[at] !== '<') {
232
+ if (insideHiddenUrlPart(ctx.source, at))
233
+ link.masked = true;
234
+ else if (ctx.source.includes('://')) {
235
+ ctx.userinfo ??= userinfoSpansOf(ctx.source);
236
+ if (insideUserinfoSpan(ctx.userinfo, at))
237
+ link.masked = true;
238
+ }
239
+ }
231
240
  run.links.push(link);
232
241
  run.links.push(...inner.links);
233
242
  run.text += inner.text;
@@ -257,27 +266,36 @@ function push(ctx, partial, node) {
257
266
  for (let i = ctx.wrappers.length - 1; i >= 0; i--) {
258
267
  const href = ctx.wrappers[i].href;
259
268
  if (href !== undefined)
260
- block.links.unshift({ text: strictNormalize(block.text), rawHref: href, resolved: resolveHref(href, ctx.base) });
269
+ block.links.unshift({ text: strictNormalize(block.text), ...(block.shown !== undefined ? { shown: block.shown } : {}), rawHref: href, resolved: resolveHref(href, ctx.base) });
261
270
  }
262
271
  ctx.blocks.push(block);
263
272
  }
264
273
  function handleTable(ctx, table, listItem) {
265
274
  const cells = [];
275
+ const cellsShown = [];
276
+ let anyShown = false;
266
277
  const links = [];
267
278
  for (const row of table.children) {
268
279
  const r = [];
280
+ const rShown = [];
269
281
  for (const cell of row.children) {
270
282
  const run = { text: '', links: [] };
271
283
  inlineChildren(ctx, cell.children, run, cell.position?.start.line);
272
284
  r.push(strictNormalize(run.text));
285
+ const shownCell = shownNormalize(run.text);
286
+ if (shownCell !== undefined)
287
+ anyShown = true;
288
+ rShown.push(shownCell ?? r[r.length - 1]);
273
289
  links.push(...run.links);
274
290
  }
275
291
  cells.push(r);
292
+ cellsShown.push(rShown);
276
293
  }
277
294
  if (cells.length === 0)
278
295
  return;
279
296
  const text = cells.map((r) => r.join(' | ')).join(' \n ');
280
- push(ctx, { type: 'table', text: strictNormalize(text), cells, links, ...(listItem ? { list: listItem } : {}) }, table);
297
+ const shownTable = anyShown ? { shown: strictNormalize(cellsShown.map((r) => r.join(' | ')).join(' \n ')), cellsShown } : {};
298
+ push(ctx, { type: 'table', text: strictNormalize(text), ...shownTable, cells, links, ...(listItem ? { list: listItem } : {}) }, table);
281
299
  }
282
300
  const LEADING_TYPES = new Set(['paragraph', 'heading', 'code', 'table', 'html']);
283
301
  function handle(ctx, node, listItem) {
@@ -289,7 +307,7 @@ function handle(ctx, node, listItem) {
289
307
  inlineChildren(ctx, node.children, run, node.position?.start.line);
290
308
  const text = strictNormalize(run.text);
291
309
  if (text !== '')
292
- push(ctx, { type: 'heading', text, depth: node.depth, links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
310
+ push(ctx, { type: 'heading', text, ...shownField(run.text), depth: node.depth, links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
293
311
  return;
294
312
  }
295
313
  case 'paragraph': {
@@ -299,7 +317,7 @@ function handle(ctx, node, listItem) {
299
317
  inlineChildren(ctx, node.children, run, node.position?.start.line);
300
318
  const text = strictNormalize(run.text);
301
319
  if (text !== '')
302
- push(ctx, { type: listItem ? 'listItem' : 'paragraph', text, links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
320
+ push(ctx, { type: listItem ? 'listItem' : 'paragraph', text, ...shownField(run.text), links: run.links, ...(listItem ? { list: listItem } : {}) }, node);
303
321
  return;
304
322
  }
305
323
  case 'code': {
@@ -399,6 +417,9 @@ function handleRawHtml(ctx, value, line, listItem) {
399
417
  // same element tree on the HTML side.
400
418
  if (err instanceof HtmlDepthError)
401
419
  throw new HtmlDepthError(err.depth - 1, ctx.maxDepth);
420
+ // A link target over the limit stops the comparison, as it does on the HTML side.
421
+ if (err instanceof LinkTargetError)
422
+ throw err;
402
423
  parsed = null;
403
424
  }
404
425
  const blocks = parsed?.blocks ?? [];
@@ -483,8 +504,13 @@ function openWrappers(fragment) {
483
504
  onopentag(name, attribs) {
484
505
  const covers = attribs['hidden'] !== undefined || attribs['aria-hidden'] === 'true' || opensExcludedSubtree(name, attribs);
485
506
  const wrapper = { name, covers };
486
- if (name === 'a' && attribs['href'] !== undefined && !covers)
507
+ if (name === 'a' && attribs['href'] !== undefined && !covers) {
508
+ // The href is written into the prefix of every raw HTML block that follows while the anchor is open, so a long
509
+ // one costs its length for each of them (0.2.39), also inside a wrapper that hides the blocks and never resolves it.
510
+ if (attribs['href'].length > MAX_LINK_TARGET_CHARS)
511
+ throw new LinkTargetError(attribs['href'].length);
487
512
  wrapper.href = attribs['href'];
513
+ }
488
514
  stack.push(wrapper);
489
515
  },
490
516
  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,8 +48,68 @@ 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;
49
111
  /** 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
112
+ * maskParenUserinfo and maskAuthorityUserinfo run first, for the shapes the runs of RUN cannot see as one URL, and
51
113
  * stripControlChars runs last so a raw ANSI escape from a compared page or an argument cannot reach a plain
52
114
  * --format text report (0.2.16, found by an outside review 2026-09-28). */
53
115
  export declare function redactText(text: string): string;
@@ -68,7 +130,19 @@ export declare function visibleNumbers(text: string): string[];
68
130
  * Unicode spaces, which the URL parser keeps as part of the address, so a target that differs by one of them
69
131
  * compared equal (MP-16). */
70
132
  export declare function trimHref(href: string): string;
71
- /** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. */
133
+ /** The longest link target the comparison accepts, in characters of the href as the page or the Markdown wrote it.
134
+ * Up to 0.2.38 the length had no bound, and the time of the comparison grew with the length times the number of
135
+ * links, blocks or references that handle it again (minutes for a few thousand links against a 100 000 character
136
+ * target). 8192 is the longest request line the Apache default accepts and is far above any link a page needs;
137
+ * a data: URI longer than this is not a link a reader follows. */
138
+ export declare const MAX_LINK_TARGET_CHARS = 8192;
139
+ /** A link target is longer than MAX_LINK_TARGET_CHARS. It names the length and never repeats the target. */
140
+ export declare class LinkTargetError extends Error {
141
+ readonly length: number;
142
+ constructor(length: number);
143
+ }
144
+ /** Resolves a possibly relative href against a base. Returns null when it cannot be resolved. Throws a
145
+ * LinkTargetError for a target longer than MAX_LINK_TARGET_CHARS. */
72
146
  export declare function resolveHref(rawHref: string, base: string | null): string | null;
73
147
  /** Masks query values, drops the fragment and removes user information for display in reports and logs.
74
148
  * Never returns the raw query or the credentials of an unparseable input either. */