mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-26 03:46:25 -08:00
formatting and tests and changeset
This commit is contained in:
1 parent
c9c3bf318c
commit
e29de131c8
8 files changed
+248
-33
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Support rendering `matrix:` URIs in incoming messages.
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<string, string> = {
|
||||
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;
|
||||
|
||||
@@ -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('<a href="matrix:u/bob:example.org">bob</a>', { 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('<a href="matrix:u/bob:example.org">bob</a>', { 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(
|
||||
'<a href="matrix:roomid/room:example.org?via=elsewhere.ca">matrix:roomid/room:example.org?via=elsewhere.ca</a>',
|
||||
{ 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('<a href="matrix:roomid/room:example.org/e/event123">see this</a>', {
|
||||
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(<div>{parse('<p>see matrix:r/room:example.org now</p>', parserOptions)}</div>);
|
||||
|
||||
const link = screen.getByRole('link', { name: '#Lobby' });
|
||||
expect(link).toHaveAttribute('data-mention-id', '!room:example.org');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -91,13 +91,23 @@ describe('sanitizeCustomHtml', () => {
|
||||
);
|
||||
|
||||
expect(sanitizeCustomHtml('<a href="/relative">relative</a>')).toBe('<a>relative</a>');
|
||||
expect(sanitizeCustomHtml('<a href="matrix:u/alice:example.com">matrix</a>')).toBe(
|
||||
'<a>matrix</a>'
|
||||
);
|
||||
expect(sanitizeCustomHtml('<a href="javascript:alert(1)">bad</a>')).toBe('<a>bad</a>');
|
||||
expect(sanitizeCustomHtml('<a href="vbscript:msgbox(1)">bad</a>')).toBe('<a>bad</a>');
|
||||
});
|
||||
|
||||
it('keeps valid matrix: URIs but strips malformed ones', () => {
|
||||
expect(sanitizeCustomHtml('<a href="matrix:u/alice:example.com">matrix</a>')).toContain(
|
||||
'href="matrix:u/alice:example.com"'
|
||||
);
|
||||
expect(
|
||||
sanitizeCustomHtml('<a href="matrix:roomid/room:example.com/e/event">matrix</a>')
|
||||
).toContain('href="matrix:roomid/room:example.com/e/event"');
|
||||
|
||||
// Malformed matrix: URIs (unknown type, missing id) are dropped.
|
||||
expect(sanitizeCustomHtml('<a href="matrix:nonsense">bad</a>')).toBe('<a>bad</a>');
|
||||
expect(sanitizeCustomHtml('<a href="matrix:u/">bad</a>')).toBe('<a>bad</a>');
|
||||
});
|
||||
|
||||
it('keeps only mxc image sources and preserves custom-emote markers', () => {
|
||||
const allowed = sanitizeCustomHtml(
|
||||
'<img data-mx-emoticon src="mxc://example.com/abc123" alt="blobcat" title="blobcat" height="32" />'
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user