Harden settings link parsing and rendering

This commit is contained in:
hazre committed 2026-04-18 18:27:16 +02:00
1 parent bf30f94bf1
commit 4dbdb6fcc9
6 files changed
+402 -61

No files matched your search

@@ -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'
);
});
});
@@ -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');
});
});
+253 -4
View File
@@ -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<SettingsSectionId, string>;
const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]> = {
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<SettingsSectionId, ReadonlySet<string>>
);
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);
@@ -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(
<div>
{renderLink({
tagName: 'a',
attributes: {
href: malformedToken,
},
content: malformedToken,
} as never)}
</div>
);
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(
'<a href="https://app.example/settings/account?focus=display-name2">Settings &gt; Account &gt; Display Name2</a>',
{ 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(
<div>
+4 -54
View File
@@ -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<typeof getSettingsLinkChipLabel>[0];
focus?: string;
handleMentionClick?: ReactEventHandler<HTMLElement>;
content?: string;
fallbackChildren?: ReactNode;
}) => (
<a
href={href}
{...makeMentionCustomProps(handleMentionClick, content)}
{...makeMentionCustomProps(handleMentionClick)}
className={classNames(css.Mention({}), css.MentionWithIcon)}
data-settings-link-section={section}
data-settings-link-focus={focus}
@@ -268,7 +222,7 @@ const renderSettingsLink = ({
<span aria-hidden="true" className={css.MentionIcon}>
<Icon size="50" src={Icons.Setting} />
</span>
{getSettingsLinkChildren({ href, section, focus, content, fallbackChildren })}
{getSettingsLinkChipLabel(section, focus)}
</a>
);
@@ -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,
});
}
}
+1
View File
@@ -178,6 +178,7 @@ export const MentionWithIcon = style({
display: 'inline-flex',
alignItems: 'center',
gap: toRem(2),
verticalAlign: 'middle',
});
export const MentionIcon = style({