import { Meta } from '@storybook/addon-docs/blocks';
import {
  MAX_NESTING_DEPTH,
  MAX_INPUT_LENGTH,
  MAX_ACCESSIBILITY_LABEL_LENGTH,
} from '../utils/parseMarkup';
import { Vulnerability, Badge } from './Vulnerability/Vulnerability';
import { InfoPrompt } from '../../Prompt/InfoPrompt/';
import Link from '../../Link/';

<Meta title="Typography/Markup/Parser security" />

# Parser security

## Security model

Five layers, each independent:

1. Tag allow-list (tokeniser). Only known tags are tokenised. `<script>`, `<img>`, `<iframe>`, etc. stay as
   literal text.
2. Attribute allow-list (parseAttributes). Only `href`, `action`, `target`, `accessibilityLabel` are extracted. `onclick`, `onerror`, etc. are silently ignored.
3. Protocol allow-list (sanitise). Only `https:`, `mailto:`, `/path`, and `#fragment` are allowed. Relative paths (`./`, `../`), `javascript:`, `data:`, `//`, and all other schemes are blocked.
4. Link destination mode (`allowLinks`). The `internal` mode (default) restricts links to root-relative paths and `https://wise.com/*`. Root-relative paths are validated through the WHATWG URL parser to ensure they don't escape same-origin after browser normalization.
5. Input limits. Input exceeding {MAX_INPUT_LENGTH} characters is returned as plain text (DoS prevention). `accessibilityLabel` is capped at {MAX_ACCESSIBILITY_LABEL_LENGTH} characters (social engineering prevention).

No `dangerouslySetInnerHTML` is used anywhere. The parser produces a typed AST, and the renderer maps it to React elements — React's own escaping handles the rest.

<InfoPrompt
  description={
    <>
      {'The parser has been tested against the attack vectors documented in '}
      <Link href="https://github.com/cure53/DOMPurify">DOMPurify 3.4.11</Link>
      {' and '}
      <Link href="https://github.com/apostrophecms/sanitize-html">sanitize-html 2.17.5</Link>
      {
        '. It aims to match the security grading of those industry-standard libraries within the scope of its supported markup subset.'
      }
    </>
  }
/>

<br />
<br />

## Attack vector

This page documents all attack vectors tested against the Markup component. Each section shows the raw malicious input and how the component neutralises it.

### XSS: Dangerous protocols

#### javascript: protocol <Badge severity="High" />

The `javascript:` protocol is blocked by the href sanitiser. The link degrades to plain text.

<Vulnerability markup='<link href="javascript:alert(1)">click me</link>' />

#### javascript: mixed case <Badge severity="High" />

`new URL()` normalises the protocol to lowercase before checking the allowlist.

<Vulnerability markup='<link href="JavaScript:alert(1)">mixed case</link>' />

#### data: URI with script <Badge severity="High" />

The `data:` protocol is blocked regardless of MIME type or encoding.

<Vulnerability markup='<link href="data:text/html,<script>alert(1)</script>">data URI</link>' />

#### data: base64-encoded <Badge severity="High" />

Base64-encoded payloads are equally blocked.

<Vulnerability markup='<link href="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==">base64</link>' />

#### vbscript: protocol <Badge severity="High" />

Legacy protocol explicitly blocked.

<Vulnerability markup='<link href="vbscript:MsgBox(1)">vbscript</link>' />

#### SVG data URI in href <Badge severity="High" />

SVG data URIs can contain executable JavaScript. Blocked by the `data:` protocol check.

<Vulnerability markup='<link href="data:image/svg+xml,<svg onload=alert(1)>">svg data</link>' />

### XSS: Control character bypass

#### Null byte in scheme <Badge severity="High" />

Null bytes inserted mid-scheme cause URL parsing to fail. The sanitiser rejects any href containing control characters.

<Vulnerability markup={'<link href="java\x00script:alert(1)">null byte</link>'} />

#### Zero-width space prefix <Badge severity="High" />

Invisible characters (ZWSP, BOM, ZWNJ) are stripped before validation so they cannot bypass `.trim()`.

<Vulnerability markup={'<link href="​javascript:alert(1)">invisible prefix</link>'} />

#### URL-encoded colon (%3A) <Badge severity="Medium" />

The sanitiser checks for `javascript%3a` patterns that evade URL constructor parsing.

<Vulnerability markup='<link href="javascript%3Aalert(1)">encoded colon</link>' />

### XSS: HTML tag injection

#### &lt;script&gt; tag <Badge severity="High" />

Not in the allowed tag list. Never tokenised — remains as escaped text.

