From a798bb1acb85f3e4639fb1cbf69a532e0e4515a5 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Mon, 2 Nov 2026 18:35:52 +0100 Subject: [PATCH] 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 --- README.md | 7 ++- app/lib/linkEmbeds.test.ts | 13 ++++++ app/lib/linkEmbeds.ts | 13 +++--- app/lib/markdown.ts | 8 +++- app/lib/urlGuard.test.ts | 92 ++++++++++++++++++++++++++++++++++++++ app/lib/urlGuard.ts | 46 +++++++++++++++++++ 6 files changed, 168 insertions(+), 11 deletions(-) create mode 100644 app/lib/urlGuard.test.ts create mode 100644 app/lib/urlGuard.ts diff --git a/README.md b/README.md index 81bdd6c..e2b5baa 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,8 @@ export default defineNuxtPlugin(() => { `linkify(escapedHtml)` (same module) turns the URLs of already-escaped text into links, and `embedRendererFor(url)` answers the registered component of a URL. +Links and cards are made only for honest URLs: `honestHttpUrl(raw)` (`app/lib/urlGuard.ts`) answers the parsed URL when the host as written is the host the browser opens, else null. A URL with a percent-escape, userinfo (`@`) or a backslash in its authority, an ideographic, fullwidth or halfwidth dot, fullwidth letters, an invisible character or a trailing dot in its host, or a scheme not followed by exactly two slashes stays text: no anchor in the message (`safeUrl`, used by `renderChatText`) and no card (`messageUrls`, `linkify`). A card therefore never shows a host the text does not. Honest URLs, IDN hosts written in Unicode, ports, queries and fragments link and embed as before. The guard covers rendering only; refusing banned links is the server's job. + ### Slash commands Typing `/` at the start of the composer opens the commands of `GET {botsApiBase}/commands`. Picking one, or sending any text that starts with `/`, calls `POST {botsApiBase}/dispatch` with `{input}` instead of posting a message. The answer shows under the conversation as a row only the sender sees, dismissable; an unknown command shows the refusal. @@ -197,7 +199,7 @@ Typing `/` at the start of the composer opens the commands of `GET {botsApiBase} | `ChatReactionBar`, `ChatStagingChips`, `ChatDeleteDialog`, `ChatMemberPicker`, `ChatMentionPopup`, `ChatCommandPicker`, `ChatLinkEmbed` | Parts of the above | | `ChatAvatar`, `ChatIcon`, `ChatNotices` | Initials avatar, stroke icons, short notices | -Composables: `useChat()` (the store, one per app, state in `useState` keys prefixed `chat:`), `useChatApi()` (the HTTP client bound to runtime config and the hook), `useChatNotice()`. The pure modules in `app/lib/` are imported explicitly, never auto-imported: `client.ts` (`createChatClient`, `ChatApiError`, `userIdFromToken`), `realtime.ts`, `linkEmbeds.ts`, `chatEvents.ts`, `chatFormat.ts`, `chatText.ts`, `chatUnread.ts`, `format.ts`, `attachments.ts`, `slots.ts` (`dmActionsTarget`, the DM-only rule of the conversation-actions slot). +Composables: `useChat()` (the store, one per app, state in `useState` keys prefixed `chat:`), `useChatApi()` (the HTTP client bound to runtime config and the hook), `useChatNotice()`. The pure modules in `app/lib/` are imported explicitly, never auto-imported: `client.ts` (`createChatClient`, `ChatApiError`, `userIdFromToken`), `realtime.ts`, `linkEmbeds.ts`, `urlGuard.ts` (`honestHttpUrl`), `chatEvents.ts`, `chatFormat.ts`, `chatText.ts`, `chatUnread.ts`, `format.ts`, `attachments.ts`, `slots.ts` (`dmActionsTarget`, the DM-only rule of the conversation-actions slot). ## Tokens @@ -229,7 +231,8 @@ pnpm test # vitest in Node: app/**/*.test.ts and tests/**/*.test. ``` - `app/lib/chatEvents.test.ts`, `chatFormat.test.ts`, `chatText.test.ts`, `chatUnread.test.ts` and `realtime.test.ts` are the Golem15 SPA's tests of the modules ported here, with only their import paths changed (`vitest.config.ts` maps the SPA's `@/api/http` to `tests/support/http.ts`). -- `app/lib/linkEmbeds.test.ts`: `linkify` (escaped input, http(s) only, `target` and `rel`), `messageUrls` and the renderer registry. +- `app/lib/linkEmbeds.test.ts`: `linkify` (escaped input, http(s) only, `target` and `rel`, deceptive hosts left as text), `messageUrls` (deceptive hosts skipped) and the renderer registry. +- `app/lib/urlGuard.test.ts`: `honestHttpUrl` on deceptive URLs (percent-escapes, fullwidth letters, ideographic and other dots, userinfo, backslashes, trailing dots, invisible characters, malformed scheme separators) and honest ones (ports, queries, fragments, IDN hosts in Unicode and punycode), and `renderChatText`, `safeUrl`, `messageUrls` and `linkify` on both. - `tests/client.test.ts`: every endpoint's URL, method and body, the 401 refresh-and-retry, `unauthorized`, the 422 mapping and the multipart upload. - `tests/store.test.ts`: `useChat` with stubbed Nuxt composables, a fake client and a fake realtime client: the bootstrap (and the anonymous, non-member and no-host cases), lazy channel joins, DMs, live messages and unread counts, threads, pins, reactions, slash commands, polling without realtime, `onUserEvent` and the DM-only `conversation-actions` rule. diff --git a/app/lib/linkEmbeds.test.ts b/app/lib/linkEmbeds.test.ts index b726bac..390cad2 100644 --- a/app/lib/linkEmbeds.test.ts +++ b/app/lib/linkEmbeds.test.ts @@ -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(' { expect(linkify('go to https://a.example/x.')).toBe(`go to https://a.example/x.`) expect(linkify('(https://a.example/x)')).toBe(`(https://a.example/x)`) @@ -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']) diff --git a/app/lib/linkEmbeds.ts b/app/lib/linkEmbeds.ts index 9cdd810..14514d2 100644 --- a/app/lib/linkEmbeds.ts +++ b/app/lib/linkEmbeds.ts @@ -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 { diff --git a/app/lib/markdown.ts b/app/lib/markdown.ts index 4eb7276..406807f 100644 --- a/app/lib/markdown.ts +++ b/app/lib/markdown.ts @@ -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 = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' } @@ -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 diff --git a/app/lib/urlGuard.test.ts b/app/lib/urlGuard.test.ts new file mode 100644 index 0000000..7a9decb --- /dev/null +++ b/app/lib/urlGuard.test.ts @@ -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(' { + 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() + }) +}) diff --git a/app/lib/urlGuard.ts b/app/lib/urlGuard.ts new file mode 100644 index 0000000..f2182cf --- /dev/null +++ b/app/lib/urlGuard.ts @@ -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 +}