// 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(' { expect(messageUrls(`look ${raw} now`)).toEqual([]) expect(messageUrls(`[click](${raw})`)).toEqual([]) expect(linkify(escapeHtml(`look ${raw} now`))).not.toContain(' { expect(renderChatText(`look ${raw} now`)).toContain(` 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() }) })