@humanspeak/svelte-markdown
Version:
Markdown and HTML renderer for Svelte 5 — built for rendering streaming AI agent output from Claude Code, ChatGPT, and agentic workflows. XSS-safe defaults, streaming-aware sanitization, token caching, TypeScript types, and Svelte 5 runes.
70 lines (69 loc) • 2.64 kB
TypeScript
/**
* URL and HTML attribute sanitization utilities for XSS prevention.
*
* These functions are applied in the Parser before tokens reach any
* renderer component or snippet, ensuring custom renderers cannot
* bypass sanitization.
*
* @see https://github.com/humanspeak/svelte-markdown/issues/272
* @packageDocumentation
*/
/**
* Context passed to sanitization functions so users can apply
* different rules per markdown token type or HTML tag.
*
* - For markdown links: `{ type: 'link', tag: 'a' }`
* - For markdown images: `{ type: 'image', tag: 'img' }`
* - For HTML tags: `{ type: 'html', tag: 'a' | 'img' | 'div' | ... }`
*/
export interface SanitizeContext {
/** The markdown token type. */
type: 'link' | 'image' | 'html';
/** The HTML tag name being rendered (e.g. `'a'`, `'img'`, `'div'`). */
tag: string;
}
export type SanitizeUrlFn = (_url: string, _context: SanitizeContext) => string;
export type SanitizeAttributesFn = (_attributes: Record<string, string>, _context: SanitizeContext, _sanitizeUrl: SanitizeUrlFn) => Record<string, string>;
/**
* Sanitizes a URL against a protocol allowlist.
*
* Allows `http:`, `https:`, `mailto:`, `tel:`, and relative URLs
* (starting with `/`, `#`, `?`, or no protocol). Blocks everything
* else including `javascript:`, `data:`, `vbscript:`, etc.
*
* Handles mixed-case protocols and leading whitespace.
*
* The `context` parameter provides the token type and HTML tag name,
* enabling per-element policies in custom overrides.
*/
export declare const defaultSanitizeUrl: (url: string, _context: SanitizeContext) => string;
/**
* Passthrough URL sanitizer that allows all URLs unchanged.
*
* Use this to disable URL sanitization entirely:
* ```svelte
* <SvelteMarkdown source={markdown} sanitizeUrl={unsanitizedUrl} />
* ```
*/
export declare const unsanitizedUrl: SanitizeUrlFn;
/**
* Passthrough attribute sanitizer that allows all attributes unchanged.
*
* Use this to disable attribute sanitization entirely:
* ```svelte
* <SvelteMarkdown source={markdown} sanitizeAttributes={unsanitizedAttributes} />
* ```
*/
export declare const unsanitizedAttributes: SanitizeAttributesFn;
/**
* Sanitizes an HTML attribute object by:
* 1. Removing all event handler attributes (`on*`)
* 2. Running URL-bearing attributes through the sanitizer
*
* The `context` parameter provides the HTML tag name, enabling
* per-element policies in custom overrides (e.g. stricter rules
* for `<iframe>` than `<a>`).
*
* Returns a new object; does not mutate the input.
*/
export declare const defaultSanitizeAttributes: SanitizeAttributesFn;