From e29de131c8c8d452d0ad4627fc0d57b3498b636d Mon Sep 17 00:00:00 2001 From: 7w1 Date: Sat, 13 Jun 2026 20:39:27 -0500 Subject: [PATCH] formatting and tests and changeset --- .changeset/add-matrix-uri-support.md | 5 + src/app/components/RenderMessageContent.tsx | 4 +- src/app/plugins/matrix-uri.test.ts | 113 ++++++++++++++++++ src/app/plugins/matrix-uri.ts | 54 ++++----- .../plugins/react-custom-html-parser.test.tsx | 76 ++++++++++++ src/app/plugins/react-custom-html-parser.tsx | 11 +- src/app/utils/sanitize.test.ts | 16 ++- src/index.tsx | 2 + 8 files changed, 248 insertions(+), 33 deletions(-) create mode 100644 .changeset/add-matrix-uri-support.md create mode 100644 src/app/plugins/matrix-uri.test.ts diff --git a/.changeset/add-matrix-uri-support.md b/.changeset/add-matrix-uri-support.md new file mode 100644 index 000000000..178022af7 --- /dev/null +++ b/.changeset/add-matrix-uri-support.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Support rendering `matrix:` URIs in incoming messages. diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index e70a680ff..2c381924d 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -5,6 +5,7 @@ import { MsgType } from '$types/matrix-sdk'; import { parseSettingsLink } from '$features/settings/settingsLink'; import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { testMatrixTo } from '$plugins/matrix-to'; +import { testMatrixUri } from '$plugins/matrix-uri'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom, CaptionPosition } from '$state/settings'; import type { HTMLReactParserOptions } from 'html-react-parser'; @@ -137,7 +138,8 @@ function RenderMessageContentInternal({ const renderUrlsPreview = useCallback( (urls: string[]) => { const filteredUrls = urls.filter( - (url) => !testMatrixTo(url) && !parseSettingsLink(settingsLinkBaseUrl, url) + (url) => + !testMatrixTo(url) && !testMatrixUri(url) && !parseSettingsLink(settingsLinkBaseUrl, url) ); if (filteredUrls.length === 0) return undefined; diff --git a/src/app/plugins/matrix-uri.test.ts b/src/app/plugins/matrix-uri.test.ts new file mode 100644 index 000000000..29a0c236e --- /dev/null +++ b/src/app/plugins/matrix-uri.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from 'vitest'; +import { + isRedundantMatrixUriAnchorText, + matrixUriKey, + parseMatrixUri, + testMatrixUri, +} from './matrix-uri'; + +describe('parseMatrixUri', () => { + it('parses user URIs (u and legacy user)', () => { + expect(parseMatrixUri('matrix:u/alice:example.org')).toEqual({ + kind: 'user', + userId: '@alice:example.org', + }); + expect(parseMatrixUri('matrix:user/alice:example.org')).toEqual({ + kind: 'user', + userId: '@alice:example.org', + }); + }); + + it('ignores action and other query params for users', () => { + expect(parseMatrixUri('matrix:u/alice:example.org?action=chat')).toEqual({ + kind: 'user', + userId: '@alice:example.org', + }); + }); + + it('parses room alias URIs (r and legacy room)', () => { + expect(parseMatrixUri('matrix:r/somewhere:example.org')).toEqual({ + kind: 'room', + room: { roomIdOrAlias: '#somewhere:example.org', viaServers: undefined }, + }); + expect(parseMatrixUri('matrix:room/somewhere:example.org')).toEqual({ + kind: 'room', + room: { roomIdOrAlias: '#somewhere:example.org', viaServers: undefined }, + }); + }); + + it('parses room id URIs with via servers', () => { + expect(parseMatrixUri('matrix:roomid/somewhere:example.org?via=elsewhere.ca')).toEqual({ + kind: 'room', + room: { roomIdOrAlias: '!somewhere:example.org', viaServers: ['elsewhere.ca'] }, + }); + expect(parseMatrixUri('matrix:roomid/r:example.org?via=a.com&via=b.com')).toEqual({ + kind: 'room', + room: { roomIdOrAlias: '!r:example.org', viaServers: ['a.com', 'b.com'] }, + }); + }); + + it('parses event URIs under room id and alias', () => { + expect(parseMatrixUri('matrix:roomid/somewhere:example.org/e/event?via=elsewhere.ca')).toEqual({ + kind: 'event', + event: { + roomIdOrAlias: '!somewhere:example.org', + eventId: '$event', + viaServers: ['elsewhere.ca'], + }, + }); + expect(parseMatrixUri('matrix:r/somewhere:example.org/e/event')).toEqual({ + kind: 'event', + event: { roomIdOrAlias: '#somewhere:example.org', eventId: '$event', viaServers: undefined }, + }); + }); + + it('accepts the legacy event type qualifier', () => { + expect(parseMatrixUri('matrix:roomid/r:example.org/event/abc')).toEqual({ + kind: 'event', + event: { roomIdOrAlias: '!r:example.org', eventId: '$abc', viaServers: undefined }, + }); + }); + + it('handles an optional authority component', () => { + expect(parseMatrixUri('matrix://elsewhere.ca/r/somewhere:example.org')).toEqual({ + kind: 'room', + room: { roomIdOrAlias: '#somewhere:example.org', viaServers: undefined }, + }); + }); + + it('decodes percent-encoded segments', () => { + expect(parseMatrixUri('matrix:r/some%2Froom:example.org')).toEqual({ + kind: 'room', + room: { roomIdOrAlias: '#some/room:example.org', viaServers: undefined }, + }); + }); + + it('returns undefined for malformed or non-matrix URIs', () => { + expect(parseMatrixUri('https://matrix.to/#/@alice:example.org')).toBeUndefined(); + expect(parseMatrixUri('matrix:nonsense')).toBeUndefined(); + expect(parseMatrixUri('matrix:u/')).toBeUndefined(); + expect(parseMatrixUri('matrix:u/alice:example.org/extra')).toBeUndefined(); + expect(parseMatrixUri('matrix:roomid/r:example.org/x/abc')).toBeUndefined(); + expect(parseMatrixUri('not a uri')).toBeUndefined(); + }); +}); + +describe('testMatrixUri', () => { + it('returns true only for well-formed matrix URIs', () => { + expect(testMatrixUri('matrix:u/alice:example.org')).toBe(true); + expect(testMatrixUri('matrix:roomid/r:example.org/e/abc')).toBe(true); + expect(testMatrixUri('matrix:bogus')).toBe(false); + expect(testMatrixUri('https://example.com')).toBe(false); + }); +}); + +describe('matrixUriKey / isRedundantMatrixUriAnchorText', () => { + it('treats identical matrix URIs as redundant anchor text', () => { + const href = 'matrix:r/room:example.org'; + expect(matrixUriKey(href)).toBe('r:#room:example.org'); + expect(isRedundantMatrixUriAnchorText(href, 'matrix:r/room:example.org')).toBe(true); + expect(isRedundantMatrixUriAnchorText(href, '')).toBe(true); + expect(isRedundantMatrixUriAnchorText(href, 'a custom label')).toBe(false); + }); +}); diff --git a/src/app/plugins/matrix-uri.ts b/src/app/plugins/matrix-uri.ts index abce17307..011dbdcc0 100644 --- a/src/app/plugins/matrix-uri.ts +++ b/src/app/plugins/matrix-uri.ts @@ -1,5 +1,5 @@ -import { registerCustomProtocol } from "linkifyjs"; -import type { MatrixToRoom, MatrixToRoomEvent } from "./matrix-to"; +import { registerCustomProtocol } from 'linkifyjs'; +import type { MatrixToRoom, MatrixToRoomEvent } from './matrix-to'; /** * Parser for the `matrix:` URI scheme @@ -7,25 +7,25 @@ import type { MatrixToRoom, MatrixToRoomEvent } from "./matrix-to"; */ const SIGIL_BY_TYPE: Record = { - u: "@", - user: "@", - r: "#", - room: "#", - roomid: "!", - e: "$", - event: "$", + u: '@', + user: '@', + r: '#', + room: '#', + roomid: '!', + e: '$', + event: '$', }; -const isRoomType = (type: string): boolean => type === "r" || type === "room" || type === "roomid"; +const isRoomType = (type: string): boolean => type === 'r' || type === 'room' || type === 'roomid'; -const isEventType = (type: string): boolean => type === "e" || type === "event"; +const isEventType = (type: string): boolean => type === 'e' || type === 'event'; -const isUserType = (type: string): boolean => type === "u" || type === "user"; +const isUserType = (type: string): boolean => type === 'u' || type === 'user'; export type MatrixUriEntity = - | { kind: "user"; userId: string } - | { kind: "room"; room: MatrixToRoom } - | { kind: "event"; event: MatrixToRoomEvent }; + | { kind: 'user'; userId: string } + | { kind: 'room'; room: MatrixToRoom } + | { kind: 'event'; event: MatrixToRoomEvent }; const tryDecodeSegment = (segment: string): string => { try { @@ -46,12 +46,12 @@ export const parseMatrixUri = (href: string): MatrixUriEntity | undefined => { return undefined; } - if (url.protocol !== "matrix:") return undefined; + if (url.protocol !== 'matrix:') return undefined; - const path = url.pathname.replace(/^\/+/, ""); + const path = url.pathname.replace(/^\/+/, ''); if (!path) return undefined; - const rawSegments = path.split("/"); + const rawSegments = path.split('/'); if (rawSegments.length < 2) return undefined; const type1 = rawSegments[0]!.toLowerCase(); @@ -59,12 +59,12 @@ export const parseMatrixUri = (href: string): MatrixUriEntity | undefined => { const sigil1 = SIGIL_BY_TYPE[type1]; if (!sigil1 || !id1) return undefined; - const viaServers = url.searchParams.getAll("via"); + const viaServers = url.searchParams.getAll('via'); const via = viaServers.length > 0 ? viaServers : undefined; if (isUserType(type1)) { if (rawSegments.length > 2) return undefined; - return { kind: "user", userId: `${sigil1}${id1}` }; + return { kind: 'user', userId: `${sigil1}${id1}` }; } if (!isRoomType(type1)) return undefined; @@ -76,14 +76,14 @@ export const parseMatrixUri = (href: string): MatrixUriEntity | undefined => { const id2 = tryDecodeSegment(rawSegments[3]!); if (!isEventType(type2) || !id2) return undefined; return { - kind: "event", + kind: 'event', event: { roomIdOrAlias, eventId: `$${id2}`, viaServers: via }, }; } if (rawSegments.length !== 2) return undefined; - return { kind: "room", room: { roomIdOrAlias, viaServers: via } }; + return { kind: 'room', room: { roomIdOrAlias, viaServers: via } }; }; export const testMatrixUri = (href: string): boolean => parseMatrixUri(href) !== undefined; @@ -91,16 +91,16 @@ export const testMatrixUri = (href: string): boolean => parseMatrixUri(href) !== export const matrixUriKey = (href: string): string | undefined => { const entity = parseMatrixUri(href); if (!entity) return undefined; - if (entity.kind === "user") return `u:${entity.userId.toLowerCase()}`; - if (entity.kind === "room") return `r:${entity.room.roomIdOrAlias.toLowerCase()}`; + if (entity.kind === 'user') return `u:${entity.userId.toLowerCase()}`; + if (entity.kind === 'room') return `r:${entity.room.roomIdOrAlias.toLowerCase()}`; return `e:${entity.event.roomIdOrAlias.toLowerCase()}/${entity.event.eventId.toLowerCase()}`; }; export const isRedundantMatrixUriAnchorText = ( href: string, - anchorText: string | undefined, + anchorText: string | undefined ): boolean => { - if (anchorText == null || anchorText.trim() === "") return true; + if (anchorText == null || anchorText.trim() === '') return true; const keyHref = matrixUriKey(href); if (!keyHref) return false; const keyText = matrixUriKey(anchorText.trim()); @@ -113,7 +113,7 @@ let matrixProtocolRegistered = false; export const registerMatrixUriProtocol = (): void => { if (matrixProtocolRegistered) return; try { - registerCustomProtocol("matrix"); + registerCustomProtocol('matrix', true); matrixProtocolRegistered = true; } catch { matrixProtocolRegistered = true; diff --git a/src/app/plugins/react-custom-html-parser.test.tsx b/src/app/plugins/react-custom-html-parser.test.tsx index c29158224..17f929650 100644 --- a/src/app/plugins/react-custom-html-parser.test.tsx +++ b/src/app/plugins/react-custom-html-parser.test.tsx @@ -11,10 +11,15 @@ import { makeMentionCustomProps, renderMatrixMention, } from './react-custom-html-parser'; +import { registerMatrixUriProtocol } from './matrix-uri'; import { markdownToHtml } from './markdown/markdownToHtml'; const settingsLinkBaseUrl = 'https://app.example'; +// Ensure linkify recognizes `matrix:` URIs in plain text before any tokenization +// happens in this file. +registerMatrixUriProtocol(); + const { CodeHighlightRenderer } = vi.hoisted(() => ({ CodeHighlightRenderer: vi.fn< (props: { code: string; language?: string; allowDetect?: boolean }) => JSX.Element @@ -458,3 +463,74 @@ describe('react custom html parser', () => { expect(container.textContent).toContain('bullet'); }); }); + +describe('matrix: URI mentions', () => { + const roomMx = () => + createMatrixClient({ + getRoom: () => ({ roomId: '!room:example.org', name: 'Lobby' }), + getRooms: () => [], + }); + + it('renders a matrix: user URI in an html anchor as a mention pill', () => { + renderParsedHtml('bob', { sanitize: false }); + + const link = screen.getByRole('link', { name: '@bob' }); + expect(link).toHaveAttribute('data-mention-id', '@bob:example.org'); + expect(link.className).toContain(customHtmlCss.Mention({})); + }); + + it('keeps valid matrix: URIs through sanitization and renders them as mentions', () => { + renderParsedHtml('bob', { sanitize: true }); + + expect(screen.getByRole('link', { name: '@bob' })).toHaveAttribute( + 'data-mention-id', + '@bob:example.org' + ); + }); + + it('renders a matrix: room URI with via servers and falls back to the room name', () => { + renderParsedHtml( + 'matrix:roomid/room:example.org?via=elsewhere.ca', + { sanitize: false, mx: roomMx() } + ); + + const link = screen.getByRole('link', { name: '#Lobby' }); + expect(link).toHaveAttribute('data-mention-id', '!room:example.org'); + expect(link).toHaveAttribute('data-mention-via', 'elsewhere.ca'); + }); + + it('renders a matrix: event URI with the event id and message icon', () => { + renderParsedHtml('see this', { + sanitize: false, + mx: roomMx(), + }); + + const link = screen.getByRole('link', { name: 'see this' }); + expect(link).toHaveAttribute('data-mention-id', '!room:example.org'); + expect(link).toHaveAttribute('data-mention-event-id', '$event123'); + expect(link.className).toContain(customHtmlCss.MentionWithIcon); + }); + + it('autolinks bare matrix: URIs in plain text as mention pills', () => { + const mx = roomMx(); + const linkifyOpts = { + ...LINKIFY_OPTS, + render: factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + (href) => + renderMatrixMention(mx, '!room:example.com', href, makeMentionCustomProps(undefined)), + undefined + ), + }; + const parserOptions = getReactCustomHtmlParser(mx, '!room:example.com', { + settingsLinkBaseUrl, + linkifyOpts, + handleMentionClick: undefined, + }); + + render(
{parse('

see matrix:r/room:example.org now

', parserOptions)}
); + + const link = screen.getByRole('link', { name: '#Lobby' }); + expect(link).toHaveAttribute('data-mention-id', '!room:example.org'); + }); +}); diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index ca62195b3..139e45a82 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -50,7 +50,10 @@ export const LINKIFY_OPTS: LinkifyOpts = { rel: 'noreferrer noopener', }, validate: { - url: (value) => /^(https|http|ftp|mailto|magnet)?:/.test(value), + url: (value) => { + if (/^matrix:/i.test(value)) return testMatrixUri(value); + return /^(https|http|ftp|mailto|magnet)?:/.test(value); + }, }, ignoreTags: ['span'], }; @@ -305,7 +308,11 @@ export const factoryRenderLinkifyWithMention = ( const encodedHref = attributes.href; const decodedHref = encodedHref && safeDecodeUrl(encodedHref); - if (tagName === 'a' && decodedHref && (testMatrixTo(decodedHref) || testMatrixUri(decodedHref))) { + if ( + tagName === 'a' && + decodedHref && + (testMatrixTo(decodedHref) || testMatrixUri(decodedHref)) + ) { const mention = mentionRender(decodedHref); if (mention) return mention; } diff --git a/src/app/utils/sanitize.test.ts b/src/app/utils/sanitize.test.ts index 6df18dbb1..57fad523a 100644 --- a/src/app/utils/sanitize.test.ts +++ b/src/app/utils/sanitize.test.ts @@ -91,13 +91,23 @@ describe('sanitizeCustomHtml', () => { ); expect(sanitizeCustomHtml('relative')).toBe('relative'); - expect(sanitizeCustomHtml('matrix')).toBe( - 'matrix' - ); expect(sanitizeCustomHtml('bad')).toBe('bad'); expect(sanitizeCustomHtml('bad')).toBe('bad'); }); + it('keeps valid matrix: URIs but strips malformed ones', () => { + expect(sanitizeCustomHtml('matrix')).toContain( + 'href="matrix:u/alice:example.com"' + ); + expect( + sanitizeCustomHtml('matrix') + ).toContain('href="matrix:roomid/room:example.com/e/event"'); + + // Malformed matrix: URIs (unknown type, missing id) are dropped. + expect(sanitizeCustomHtml('bad')).toBe('bad'); + expect(sanitizeCustomHtml('bad')).toBe('bad'); + }); + it('keeps only mxc image sources and preserves custom-emote markers', () => { const allowed = sanitizeCustomHtml( 'blobcat' diff --git a/src/index.tsx b/src/index.tsx index 1721755d5..75b1eb7b3 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -23,9 +23,11 @@ import { getFallbackSession, MATRIX_SESSIONS_KEY, ACTIVE_SESSION_KEY } from './a import { createLogger } from './app/utils/debug'; import { getLocalStorageItem } from './app/state/utils/atomWithLocalStorage'; import { installConsolePasteScamWarning } from './app/utils/consolePasteScamWarning'; +import { registerMatrixUriProtocol } from './app/plugins/matrix-uri'; enableMapSet(); installConsolePasteScamWarning(); +registerMatrixUriProtocol(); const log = createLogger('index'); document.body.classList.add(configClass, varsClass);