<Vulnerability markup='<script>alert("xss")</script>' />

#### Deeply malformed nesting with &lt;script&gt; <Badge severity="High" />

Mismatched closing tags, interleaved valid and invalid elements, and duplicated `<script>` blocks
cannot confuse the parser into executing code. Unrecognised tags stay as literal text, and
mismatched close tags degrade to visible text — no combination of malformed nesting can promote
a `<script>` to an executable element.

<Vulnerability markup="start <strong>hello<important></strong><script>console.log(1)</strong><script>console.log(1)</script></important>" />

#### &lt;img onerror&gt; <Badge severity="High" />

Not in the allowed tag list. Passes through as literal text rendered via `textContent`.

<Vulnerability markup="<img src=x onerror=alert(1)>" />

#### &lt;svg onload&gt; <Badge severity="High" />

Not in the allowed tag list. Rendered as harmless text content.

<Vulnerability markup="<svg onload=alert(1)>" />

#### &lt;svg&gt; inside allowed element <Badge severity="High" />

Even inside a valid element, unrecognised tags are text nodes. React escapes them.

<Vulnerability markup="<important><svg onload=alert(1)></important>" />

#### &lt;iframe&gt; injection <Badge severity="High" />

Not in the allowed tag list. The entire string renders as escaped text.

<Vulnerability markup='<iframe src="javascript:alert(1)"></iframe>' />

#### &lt;img&gt; inside link <Badge severity="High" />

Unrecognised tags within link content are safe text children.

<Vulnerability markup='<link href="/safe"><img src=x onerror=alert(1)></link>' />

#### &lt;input&gt; with autofocus <Badge severity="High" />

Not in the allowed tag list. Cannot trigger focus-based XSS.

<Vulnerability markup="<input onfocus=alert(1) autofocus>" />

#### &lt;details ontoggle&gt; <Badge severity="High" />

Not in the allowed tag list. Cannot trigger toggle-based XSS.

<Vulnerability markup="<details open ontoggle=alert(1)>" />

### XSS: Attribute injection

#### onclick attribute on link <Badge severity="High" />

Only `href`, `action`, `target`, and `accessibilityLabel` are extracted. All event handlers are discarded.

<Vulnerability markup='<link href="/safe" onclick="alert(1)">click</link>' />

#### HTML in accessibilityLabel <Badge severity="Medium" />

HTML metacharacters are stripped from `accessibilityLabel` to prevent injection if the value is ever used in an unsafe context.

<Vulnerability markup='<important accessibilityLabel="&lt;img onerror=alert(1)&gt;">safe text</important>' />

#### Slash as attribute separator <Badge severity="Low" />

The attribute regex now requires whitespace before attribute names. `<link/href="x">` no longer parses the href.

<Vulnerability markup='<link/href="/evil">slash separator</link>' />

### Open redirect

#### Protocol-relative URL (//) <Badge severity="High" />

Protocol-relative URLs navigate to external domains. Blocked by `startsWith("//")` check.

<Vulnerability markup='<link href="//evil.com/phishing">protocol relative</link>' />

#### Backslash after slash (/\) <Badge severity="High" />

Browsers normalise `\` to `/`, making `/\evil.com` equivalent to `//evil.com`. The WHATWG URL parser
is used to verify that root-relative paths stay on the same origin after normalization — the same
parser the browser uses to resolve the `href`.

<Vulnerability markup='<link href="/\evil.com">backslash redirect</link>' />

#### Backslash with @ (/\@evil.com) <Badge severity="High" />

Combining backslash with userinfo syntax could trick naive string checks. The URL-parser origin
check catches this because the resolved URL no longer matches the sentinel origin.

<Vulnerability markup='<link href="/\@evil.com">backslash userinfo</link>' />

#### Relative path traversal <Badge severity="Medium" />

Relative paths (`./`, `../`) could be exploited to navigate outside the expected domain or bypass path-based security checks. Only absolute `https:` URLs, `mailto:`, root-relative `/path`, and `#fragment` are allowed.

<Vulnerability markup='<link href="../admin/secret">parent traversal</link>' />

<Vulnerability markup='<link href="./evil-page">dot relative</link>' />

#### Credential confusion (@) <Badge severity="Medium" />

In `https://good.com@evil.com`, the actual host is `evil.com`. URLs with username/password components are rejected.

<Vulnerability markup='<link href="https://good.com@evil.com">phishing link</link>' />

### SSRF: Internal network

#### Localhost IP <Badge severity="Medium" />

Numeric IPs, hex IPs, localhost, and `*.internal` hosts are blocked.

