Files
vue-chat-layer/app/lib/markdown.ts
Jakub Zych a798bb1acb fix: deceptive link hosts render as text, not links or cards
- urlGuard: honestHttpUrl answers an http(s) URL only when its written
  host is the host the browser opens: no percent-escape, userinfo or
  backslash in the authority, no ideographic, fullwidth or halfwidth dot,
  fullwidth letter, invisible character or trailing dot in the host, and
  exactly two slashes after the scheme; IDN hosts in Unicode pass
- safeUrl allows an http(s) target only through honestHttpUrl, so
  renderChatText leaves a deceptive URL as text, bare or labelled
- linkify and messageUrls parse through it, so no card shows a host the
  text does not
- tests: urlGuard.test.ts and linkEmbeds cases; the SPA's copied tests
  are unchanged
2026-11-02 18:35:52 +01:00

37 lines
1.6 KiB
TypeScript

// HTML helpers of the chat text renderer (chatText.ts), ported from a
// Golem15 SPA's markdown.ts: escaping, the link-target allow-list and
// bold/italic on escaped text.
//
// Links must be http(s), mailto, a site path or an anchor; anything else
// (javascript:, data:, ...) is refused. An http(s) target must also pass
// honestHttpUrl (urlGuard.ts): its written host is the host it opens.
import { honestHttpUrl } from './urlGuard'
const ESC: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
export function escapeHtml(s: string): string {
return s.replace(/[&<>"']/g, (c) => ESC[c])
}
/** Returns the URL when it is allowed as a link target, else null. */
export function safeUrl(raw: string): string | null {
// Strip whitespace and control characters browsers ignore inside schemes.
// eslint-disable-next-line no-control-regex
const url = raw.trim().replace(/[\u0000-\u001f\u007f\s]+/g, '')
if (/^https?:/i.test(url)) return honestHttpUrl(url) ? url : null
if (/^mailto:[^\s]+$/i.test(url)) return url
// A site path: a "/" not followed by another "/" or a backslash (browsers
// read "/\host" as "//host", an external link).
if (/^\/(?![/\\])/.test(url) || url.startsWith('#')) return url
return null
}
/** Bold and italic on already-escaped text (shared with the chat renderer). */
export function formatSpans(escaped: string): string {
return escaped
.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|[\s(])\*([^*\n]+)\*(?=$|[\s).,;:!?])/g, '$1<em>$2</em>')
.replace(/(^|[\s(])_([^_\n]+)_(?=$|[\s).,;:!?])/g, '$1<em>$2</em>')
}