mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 17:11:17 -08:00
Basic matrix uri support (#935)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> Support for rendering incoming matrix uri mentions/links/whatever, doesn't change sending at all, just adds support for rendering incoming ones. Fixes #718 #### Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [x] My code follows the style guidelines of this project - [x] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings ### AI disclosure: - [x] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. --> Tests were AI generated.
This commit is contained in:
9 files changed
+368
-13
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { registerCustomProtocol } from 'linkifyjs';
|
||||
import type { MatrixToRoom, MatrixToRoomEvent } from './matrix-to';
|
||||
|
||||
/**
|
||||
* Parser for the `matrix:` URI scheme
|
||||
* matrix:[//{authority}/]{type}/{id-without-sigil}[/{type}/{id}...][?{query}][#{fragment}]
|
||||
*/
|
||||
|
||||
const SIGIL_BY_TYPE: Record<string, string> = {
|
||||
u: '@',
|
||||
user: '@',
|
||||
r: '#',
|
||||
room: '#',
|
||||
roomid: '!',
|
||||
e: '$',
|
||||
event: '$',
|
||||
};
|
||||
|
||||
const isRoomType = (type: string): boolean => type === 'r' || type === 'room' || type === 'roomid';
|
||||
|
||||
const isEventType = (type: string): boolean => type === 'e' || type === 'event';
|
||||
|
||||
const isUserType = (type: string): boolean => type === 'u' || type === 'user';
|
||||
|
||||
export type MatrixUriEntity =
|
||||
| { kind: 'user'; userId: string }
|
||||
| { kind: 'room'; room: MatrixToRoom }
|
||||
| { kind: 'event'; event: MatrixToRoomEvent };
|
||||
|
||||
const tryDecodeSegment = (segment: string): string => {
|
||||
try {
|
||||
return decodeURIComponent(segment);
|
||||
} catch {
|
||||
return segment;
|
||||
}
|
||||
};
|
||||
|
||||
export const parseMatrixUri = (href: string): MatrixUriEntity | undefined => {
|
||||
const trimmed = href.trim();
|
||||
if (!/^matrix:/i.test(trimmed)) return undefined;
|
||||
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(trimmed);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (url.protocol !== 'matrix:') return undefined;
|
||||
|
||||
const path = url.pathname.replace(/^\/+/, '');
|
||||
if (!path) return undefined;
|
||||
|
||||
const rawSegments = path.split('/');
|
||||
if (rawSegments.length < 2) return undefined;
|
||||
|
||||
const type1 = rawSegments[0]!.toLowerCase();
|
||||
const id1 = tryDecodeSegment(rawSegments[1]!);
|
||||
const sigil1 = SIGIL_BY_TYPE[type1];
|
||||
if (!sigil1 || !id1) return undefined;
|
||||
|
||||
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}` };
|
||||
}
|
||||
|
||||
if (!isRoomType(type1)) return undefined;
|
||||
|
||||
const roomIdOrAlias = `${sigil1}${id1}`;
|
||||
|
||||
if (rawSegments.length >= 4) {
|
||||
const type2 = rawSegments[2]!.toLowerCase();
|
||||
const id2 = tryDecodeSegment(rawSegments[3]!);
|
||||
if (!isEventType(type2) || !id2) return undefined;
|
||||
return {
|
||||
kind: 'event',
|
||||
event: { roomIdOrAlias, eventId: `$${id2}`, viaServers: via },
|
||||
};
|
||||
}
|
||||
|
||||
if (rawSegments.length !== 2) return undefined;
|
||||
|
||||
return { kind: 'room', room: { roomIdOrAlias, viaServers: via } };
|
||||
};
|
||||
|
||||
export const testMatrixUri = (href: string): boolean => parseMatrixUri(href) !== undefined;
|
||||
|
||||
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()}`;
|
||||
return `e:${entity.event.roomIdOrAlias.toLowerCase()}/${entity.event.eventId.toLowerCase()}`;
|
||||
};
|
||||
|
||||
export const isRedundantMatrixUriAnchorText = (
|
||||
href: string,
|
||||
anchorText: string | undefined
|
||||
): boolean => {
|
||||
if (anchorText == null || anchorText.trim() === '') return true;
|
||||
const keyHref = matrixUriKey(href);
|
||||
if (!keyHref) return false;
|
||||
const keyText = matrixUriKey(anchorText.trim());
|
||||
if (!keyText) return false;
|
||||
return keyHref === keyText;
|
||||
};
|
||||
|
||||
let matrixProtocolRegistered = false;
|
||||
|
||||
export const registerMatrixUriProtocol = (): void => {
|
||||
if (matrixProtocolRegistered) return;
|
||||
try {
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
parseMatrixToUser,
|
||||
testMatrixTo,
|
||||
} from './matrix-to';
|
||||
import { isRedundantMatrixUriAnchorText, parseMatrixUri, testMatrixUri } from './matrix-uri';
|
||||
import { getHexcodeForEmoji, getShortcodeFor } from './emoji';
|
||||
|
||||
const EMOJI_REG_G = new RegExp(`${URL_NEG_LB}(${EMOJI_PATTERN})`, 'g');
|
||||
@@ -49,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'],
|
||||
};
|
||||
@@ -156,7 +160,10 @@ const matrixPermalinkDisplayLabel = (
|
||||
): ReactNode => {
|
||||
if (customChildren === undefined || customChildren === null) return fallback;
|
||||
if (typeof customChildren === 'string') {
|
||||
return isRedundantMatrixToAnchorText(href, customChildren) ? fallback : customChildren;
|
||||
const redundant =
|
||||
isRedundantMatrixToAnchorText(href, customChildren) ||
|
||||
isRedundantMatrixUriAnchorText(href, customChildren);
|
||||
return redundant ? fallback : customChildren;
|
||||
}
|
||||
return customChildren;
|
||||
};
|
||||
@@ -168,7 +175,10 @@ export const renderMatrixMention = (
|
||||
customProps: ComponentPropsWithoutRef<'a'>,
|
||||
nicknames?: Nicknames
|
||||
) => {
|
||||
const userId = parseMatrixToUser(href);
|
||||
const matrixUri = parseMatrixUri(href);
|
||||
|
||||
const userId =
|
||||
parseMatrixToUser(href) ?? (matrixUri?.kind === 'user' ? matrixUri.userId : undefined);
|
||||
if (userId) {
|
||||
const currentRoom = mx.getRoom(currentRoomId);
|
||||
|
||||
@@ -187,7 +197,8 @@ export const renderMatrixMention = (
|
||||
);
|
||||
}
|
||||
|
||||
const matrixToRoom = parseMatrixToRoom(href);
|
||||
const matrixToRoom =
|
||||
parseMatrixToRoom(href) ?? (matrixUri?.kind === 'room' ? matrixUri.room : undefined);
|
||||
if (matrixToRoom) {
|
||||
const { roomIdOrAlias, viaServers } = matrixToRoom;
|
||||
const mentionRoom = mx.getRoom(
|
||||
@@ -212,7 +223,8 @@ export const renderMatrixMention = (
|
||||
);
|
||||
}
|
||||
|
||||
const matrixToRoomEvent = parseMatrixToRoomEvent(href);
|
||||
const matrixToRoomEvent =
|
||||
parseMatrixToRoomEvent(href) ?? (matrixUri?.kind === 'event' ? matrixUri.event : undefined);
|
||||
if (matrixToRoomEvent) {
|
||||
const { roomIdOrAlias, eventId, viaServers } = matrixToRoomEvent;
|
||||
const mentionRoom = mx.getRoom(
|
||||
@@ -296,7 +308,11 @@ export const factoryRenderLinkifyWithMention = (
|
||||
const encodedHref = attributes.href;
|
||||
const decodedHref = encodedHref && safeDecodeUrl(encodedHref);
|
||||
|
||||
if (tagName === 'a' && decodedHref && testMatrixTo(decodedHref)) {
|
||||
if (
|
||||
tagName === 'a' &&
|
||||
decodedHref &&
|
||||
(testMatrixTo(decodedHref) || testMatrixUri(decodedHref))
|
||||
) {
|
||||
const mention = mentionRender(decodedHref);
|
||||
if (mention) return mention;
|
||||
}
|
||||
@@ -727,7 +743,7 @@ export const getReactCustomHtmlParser = (
|
||||
? undefined
|
||||
: children.map((c) => (c instanceof DOMText ? c.data : '')).join();
|
||||
|
||||
if (decodedHref && testMatrixTo(decodedHref)) {
|
||||
if (decodedHref && (testMatrixTo(decodedHref) || testMatrixUri(decodedHref))) {
|
||||
const mention = renderMatrixMention(
|
||||
mx,
|
||||
roomId,
|
||||
|
||||
@@ -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" />'
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import DOMPurify from 'dompurify';
|
||||
import { isMatrixHexColor } from './matrixHtml';
|
||||
import { testMatrixUri } from '../plugins/matrix-uri';
|
||||
|
||||
const MAX_TAG_NESTING = 100;
|
||||
const INTERNAL_IMG_SRC_ATTR = 'data-sable-img-src';
|
||||
@@ -77,7 +78,7 @@ const forbiddenContentTags = ['mx-reply', 'script', 'style', 'textarea', 'option
|
||||
|
||||
const codeLanguageClassRegex = /^language-[A-Za-z0-9_-]+$/;
|
||||
const orderedListStartRegex = /^-?\d+$/;
|
||||
const allowedUriRegex = /^(?:https?|ftp|mailto|magnet|mxc):/i;
|
||||
const allowedUriRegex = /^(?:https?|ftp|mailto|magnet|mxc|matrix):/i;
|
||||
|
||||
export function sanitizeText(body: string): string {
|
||||
const tagsToReplace: Record<string, string> = {
|
||||
@@ -107,6 +108,10 @@ function isAllowedAbsoluteLink(value: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function isAllowedMatrixUri(value: string): boolean {
|
||||
return testMatrixUri(value);
|
||||
}
|
||||
|
||||
function isAllowedMxcUri(value: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
@@ -152,7 +157,12 @@ function getValidatedAttributeValue(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (tagName === 'a' && attrName === 'href' && !isAllowedAbsoluteLink(attrValue)) {
|
||||
if (
|
||||
tagName === 'a' &&
|
||||
attrName === 'href' &&
|
||||
!isAllowedAbsoluteLink(attrValue) &&
|
||||
!isAllowedMatrixUri(attrValue)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -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