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:
@@ -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.
|
||||
|
||||
|
||||
@@ -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'])
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
|
||||
|
||||
@@ -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
92
app/lib/urlGuard.test.ts
Normal 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.ly/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
46
app/lib/urlGuard.ts
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user