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
This commit is contained in:
Jakub Zych
2026-11-02 18:35:52 +01:00
parent b6d3389e46
commit a798bb1acb
6 changed files with 168 additions and 11 deletions

View File

@@ -18,6 +18,14 @@ describe('linkify', () => {
}
})
it('leaves deceptive hosts as text and links honest ones', () => {
for (const s of ['https://example.com@bit.ly/', 'https://bit。ly/x']) {
expect(linkify(escapeHtml(s))).toBe(escapeHtml(s))
}
expect(linkify('https://ok.example:8443/a?b=c#d')).toContain('<a href="https://ok.example:8443/a?b=c#d"')
expect(linkify('https://żółw.example/')).toContain('<a href="https://żółw.example/"')
})
it('keeps trailing punctuation outside the link', () => {
expect(linkify('go to https://a.example/x.')).toBe(`go to <a href="https://a.example/x" ${EXTERNAL}>https://a.example/x</a>.`)
expect(linkify('(https://a.example/x)')).toBe(`(<a href="https://a.example/x" ${EXTERNAL}>https://a.example/x</a>)`)
@@ -65,6 +73,11 @@ describe('messageUrls', () => {
expect(messageUrls('xhttps://a.example user@https://b.example')).toEqual([])
})
it('skips URLs whose written host is not the host they open', () => {
const text = 'a https://bit%2Ely/x b https://ok.example/1 c https://bit.ly/x d https://żółw.example/'
expect(messageUrls(text).map((u) => u.host)).toEqual(['ok.example', 'xn--w-uga1v8h.example'])
})
it('gives the cards limits.max_embeds takes the first of', () => {
const urls = messageUrls('https://1.example https://2.example https://3.example https://4.example')
expect(urls.slice(0, 3).map((u) => u.host)).toEqual(['1.example', '2.example', '3.example'])

View File

@@ -9,8 +9,12 @@
//
// The component gets the URL as the `url` prop (a URL object). The first
// registered renderer that matches wins; ChatLinkEmbed is the fallback.
//
// Only honest URLs (urlGuard.ts: the written host is the host the browser
// opens) become links or cards; a deceptive one stays text.
import type { Component } from 'vue'
import { escapeHtml } from './markdown'
import { honestHttpUrl } from './urlGuard'
const EXTERNAL = ' target="_blank" rel="noopener noreferrer nofollow"'
@@ -36,14 +40,9 @@ function splitUrl(raw: string): { url: string; rest: string } {
return { url, rest: raw.slice(url.length) }
}
/** The URL when it parses as http(s), else null. */
/** The URL when it is an honest http(s) URL (honestHttpUrl), else null. */
function parseHttp(raw: string): URL | null {
try {
const u = new URL(raw)
return u.protocol === 'http:' || u.protocol === 'https:' ? u : null
} catch {
return null
}
return honestHttpUrl(raw)
}
function unescapeHtml(s: string): string {

View File

@@ -3,7 +3,10 @@
// bold/italic on escaped text.
//
// Links must be http(s), mailto, a site path or an anchor; anything else
// (javascript:, data:, ...) is refused.
// (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;' }
@@ -16,7 +19,8 @@ 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) || /^mailto:[^\s]+$/i.test(url)) return url
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

92
app/lib/urlGuard.test.ts Normal file
View File

@@ -0,0 +1,92 @@
// The chat's link guard: URLs whose written host is not the host the
// browser opens stay text, in renderChatText, linkify and messageUrls;
// honest URLs (IDN hosts in Unicode, ports, queries, fragments) still link.
import { describe, expect, it } from 'vitest'
import { renderChatText } from './chatText'
import { linkify, messageUrls } from './linkEmbeds'
import { escapeHtml, safeUrl } from './markdown'
import { honestHttpUrl } from './urlGuard'
const DECEPTIVE = [
'https://bit%2Ely/x',
'https://bit.l%79/x',
'https://bit.ly/x',
'https://bit。ly/x',
'https://bit.ly/x',
'https://bit。ly/x',
'https://user@bit.ly/x',
'https://example.com@bit.ly/',
'https:/\\bit.ly/x',
'https://\\bit.ly/x',
'https://bit.ly./x',
'https:///bit.ly/x',
'https:bit.ly/x',
'https://bit.l­y/x',
'https://bit​.ly/x',
'https://0x7f.1/x',
]
const HONEST = [
'https://bit.ly/x',
'http://example.com:8080/a?b=c#d',
'https://żółw.example/',
'https://xn--w-uga1v8h.example/',
'https://sub.example.org/path',
'https://Example.COM/Path',
'https://medium.example/@ada/post',
'https://a.example/?next=https://b.example/%2E',
]
describe('honestHttpUrl', () => {
it.each(DECEPTIVE)('refuses %s', (raw) => {
expect(honestHttpUrl(raw)).toBeNull()
})
it('refuses other schemes and what the parser cannot read', () => {
for (const raw of ['javascript:alert(1)', 'data:text/html,hi', 'mailto:a@b.example', 'ftp://a.example/', 'https://', 'https://exa mple.com/', '//bit.ly/x', '/x', '']) {
expect(honestHttpUrl(raw)).toBeNull()
}
})
it.each(HONEST)('accepts %s', (raw) => {
const url = honestHttpUrl(raw)
expect(url).not.toBeNull()
expect(url!.href).toBe(new URL(raw).href)
})
it('answers the parsed URL, IDN hosts in their ASCII form', () => {
expect(honestHttpUrl('https://żółw.example/a')!.hostname).toBe('xn--w-uga1v8h.example')
expect(honestHttpUrl('http://example.com:8080/a?b=c#d')!.port).toBe('8080')
})
})
describe('the chat renderer with the guard', () => {
it.each(DECEPTIVE)('%s stays text, bare and as a [label](url) link', (raw) => {
const bare = renderChatText(`look ${raw} now`)
expect(bare).not.toContain('<a')
expect(bare).toContain(escapeHtml(raw))
const labelled = renderChatText(`[click](${raw})`)
expect(labelled).not.toContain('<a')
expect(labelled).toContain('click')
expect(safeUrl(raw)).toBeNull()
})
it.each(DECEPTIVE)('%s yields no card and no linkify link', (raw) => {
expect(messageUrls(`look ${raw} now`)).toEqual([])
expect(messageUrls(`[click](${raw})`)).toEqual([])
expect(linkify(escapeHtml(`look ${raw} now`))).not.toContain('<a')
})
it.each(HONEST)('%s still links and yields a card', (raw) => {
expect(renderChatText(`look ${raw} now`)).toContain(`<a href="${escapeHtml(raw)}"`)
expect(renderChatText(`[click](${raw})`)).toContain(`<a href="${escapeHtml(raw)}"`)
expect(messageUrls(`look ${raw} now`).map((u) => u.href)).toEqual([new URL(raw).href])
})
it('keeps mailto, site paths and anchors', () => {
expect(safeUrl('mailto:ada@example.com')).toBe('mailto:ada@example.com')
expect(safeUrl('/chat')).toBe('/chat')
expect(safeUrl('#top')).toBe('#top')
expect(safeUrl('/\\bit.ly')).toBeNull()
})
})

46
app/lib/urlGuard.ts Normal file
View File

@@ -0,0 +1,46 @@
// The chat's guard for http(s) link targets.
//
// The chat links and embeds only URLs whose host, as written, is the host
// the browser opens. The URL parser percent-decodes the host, maps
// fullwidth letters and ideographic dots to ASCII, drops userinfo and reads
// a backslash as a slash, so "https://bit%2Ely/x" or "https://bit.ly/x"
// opens bit.ly although the text shows something else. Such a URL stays
// text: no anchor, and no link card, so a card never shows a host the text
// does not. Honest URLs, IDN hosts written in Unicode, ports, queries and
// fragments pass.
/** The written scheme: http or https, followed by exactly two slashes. */
const SCHEME_RE = /^https?:\/\/(?![/\\])/i
/** Ideographic, fullwidth and halfwidth full stops (URL parsers read them as "."). */
const ODD_DOTS_RE = /[。.。]/
/** Characters the URL parser drops from a host (soft hyphen, zero-width space and the like). */
const INVISIBLE_RE = /[\p{Default_Ignorable_Code_Point}\p{Cf}]/u
// eslint-disable-next-line no-control-regex
const NON_ASCII_RE = /[^\u0000-\u007f]/
/**
* honestHttpUrl answers the parsed URL when `raw` is an http(s) URL whose
* written host is the host it opens, else null. The authority as written
* (up to the first "/", "?" or "#") holds no "%", "@" or "\"; the host holds
* no ideographic, fullwidth or halfwidth dot and no invisible character the
* parser drops, is unchanged by NFKC and does not end with a dot; and its lower-cased form is the parsed hostname, or,
* for a host with non-ASCII letters, it is in NFC.
*/
export function honestHttpUrl(raw: string): URL | null {
if (!SCHEME_RE.test(raw)) return null
let url: URL
try {
url = new URL(raw)
} catch {
return null
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
const rest = raw.slice(raw.indexOf('//') + 2)
const authority = /^[^/?#]*/.exec(rest)?.[0] ?? ''
if (/[%@\\]/.test(authority)) return null
const host = authority.startsWith('[') ? authority.slice(0, authority.indexOf(']') + 1) : authority.replace(/:\d*$/, '')
if (!host || ODD_DOTS_RE.test(host) || INVISIBLE_RE.test(host) || host.normalize('NFKC') !== host || host.endsWith('.')) return null
if (host.toLowerCase() === url.hostname) return url
if (NON_ASCII_RE.test(host) && host.normalize('NFC') === host) return url
return null
}