<Vulnerability markup='<link href="https://127.0.0.1/admin">localhost</link>' />

#### Cloud metadata endpoint <Badge severity="Medium" />

Prevents access to cloud instance metadata services.

<Vulnerability markup='<link href="https://169.254.169.254/latest/meta-data">AWS metadata</link>' />

#### IPv6 localhost <Badge severity="Medium" />

IPv6 loopback address blocked.

<Vulnerability markup='<link href="https://[::1]/">ipv6 localhost</link>' />

### Open redirect: WHATWG URL-parser normalization

The browser's WHATWG URL parser applies normalization (stripping tabs, newlines, resolving `\` to `/`)
that can turn an apparently-safe root-relative path into a cross-origin navigation. Rather than
maintaining an ever-growing list of regex patterns, the `internal` mode validates root-relative paths
by resolving them through the same URL parser the browser uses, then comparing the resolved origin
against a synthetic sentinel. If they differ, the path escapes same-origin and is blocked.

#### Tab in path (/\t/evil.com) <Badge severity="High" />

A literal tab character causes the WHATWG parser to strip it, turning `/[tab]/evil.com` into
`//evil.com` — a protocol-relative URL navigating to `evil.com`. Caught by both the control-character
check in base sanitisation and the URL-parser origin check.

<Vulnerability markup={'<link href="/\t/evil.com">tab bypass</link>'} />

#### Newline in path (/\n/evil.com) <Badge severity="High" />

Same class as tab — the parser strips the newline, producing `//evil.com`.

<Vulnerability markup={'<link href="/\n/evil.com">newline bypass</link>'} />

### DoS: Stack overflow

#### Deep nesting <Badge severity="High" />

The recursive parser enforces a `MAX_NESTING_DEPTH` limit (currently {MAX_NESTING_DEPTH}). Beyond that, tags are emitted as literal text.

<Vulnerability
  markup={
    '<important>'.repeat(MAX_NESTING_DEPTH + 20) +
    'deep' +
    '</important>'.repeat(MAX_NESTING_DEPTH + 20)
  }
/>

### DoS: Input length

#### Oversized input <Badge severity="Medium" />

Inputs exceeding `MAX_INPUT_LENGTH` ({MAX_INPUT_LENGTH} characters) are returned as a single
unprocessed text node. This prevents regex-based DoS on pathological inputs without silently
truncating content.

<Vulnerability markup={'<important>attack</important>' + 'x'.repeat(MAX_INPUT_LENGTH)} />

### accessibilityLabel abuse

#### Oversized aria-label (social engineering) <Badge severity="Low" />

The `accessibilityLabel` attribute is truncated to {MAX_ACCESSIBILITY_LABEL_LENGTH} characters.
This prevents attacker-controlled input from injecting arbitrarily long fake security messages
into the accessibility tree.

<Vulnerability
  markup={'<important accessibilityLabel="' + 'A'.repeat(300) + '">text</important>'}
/>

### Prototype pollution

#### action="\_\_proto\_\_" <Badge severity="Medium" />

Action values that collide with `Object.prototype` properties are rejected by the parser.
Without this, `actions?.['__proto__']` resolves to a truthy inherited value, rendering an unintended clickable link.

<Vulnerability markup='<link action="__proto__">click</link>' />

#### action="constructor" <Badge severity="Medium" />

`Object.prototype.constructor` is the `Object` function — truthy and callable. Blocked.

<Vulnerability markup='<link action="constructor">click</link>' />

### Attribute injection

#### Duplicate href (first wins) <Badge severity="Medium" />

When the same attribute appears twice, the first value is used. Previously the last won,
which could bypass content filters that only inspect the first occurrence.

<Vulnerability markup='<link href="/safe" href="javascript:alert(1)">duplicate href</link>' />

#### target="\_top" (iframe breakout) <Badge severity="Low" />

The `target` attribute is restricted to `_blank` and `_self`. Values like `_top` and `_parent` are stripped.

<Vulnerability markup='<link href="https://example.com" target="_top">escape iframe</link>' />

### Mailto abuse

#### Header injection (cc/bcc) <Badge severity="Medium" />

Mailto query parameters can inject additional recipients. Mailto URLs with query strings are blocked.

<Vulnerability markup='<link href="mailto:evil@evil.com?cc=victim@good.com&bcc=spy@evil.com">contact</link>' />

#### No recipient (social engineering) <Badge severity="Medium" />

Mailto URLs must have an actual address.

<Vulnerability markup='<link href="mailto:?subject=urgent&body=click%20here">empty mailto</link>' />
