From 4dbdb6fcc9a54e66a2b1e7fa5b219d7258eabcc3 Mon Sep 17 00:00:00 2001 From: hazre Date: Sat, 18 Apr 2026 18:27:16 +0200 Subject: [PATCH] Harden settings link parsing and rendering --- .../components/RenderMessageContent.test.tsx | 20 ++ .../features/settings/settingsLink.test.ts | 78 ++++++ src/app/features/settings/settingsLink.ts | 257 +++++++++++++++++- .../plugins/react-custom-html-parser.test.tsx | 49 +++- src/app/plugins/react-custom-html-parser.tsx | 58 +--- src/app/styles/CustomHtml.css.ts | 1 + 6 files changed, 402 insertions(+), 61 deletions(-) diff --git a/src/app/components/RenderMessageContent.test.tsx b/src/app/components/RenderMessageContent.test.tsx index 789b84469..191fa23b4 100644 --- a/src/app/components/RenderMessageContent.test.tsx +++ b/src/app/components/RenderMessageContent.test.tsx @@ -55,4 +55,24 @@ describe('RenderMessageContent', () => { expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com'); }); + + it('still renders url previews for malformed settings-looking links', () => { + renderMessage( + 'https://app.example/settings/account?focus=status&moe.sable.client.action=settings">Settings' + ); + + expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); + expect(screen.getByTestId('url-preview-card')).toHaveTextContent( + 'https://app.example/settings/account?focus=status&moe.sable.client.action=settings">Settings' + ); + }); + + it('still renders url previews for settings links with unknown focus ids', () => { + renderMessage('https://app.example/settings/account?focus=display-name2'); + + expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); + expect(screen.getByTestId('url-preview-card')).toHaveTextContent( + 'https://app.example/settings/account?focus=display-name2' + ); + }); }); diff --git a/src/app/features/settings/settingsLink.test.ts b/src/app/features/settings/settingsLink.test.ts index f47c53c10..37b1e9921 100644 --- a/src/app/features/settings/settingsLink.test.ts +++ b/src/app/features/settings/settingsLink.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from 'vitest'; import { buildSettingsLink, + getSettingsLinkLabel, + normalizeSettingsFocusId, parseSettingsLink, SETTINGS_LINK_ACTION_PARAM, SETTINGS_LINK_ACTION_SETTINGS, @@ -32,6 +34,12 @@ describe('settingsLink', () => { 'https://app.example/settings/appearance/?focus=message-link-preview' ) ).toEqual({ section: 'appearance', focus: 'message-link-preview' }); + expect( + parseSettingsLink( + 'https://app.example', + 'https://app.example/settings/account?focus=display-name&moe.sable.client.action=settings&hello=world' + ) + ).toEqual({ section: 'account', focus: 'display-name' }); expect(parseSettingsLink('https://app.example', 'https://app.example/home/')).toBeUndefined(); }); @@ -50,6 +58,12 @@ describe('settingsLink', () => { `https://other.example/#/client/settings/account?focus=status&${SETTINGS_LINK_ACTION_PARAM}=${SETTINGS_LINK_ACTION_SETTINGS}` ) ).toEqual({ section: 'account', focus: 'status' }); + expect( + parseSettingsLink( + 'https://app.example', + `https://other.example/settings/account?focus=status&${SETTINGS_LINK_ACTION_PARAM}=${SETTINGS_LINK_ACTION_SETTINGS}&hello=world` + ) + ).toEqual({ section: 'account', focus: 'status' }); expect( parseSettingsLink('https://app.example', 'https://other.example/settings/appearance') @@ -86,8 +100,72 @@ describe('settingsLink', () => { ).toBeUndefined(); }); + it('rejects settings links with malformed focus ids', () => { + expect( + parseSettingsLink( + 'https://app.example', + 'https://app.example/settings/account?focus=display-name%22%3ESettings' + ) + ).toBeUndefined(); + expect( + parseSettingsLink( + 'https://app.example', + `https://other.example/settings/account?focus=display-name%22%3ESettings&${SETTINGS_LINK_ACTION_PARAM}=${SETTINGS_LINK_ACTION_SETTINGS}` + ) + ).toBeUndefined(); + }); + + it('rejects settings links with unknown focus ids', () => { + expect( + parseSettingsLink( + 'https://app.example', + 'https://app.example/settings/account?focus=display-name2' + ) + ).toBeUndefined(); + expect( + parseSettingsLink( + 'https://app.example', + `https://other.example/settings/account?focus=display-name2&${SETTINGS_LINK_ACTION_PARAM}=${SETTINGS_LINK_ACTION_SETTINGS}` + ) + ).toBeUndefined(); + }); + + it('rejects settings links with malformed query params', () => { + expect( + parseSettingsLink( + 'https://app.example', + 'https://app.example/settings/account?focus=status&moe.sable.client.action=settings%22%3ESettings' + ) + ).toBeUndefined(); + expect( + parseSettingsLink( + 'https://app.example', + 'https://app.example/settings/account?focus=status&hello=world%22%3ESettings' + ) + ).toBeUndefined(); + expect( + parseSettingsLink( + 'https://app.example', + `https://other.example/settings/account?focus=status&hello=world%22%3ESettings&${SETTINGS_LINK_ACTION_PARAM}=${SETTINGS_LINK_ACTION_SETTINGS}` + ) + ).toBeUndefined(); + }); + it('normalizes focus id parts', () => { expect(toSettingsFocusIdPart('@alice:example.org')).toBe('alice-example-org'); expect(toSettingsFocusIdPart('DEVICE-123')).toBe('device-123'); }); + + it('accepts only valid settings focus ids', () => { + expect(normalizeSettingsFocusId('display-name')).toBe('display-name'); + expect(normalizeSettingsFocusId('display-name">Settings')).toBeUndefined(); + expect(normalizeSettingsFocusId('')).toBeUndefined(); + }); + + it('builds human-readable settings link labels', () => { + expect(getSettingsLinkLabel('appearance', 'message-link-preview')).toBe( + 'Settings > Appearance > Message Link Preview' + ); + expect(getSettingsLinkLabel('account')).toBe('Settings > Account'); + }); }); diff --git a/src/app/features/settings/settingsLink.ts b/src/app/features/settings/settingsLink.ts index fa0c1dabc..030472a25 100644 --- a/src/app/features/settings/settingsLink.ts +++ b/src/app/features/settings/settingsLink.ts @@ -1,5 +1,5 @@ import { getAppPathFromHref, getSettingsPath, withOriginBaseUrl } from '$pages/pathUtils'; -import { isSettingsSectionId, type SettingsSectionId } from './routes'; +import { isSettingsSectionId, settingsSections, type SettingsSectionId } from './routes'; export type SettingsLink = { section: SettingsSectionId; @@ -8,6 +8,229 @@ export type SettingsLink = { export const SETTINGS_LINK_ACTION_PARAM = 'moe.sable.client.action'; export const SETTINGS_LINK_ACTION_SETTINGS = 'settings'; +const SETTINGS_FOCUS_ID_PATTERN = /^[a-z0-9-]+$/; +const SETTINGS_LINK_FORBIDDEN_QUERY_VALUE_PATTERN = /["<>]/; + +const settingsSectionLabel = Object.fromEntries( + settingsSections.map((section) => [section.id, section.label]) +) as Record; + +const settingsLinkFocusIdsBySection: Record = { + general: [ + 'client-side-embeds', + 'custom-date-format', + 'date-format', + 'disable-media-auto-load', + 'display-bundled-embeds', + 'embed-youtube-links', + 'emoji-selector-threshold', + 'enable-swiping', + 'encrypted-room-embeds', + 'encrypted-room-url-preview', + 'enter-for-newline', + 'error-reporting', + 'file-description-placement', + 'hide-member-events-read-only-rooms', + 'hide-membership-change', + 'hide-profile-change', + 'hide-read-receipts', + 'hide-typing-indicators', + 'large-room-call-button', + 'markdown-formatting', + 'message-layout', + 'message-spacing', + 'presence-status', + 'reply-notifications', + 'right-aligned-bubbles', + 'right-swipe-action', + 'session-replay', + 'show-hidden-events', + 'show-redacted-message-tombstones', + 'sync-across-devices', + 'sync-status', + 'twenty-four-hour-time-format', + 'url-preview', + 'use-sliding-sync', + ], + account: [ + 'about-you', + 'avatar', + 'banner', + 'blocked-users', + 'display-name', + 'email-address', + 'has-cats', + 'is-cat', + 'matrix-id', + 'name-color', + 'name-color-dark-theme', + 'name-color-light-theme', + 'pronouns', + 'render-animals', + 'status', + 'timezone', + ], + persona: ['enable-pk-commands', 'enable-pk-shorthands'], + appearance: [ + 'autoplay-emojis', + 'autoplay-gifs', + 'autoplay-stickers', + 'blur-avatars', + 'blur-emotes', + 'blur-media', + 'code-block-dark-theme', + 'code-block-light-theme', + 'code-block-manual-theme', + 'code-block-system-theme', + 'collapse-folders-by-default', + 'colorful-names', + 'consistent-icon-style', + 'customize-dm-cards', + 'dark-theme', + 'jumbo-emoji-size', + 'light-theme', + 'manual-theme', + 'message-link-preview', + 'page-zoom', + 'pronoun-pills-for-all', + 'reduced-motion', + 'render-global-username-colors', + 'render-space-room-fonts', + 'render-space-room-username-colors', + 'saturation', + 'selected-language-for-pronouns', + 'show-easter-eggs', + 'show-pronoun-pills', + 'show-pronouns-only-in-selected-language', + 'subspace-hierarchy-limit', + 'system-theme', + 'twitter-emoji', + 'underline-links', + ], + notifications: [ + 'background-push-notifications', + 'clear-notifications-when-read-elsewhere', + 'contains-display-name', + 'contains-username', + 'direct-messages', + 'direct-messages-encrypted', + 'email-notification', + 'favicon-dot-mentions-only', + 'highlight-mentions', + 'in-app-notification-sound', + 'in-app-notifications', + 'mention-room', + 'mention-user-id', + 'reset-all-push-notifications', + 'rooms', + 'rooms-encrypted', + 'select-keyword', + 'show-dm-counts', + 'show-encrypted-message-content', + 'show-mention-counts', + 'show-message-content', + 'show-room-counts', + 'system-notifications', + ], + devices: [ + 'device-dashboard', + 'device-verification', + 'export-messages-data', + 'import-messages-data', + ], + emojis: ['default-pack', 'select-pack'], + 'developer-tools': [ + 'access-token', + 'enable-developer-tools', + 'export-debug-logs', + 'global-account-data', + 'sentry-category-call', + 'sentry-category-error', + 'sentry-category-general', + 'sentry-category-message', + 'sentry-category-network', + 'sentry-category-notification', + 'sentry-category-sync', + 'sentry-category-timeline', + 'sentry-category-ui', + 'session-activity', + 'session-error-budget', + 'session-replay', + 'traces-profiles', + ], + experimental: ['bandwidth-saving-emojis', 'sharehistory-command', 'show-personas-tab'], + about: [ + 'base-url', + 'clear-cache-and-reload', + 'domain', + 'federation-url', + 'homeserver-compiler', + 'homeserver-name', + 'homeserver-version', + 'report-an-issue', + ], + 'keyboard-shortcuts': [], +}; + +const settingsLinkFocusIdsBySectionSet = settingsSections.reduce( + (acc, section) => { + acc[section.id] = new Set(settingsLinkFocusIdsBySection[section.id]); + return acc; + }, + {} as Record> +); + +export const normalizeSettingsFocusId = (focus?: string): string | undefined => { + if (!focus || !SETTINGS_FOCUS_ID_PATTERN.test(focus)) { + return undefined; + } + + return focus; +}; + +const isShareableSettingsFocusId = (section: SettingsSectionId, focus: string): boolean => + settingsLinkFocusIdsBySectionSet[section].has(focus); + +const parseSettingsLinkQuery = ( + search: string +): { focus?: string; hasActionMarker: boolean } | undefined => { + const params = new URLSearchParams(search); + + if ( + Array.from(params.entries()).some( + ([key, value]) => + SETTINGS_LINK_FORBIDDEN_QUERY_VALUE_PATTERN.test(key) || + SETTINGS_LINK_FORBIDDEN_QUERY_VALUE_PATTERN.test(value) + ) + ) { + return undefined; + } + + const focusValues = params.getAll('focus'); + if (focusValues.length > 1) { + return undefined; + } + + const focus = focusValues[0]; + if (focus !== undefined && normalizeSettingsFocusId(focus) === undefined) { + return undefined; + } + + const actionValues = params.getAll(SETTINGS_LINK_ACTION_PARAM); + if (actionValues.length > 1) { + return undefined; + } + + const action = actionValues[0]; + if (action !== undefined && action !== SETTINGS_LINK_ACTION_SETTINGS) { + return undefined; + } + + return { + focus, + hasActionMarker: action === SETTINGS_LINK_ACTION_SETTINGS, + }; +}; const withSettingsLinkAction = (path: string): string => { const [pathname, search = ''] = path.split('?'); @@ -27,13 +250,18 @@ const parseSettingsAppPath = (appPath: string): SettingsLink | undefined => { const section = sectionMatch[1]; if (!isSettingsSectionId(section)) return undefined; - const focus = new URLSearchParams(search).get('focus') ?? undefined; + const query = parseSettingsLinkQuery(search); + if (!query) return undefined; - return { section, focus }; + if (query.focus && !isShareableSettingsFocusId(section, query.focus)) { + return undefined; + } + + return { section, focus: query.focus }; }; const hasSettingsLinkAction = (search: string): boolean => - new URLSearchParams(search).get(SETTINGS_LINK_ACTION_PARAM) === SETTINGS_LINK_ACTION_SETTINGS; + parseSettingsLinkQuery(search)?.hasActionMarker === true; const getCrossBaseSettingsPathname = (pathname: string): string | undefined => pathname.match(/(\/settings\/[^/]+\/?)$/)?.[1]; @@ -88,6 +316,27 @@ export const buildSettingsLink = ( focus?: string ): string => withOriginBaseUrl(baseUrl, withSettingsLinkAction(getSettingsPath(section, focus))); +const humanizeSettingsLinkPart = (value: string): string => + value + .split(/[^a-zA-Z0-9]+/) + .filter(Boolean) + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(' '); + +export const getSettingsLinkLabel = (section: SettingsSectionId, focus?: string): string => { + const sectionLabel = settingsSectionLabel[section]; + const focusLabel = focus ? humanizeSettingsLinkPart(focus) : undefined; + + return focusLabel ? `Settings > ${sectionLabel} > ${focusLabel}` : `Settings > ${sectionLabel}`; +}; + +export const getSettingsLinkChipLabel = (section: SettingsSectionId, focus?: string): string => { + const sectionLabel = settingsSectionLabel[section]; + const focusLabel = focus ? humanizeSettingsLinkPart(focus) : undefined; + + return focusLabel ? `${sectionLabel} / ${focusLabel}` : sectionLabel; +}; + export const parseSettingsLink = (baseUrl: string, href: string): SettingsLink | undefined => { try { const sameBaseAppPath = getSameBaseSettingsAppPath(baseUrl, href); diff --git a/src/app/plugins/react-custom-html-parser.test.tsx b/src/app/plugins/react-custom-html-parser.test.tsx index 0513cc74d..d6bbd099b 100644 --- a/src/app/plugins/react-custom-html-parser.test.tsx +++ b/src/app/plugins/react-custom-html-parser.test.tsx @@ -160,7 +160,7 @@ describe('react custom html parser', () => { expect(link).toHaveAttribute('data-settings-link-section', 'appearance'); expect(link).toHaveAttribute('data-settings-link-focus', 'message-link-preview'); expect(link.className).toContain(customHtmlCss.Mention({})); - expect(link).not.toHaveTextContent('Settings:'); + expect(link).not.toHaveTextContent('Settings >'); expect(link.className).toContain(customHtmlCss.MentionWithIcon); }); @@ -170,7 +170,7 @@ describe('react custom html parser', () => { { sanitize: false } ); - const link = screen.getByRole('link', { name: 'Appearance' }); + const link = screen.getByRole('link', { name: 'Appearance / Message Link Preview' }); expect(link).toHaveAttribute( 'href', 'https://app.example/settings/appearance?focus=message-link-preview&moe.sable.client.action=settings' @@ -188,7 +188,7 @@ describe('react custom html parser', () => { { sanitize: false } ); - const link = screen.getByRole('link', { name: 'Account' }); + const link = screen.getByRole('link', { name: 'Account / Status' }); expect(link).toHaveAttribute( 'href', 'https://other.example/#/client/settings/account?focus=status&moe.sable.client.action=settings' @@ -197,6 +197,49 @@ describe('react custom html parser', () => { expect(link).toHaveAttribute('data-settings-link-focus', 'status'); }); + it('keeps malformed settings-looking linkified tokens as normal links', () => { + const renderLink = factoryRenderLinkifyWithMention( + settingsLinkBaseUrl, + () => undefined, + undefined + ) as (ir: never) => JSX.Element; + const malformedToken = + 'https://app.example/settings/account?focus=status&moe.sable.client.action=settings">Settings'; + + render( +
+ {renderLink({ + tagName: 'a', + attributes: { + href: malformedToken, + }, + content: malformedToken, + } as never)} +
+ ); + + const link = screen.getByRole('link', { name: malformedToken }); + expect(link).not.toHaveAttribute('data-settings-link-section'); + expect(link).not.toHaveAttribute('data-settings-link-focus'); + expect(link.className).not.toContain(customHtmlCss.MentionWithIcon); + }); + + it('keeps settings links with unknown focus ids as normal links', () => { + renderParsedHtml( + 'Settings > Account > Display Name2', + { sanitize: false } + ); + + const link = screen.getByRole('link', { name: 'Settings > Account > Display Name2' }); + expect(link).toHaveAttribute( + 'href', + 'https://app.example/settings/account?focus=display-name2' + ); + expect(link).not.toHaveAttribute('data-settings-link-section'); + expect(link).not.toHaveAttribute('data-settings-link-focus'); + expect(link.className).not.toContain(customHtmlCss.MentionWithIcon); + }); + it('renders matrix message permalinks with an icon instead of the Message prefix', () => { render(
diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index c39ac976c..51a718f53 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -36,8 +36,7 @@ import { onEnterOrSpace } from '$utils/keyboard'; import { copyToClipboard } from '$utils/dom'; import { isMatrixHexColor } from '$utils/matrixHtml'; import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; -import { parseSettingsLink } from '$features/settings/settingsLink'; -import { settingsSections } from '$features/settings/routes'; +import { getSettingsLinkChipLabel, parseSettingsLink } from '$features/settings/settingsLink'; import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; import { CodeHighlightRenderer } from '$components/code-highlight'; import { @@ -202,65 +201,20 @@ export const renderMatrixMention = ( return undefined; }; -const settingsSectionLabel = Object.fromEntries( - settingsSections.map((section) => [section.id, section.label]) -) as Record<(typeof settingsSections)[number]['id'], string>; - -const humanizeSettingsLinkPart = (value: string): string => - value - .split(/[^a-zA-Z0-9]+/) - .filter(Boolean) - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); - -const getSettingsLinkLabel = ( - section: keyof typeof settingsSectionLabel, - focus?: string -): string => { - const sectionLabel = settingsSectionLabel[section]; - const focusLabel = focus ? humanizeSettingsLinkPart(focus) : undefined; - - return focusLabel ? `${sectionLabel} / ${focusLabel}` : sectionLabel; -}; - -const getSettingsLinkChildren = ({ - href, - section, - focus, - content, - fallbackChildren, -}: { - href: string; - section: keyof typeof settingsSectionLabel; - focus?: string; - content?: string; - fallbackChildren?: ReactNode; -}): ReactNode => { - if (!content || content === href || content === safeDecodeUrl(href)) { - return getSettingsLinkLabel(section, focus); - } - - return fallbackChildren ?? content; -}; - const renderSettingsLink = ({ href, section, focus, handleMentionClick, - content, - fallbackChildren, }: { href: string; - section: keyof typeof settingsSectionLabel; + section: Parameters[0]; focus?: string; handleMentionClick?: ReactEventHandler; - content?: string; - fallbackChildren?: ReactNode; }) => ( ); @@ -299,8 +253,6 @@ export const factoryRenderLinkifyWithMention = ( section, focus, handleMentionClick, - content, - fallbackChildren: content, }); } } @@ -715,8 +667,6 @@ export const getReactCustomHtmlParser = ( section, focus, handleMentionClick: params.handleMentionClick, - content, - fallbackChildren: renderedChildren, }); } } diff --git a/src/app/styles/CustomHtml.css.ts b/src/app/styles/CustomHtml.css.ts index fb6882f95..81d841faa 100644 --- a/src/app/styles/CustomHtml.css.ts +++ b/src/app/styles/CustomHtml.css.ts @@ -178,6 +178,7 @@ export const MentionWithIcon = style({ display: 'inline-flex', alignItems: 'center', gap: toRem(2), + verticalAlign: 'middle', }); export const MentionIcon = style({