diff --git a/.changeset/add_shorts_support_to_fix_crash.md b/.changeset/add_shorts_support_to_fix_crash.md deleted file mode 100644 index a7396c050..000000000 --- a/.changeset/add_shorts_support_to_fix_crash.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Add youtube shorts support to stop it from crashing sable. diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 000000000..f1df6a2db --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,101 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: 'CodeQL Advanced' + +on: + push: + branches: ['dev'] + pull_request: + branches: ['dev'] + schedule: + - cron: '29 1 * * 2' + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + # Runner size impacts CodeQL analysis time. To learn more, please see: + # - https://gh.io/recommended-hardware-resources-for-running-codeql + # - https://gh.io/supported-runners-and-hardware-resources + # - https://gh.io/using-larger-runners (GitHub.com only) + # Consider using larger runners or machines with greater resources for possible analysis time improvements. + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + permissions: + # required for all workflows + security-events: write + + # required to fetch internal or private CodeQL packs + packages: read + + # only required for workflows in private repositories + actions: read + contents: read + + strategy: + fail-fast: false + matrix: + include: + - language: actions + build-mode: none + - language: javascript-typescript + build-mode: none + # CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift' + # Use `c-cpp` to analyze code written in C, C++ or both + # Use 'java-kotlin' to analyze code written in Java, Kotlin or both + # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both + # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis, + # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning. + # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how + # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + # Add any setup steps before running the `github/codeql-action/init` action. + # This includes steps like installing compilers or runtimes (`actions/setup-node` + # or others). This is typically only required for manual builds. + # - name: Setup runtime (example) + # uses: actions/setup-example@v1 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@c10b8064de6f491fea524254123dbe5e09572f13 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + # If the analyze step fails for one of the languages you are analyzing with + # "We were unable to automatically build your code", modify the matrix above + # to set the build mode to "manual" for that language. Then modify this step + # to build your code. + # â„šī¸ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + - name: Run manual build steps + if: matrix.build-mode == 'manual' + shell: bash + run: | + echo 'If you are using a "manual" build mode for one or more of the' \ + 'languages you are analyzing, replace this with the commands to build' \ + 'your code, for example:' + echo ' make bootstrap' + echo ' make release' + exit 1 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@c10b8064de6f491fea524254123dbe5e09572f13 + with: + category: '/language:${{matrix.language}}' diff --git a/CHANGELOG.md b/CHANGELOG.md index 9808f917d..8d0dbcb8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Sable Client Changelog +## 1.13.1 (2026-03-30) + +### Fixes + +* Add youtube shorts support to stop it from crashing sable. ([#578](https://github.com/SableClient/Sable/pull/578) by @nushea) +* Fix rich-text reply previews and custom-formatted messages so unsafe HTML is filtered more strictly and Matrix colors render correctly. ([#571](https://github.com/SableClient/Sable/pull/571) by @hazre) +* Fix crash when previewing non-video YouTube URLs (channels, @handles, etc.) that lack query parameters. ([#584](https://github.com/SableClient/Sable/pull/584) by @Just-Insane) +* fix id handling and id generation for Personas ([#583](https://github.com/SableClient/Sable/pull/583) by @dozro) + ## 1.13.0 (2026-03-28) ### Features diff --git a/package.json b/package.json index 396386ff2..0f8bd3df2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sable", - "version": "1.13.0", + "version": "1.13.1", "description": "An almost stable Matrix client", "type": "module", "packageManager": "pnpm@10.32.1+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be", @@ -53,6 +53,7 @@ "classnames": "^2.5.1", "dayjs": "^1.11.19", "domhandler": "^5.0.3", + "dompurify": "^3.3.3", "emojibase": "^15.3.1", "emojibase-data": "^15.3.2", "eslint-plugin-react": "7.37.5", @@ -85,7 +86,6 @@ "react-i18next": "^16.5.4", "react-range": "^1.10.0", "react-router-dom": "^6.30.3", - "sanitize-html": "^2.17.1", "slate": "^0.123.0", "slate-dom": "^0.123.0", "slate-history": "^0.113.1", @@ -114,7 +114,6 @@ "@types/react": "^18.3.28", "@types/react-dom": "^18.3.7", "@types/react-google-recaptcha": "^2.1.9", - "@types/sanitize-html": "^2.16.0", "@types/ua-parser-js": "^0.7.39", "@vitejs/plugin-react": "^5.1.4", "@vitest/coverage-v8": "^4.1.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ad8544f09..e5a3fb8a2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -84,6 +84,9 @@ importers: domhandler: specifier: ^5.0.3 version: 5.0.3 + dompurify: + specifier: ^3.3.3 + version: 3.3.3 emojibase: specifier: ^15.3.1 version: 15.3.1 @@ -180,9 +183,6 @@ importers: react-router-dom: specifier: ^6.30.3 version: 6.30.3(react-dom@18.3.1(react@18.3.1))(react@18.3.1) - sanitize-html: - specifier: ^2.17.1 - version: 2.17.1 slate: specifier: ^0.123.0 version: 0.123.0 @@ -262,9 +262,6 @@ importers: '@types/react-google-recaptcha': specifier: ^2.1.9 version: 2.1.9 - '@types/sanitize-html': - specifier: ^2.16.0 - version: 2.16.1 '@types/ua-parser-js': specifier: ^0.7.39 version: 0.7.39 @@ -2836,9 +2833,6 @@ packages: '@types/resolve@1.20.2': resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==} - '@types/sanitize-html@2.16.1': - resolution: {integrity: sha512-n9wjs8bCOTyN/ynwD8s/nTcTreIHB1vf31vhLMGqUPNHaweKC4/fAl4Dj+hUlCTKYgm4P3k83fmiFfzkZ6sgMA==} - '@types/trusted-types@2.0.7': resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} @@ -3514,6 +3508,9 @@ packages: resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} engines: {node: '>= 4'} + dompurify@3.3.3: + resolution: {integrity: sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==} + domutils@3.2.2: resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} @@ -4082,9 +4079,6 @@ packages: htmlparser2@10.1.0: resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==} - htmlparser2@8.0.2: - resolution: {integrity: sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==} - htmlparser2@9.0.0: resolution: {integrity: sha512-uxbSI98wmFT/G4P2zXx4OVx04qWUmyFPrD2/CNepa2Zo3GPNaCaaxElDgwUrwYWkK1nr9fft0Ya8dws8coDLLQ==} @@ -4689,9 +4683,6 @@ packages: resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} engines: {node: '>=8'} - parse-srcset@1.0.2: - resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==} - parse5@8.0.0: resolution: {integrity: sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==} @@ -4971,9 +4962,6 @@ packages: resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} engines: {node: '>= 0.4'} - sanitize-html@2.17.1: - resolution: {integrity: sha512-ehFCW+q1a4CSOWRAdX97BX/6/PDEkCqw7/0JXZAGQV57FQB3YOkTa/rrzHPeJ+Aghy4vZAFfWMYyfxIiB7F/gw==} - saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} @@ -8500,10 +8488,6 @@ snapshots: '@types/resolve@1.20.2': {} - '@types/sanitize-html@2.16.1': - dependencies: - htmlparser2: 10.1.0 - '@types/trusted-types@2.0.7': {} '@types/ua-parser-js@0.7.39': {} @@ -9247,6 +9231,10 @@ snapshots: dependencies: domelementtype: 2.3.0 + dompurify@3.3.3: + optionalDependencies: + '@types/trusted-types': 2.0.7 + domutils@3.2.2: dependencies: dom-serializer: 2.0.0 @@ -10002,13 +9990,6 @@ snapshots: domutils: 3.2.2 entities: 7.0.1 - htmlparser2@8.0.2: - dependencies: - domelementtype: 2.3.0 - domhandler: 5.0.3 - domutils: 3.2.2 - entities: 4.5.0 - htmlparser2@9.0.0: dependencies: domelementtype: 2.3.0 @@ -10644,8 +10625,6 @@ snapshots: json-parse-even-better-errors: 2.3.1 lines-and-columns: 1.2.4 - parse-srcset@1.0.2: {} - parse5@8.0.0: dependencies: entities: 6.0.1 @@ -10979,15 +10958,6 @@ snapshots: es-errors: 1.3.0 is-regex: 1.2.1 - sanitize-html@2.17.1: - dependencies: - deepmerge: 4.3.1 - escape-string-regexp: 4.0.0 - htmlparser2: 8.0.2 - is-plain-object: 5.0.0 - parse-srcset: 1.0.2 - postcss: 8.5.8 - saxes@6.0.0: dependencies: xmlchars: 2.2.0 diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 08c5e281d..e147610bf 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -88,6 +88,7 @@ function RenderMessageContentInternal({ [CaptionPosition.Inline]: 'row', [CaptionPosition.Hidden]: 'row', } satisfies Record; + const attachmentDirection = captionPositionMap[captionPosition]; const renderBody = useCallback( (props: any) => ( @@ -147,6 +148,8 @@ function RenderMessageContentInternal({ ), [urlPreview] ); + const messageUrlsPreview = urlPreview ? renderUrlsPreview : undefined; + const messageBundlePreview = bundledPreview ? renderBundledPreviews : undefined; const renderCaption = () => { const hasCaption = content.body && content.body.trim().length > 0; @@ -159,8 +162,8 @@ function RenderMessageContentInternal({ edited={edited} content={content} renderBody={renderBody} - renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined} - renderBundledPreviews={bundledPreview ? renderBundledPreviews : undefined} + renderUrlsPreview={messageUrlsPreview} + renderBundledPreviews={messageBundlePreview} /> ); return ( @@ -179,8 +182,8 @@ function RenderMessageContentInternal({ edited={edited} content={content} renderBody={renderBody} - renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined} - renderBundledPreviews={bundledPreview ? renderBundledPreviews : undefined} + renderUrlsPreview={messageUrlsPreview} + renderBundledPreviews={messageBundlePreview} /> ); @@ -188,54 +191,53 @@ function RenderMessageContentInternal({ return null; }; - const renderFile = () => ( -
-
- ( - ( - } - /> - )} - renderAsTextFile={() => ( - } - /> - )} - > - +
{attachment}
+ {renderCaption()} +
+ ); + } + + const renderFile = () => + renderCaptionedAttachment( + ( + ( + } /> - - )} - outlined={outlineAttachment} - /> -
- {renderCaption()} - - ); + )} + renderAsTextFile={() => ( + } + /> + )} + > + + + )} + outlined={outlineAttachment} + /> + ); if (msgType === MsgType.Text) { return ( @@ -243,8 +245,8 @@ function RenderMessageContentInternal({ edited={edited} content={content} renderBody={renderBody} - renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined} - renderBundledPreviews={bundledPreview ? renderBundledPreviews : undefined} + renderUrlsPreview={messageUrlsPreview} + renderBundledPreviews={messageBundlePreview} /> ); } @@ -265,8 +267,8 @@ function RenderMessageContentInternal({ edited={edited} content={content} renderBody={renderBody} - renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined} - renderBundledPreviews={bundledPreview ? renderBundledPreviews : undefined} + renderUrlsPreview={messageUrlsPreview} + renderBundledPreviews={messageBundlePreview} /> ); } @@ -277,8 +279,8 @@ function RenderMessageContentInternal({ edited={edited} content={content} renderBody={renderBody} - renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined} - renderBundledPreviews={bundledPreview ? renderBundledPreviews : undefined} + renderUrlsPreview={messageUrlsPreview} + renderBundledPreviews={messageBundlePreview} /> ); } @@ -291,101 +293,71 @@ function RenderMessageContentInternal({ content.body?.toLowerCase().endsWith('.webp') || (typeof content.url === 'string' && content.url.toLowerCase().includes('gif')); - return ( -
-
- ( - { - if (isGif && !autoplayGifs && p.src) { - return ( - - - - ); - } - return ; - }} - renderViewer={(p) => } - /> - )} - outlined={outlineAttachment} + return renderCaptionedAttachment( + ( + { + if (isGif && !autoplayGifs && p.src) { + return ( + + + + ); + } + return ; + }} + renderViewer={(p) => } /> -
- {renderCaption()} -
+ )} + outlined={outlineAttachment} + /> ); } if (msgType === MsgType.Video) { - return ( -
-
- ( - ( - ( - {body} - )} - /> - ) - : undefined - } - renderVideo={(p) => } - /> - )} - outlined={outlineAttachment} + return renderCaptionedAttachment( + ( + ( + ( + {body} + )} + /> + ) + : undefined + } + renderVideo={(p) => } /> -
- {renderCaption()} -
+ )} + outlined={outlineAttachment} + /> ); } if (msgType === MsgType.Audio) { - return ( -
-
- ( - } /> - )} - outlined={outlineAttachment} - /> -
- {renderCaption()} -
+ return renderCaptionedAttachment( + ( + } /> + )} + outlined={outlineAttachment} + /> ); } diff --git a/src/app/components/message/RenderBody.tsx b/src/app/components/message/RenderBody.tsx index e26b237b0..ad027db22 100644 --- a/src/app/components/message/RenderBody.tsx +++ b/src/app/components/message/RenderBody.tsx @@ -9,6 +9,25 @@ import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations'; import { splitByAbbreviations } from '$utils/abbreviations'; import { MessageEmptyContent } from './content'; +function getRenderedBodyText(text: string, highlightRegex?: RegExp): (string | JSX.Element)[] { + const emojiScaledText = scaleSystemEmoji(text); + + return highlightRegex ? highlightText(highlightRegex, emojiScaledText) : emojiScaledText; +} + +function renderLinkifiedBodyText( + text: string, + linkifyOpts: Opts, + highlightRegex: RegExp | undefined, + key?: string +): JSX.Element { + return ( + + {getRenderedBodyText(text, highlightRegex)} + + ); +} + type AbbreviationTermProps = { text: string; definition: string; @@ -92,7 +111,6 @@ export function buildAbbrReplaceTextNode( type RenderBodyProps = { body: string; customBody?: string; - highlightRegex?: RegExp; htmlReactParserOptions: HTMLReactParserOptions; linkifyOpts: Opts; @@ -107,7 +125,6 @@ export function RenderBody({ const abbrMap = useRoomAbbreviationsContext(); if (customBody) { - if (customBody === '') return ; return parse(sanitizeCustomHtml(customBody), htmlReactParserOptions); } if (body === '') return ; @@ -122,24 +139,12 @@ export function RenderBody({ const definition = abbrMap.get(seg.termKey) ?? ''; return ; } - return ( - - {highlightRegex - ? highlightText(highlightRegex, scaleSystemEmoji(seg.text)) - : scaleSystemEmoji(seg.text)} - - ); + return renderLinkifiedBodyText(seg.text, linkifyOpts, highlightRegex, seg.id); })} ); } } - return ( - - {highlightRegex - ? highlightText(highlightRegex, scaleSystemEmoji(body)) - : scaleSystemEmoji(body)} - - ); + return renderLinkifiedBodyText(body, linkifyOpts, highlightRegex); } diff --git a/src/app/components/message/Reply.test.tsx b/src/app/components/message/Reply.test.tsx new file mode 100644 index 000000000..aa5c19fb5 --- /dev/null +++ b/src/app/components/message/Reply.test.tsx @@ -0,0 +1,129 @@ +import { render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { Reply } from './Reply'; + +const { mockUseRoomEvent, mockInvalidateQueries } = vi.hoisted(() => ({ + mockUseRoomEvent: vi.fn(), + mockInvalidateQueries: vi.fn(), +})); + +vi.mock('@tanstack/react-query', () => ({ + useQueryClient: () => ({ + invalidateQueries: mockInvalidateQueries, + }), +})); + +vi.mock('jotai', async (importActual) => { + const actual = await importActual(); + return { + ...actual, + useAtomValue: () => ({}), + }; +}); + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string) => key, + }), +})); + +vi.mock('$hooks/useRoomEvent', () => ({ + useRoomEvent: (...args: unknown[]) => mockUseRoomEvent(...args), +})); + +vi.mock('$hooks/useSableCosmetics', () => ({ + useSableCosmetics: () => ({ color: undefined, font: undefined }), +})); + +vi.mock('$hooks/useMediaAuthentication', () => ({ + useMediaAuthentication: () => false, +})); + +vi.mock('$hooks/useIgnoredUsers', () => ({ + useIgnoredUsers: () => [], +})); + +vi.mock('$hooks/useMatrixClient', () => ({ + useMatrixClient: () => + ({ + getRoom: () => undefined, + getUserId: () => '@me:example.com', + mxcUrlToHttp: () => null, + }) as any, +})); + +vi.mock('$hooks/useMemberEventParser', () => ({ + useMemberEventParser: () => vi.fn(), +})); + +vi.mock('$hooks/useMentionClickHandler', () => ({ + useMentionClickHandler: () => undefined, +})); + +vi.mock('$utils/room', async (importActual) => { + const actual = await importActual(); + return { + ...actual, + getMemberDisplayName: () => 'Alice', + }; +}); + +const createReplyEvent = (formattedBody: string) => + ({ + getContent: () => ({ + body: 'fallback body', + format: 'org.matrix.custom.html', + formatted_body: formattedBody, + msgtype: 'm.text', + }), + getSender: () => '@alice:example.com', + getType: () => 'm.room.message', + isRedacted: () => false, + isEncrypted: () => false, + isDecryptionFailure: () => false, + getClearContent: () => ({}), + }) as any; + +describe('Reply', () => { + it('sanitizes formatted_body before trimming and parsing the reply preview', () => { + mockUseRoomEvent.mockReturnValue( + createReplyEvent( + '
quoted
' + + 'visible' + + 'blocked image' + ) + ); + + render( + undefined } as any} + replyEventId="$reply:example.com" + /> + ); + + expect(screen.getByText('visible')).toBeInTheDocument(); + expect(screen.queryByText('quoted')).not.toBeInTheDocument(); + expect(screen.queryByText('alert(1)')).not.toBeInTheDocument(); + expect(screen.queryByAltText('blocked image')).not.toBeInTheDocument(); + }); + + it('does not render unresolved mxc images as raw browser img tags in reply previews', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + + mockUseRoomEvent.mockReturnValue( + createReplyEvent( + 'blobcat' + ) + ); + + const { container } = render( + undefined } as any} + replyEventId="$reply:example.com" + /> + ); + + expect(container.querySelector('img[src^="mxc://"]')).toBeNull(); + expect(warnSpy).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index a7e10729b..cf1786ca8 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -8,6 +8,7 @@ import { useAtomValue } from 'jotai'; import { getMemberDisplayName, trimReplyFromBody, trimReplyFromFormattedBody } from '$utils/room'; import { getMxIdLocalPart } from '$utils/matrix'; import { randomNumberBetween } from '$utils/common'; +import { sanitizeCustomHtml } from '$utils/sanitize'; import { getReactCustomHtmlParser, scaleSystemEmoji, @@ -25,7 +26,6 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMemberEventParser } from '$hooks/useMemberEventParser'; import { StateEvent, MessageEvent } from '$types/matrix/room'; import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; -import { sanitizeCustomHtml } from '$utils/sanitize'; import { useTranslation } from 'react-i18next'; import * as customHtmlCss from '$styles/CustomHtml.css'; import { @@ -93,7 +93,8 @@ type ReplyProps = { }; export const sanitizeReplyFormattedPreview = (formattedBody: string): string => { - const strippedHtml = trimReplyFromFormattedBody(formattedBody) + const safeFormattedBody = sanitizeCustomHtml(formattedBody); + const strippedHtml = trimReplyFromFormattedBody(safeFormattedBody) .replaceAll(//gi, ' ') .replaceAll(/<\/p>\s*]*>/gi, ' ') .replaceAll(/<\/?p[^>]*>/gi, '') @@ -101,7 +102,7 @@ export const sanitizeReplyFormattedPreview = (formattedBody: string): string => .replaceAll(/<\/?(ul|ol|li|blockquote|h[1-6]|pre|div)[^>]*>/gi, '') .replaceAll(/(?:\r\n|\r|\n)/g, ' '); - return sanitizeCustomHtml(strippedHtml); + return strippedHtml; }; export const Reply = as<'div', ReplyProps>( @@ -138,6 +139,9 @@ export const Reply = as<'div', ReplyProps>( const badEncryption = replyEvent?.getContent().msgtype === 'm.bad.encrypted'; const mentionClickHandler = useMentionClickHandler(room.roomId); + const isFormattedReply = + format === 'org.matrix.custom.html' && typeof formattedBody === 'string'; + const hasPlainTextReply = typeof body === 'string' && body !== ''; // An encrypted event that hasn't been decrypted yet (keys pending) has an // empty result from getClearContent(). Treat it as still-loading rather @@ -170,7 +174,7 @@ export const Reply = as<'div', ReplyProps>( [mx, room.roomId, mentionClickHandler, nicknames] ); - if (format === 'org.matrix.custom.html' && formattedBody) { + if (isFormattedReply && formattedBody !== '') { const sanitizedHtml = sanitizeReplyFormattedPreview(formattedBody); const parserOpts = getReactCustomHtmlParser(mx, room.roomId, { linkifyOpts: replyLinkifyOpts, @@ -179,7 +183,7 @@ export const Reply = as<'div', ReplyProps>( handleMentionClick: mentionClickHandler, }); bodyJSX = parse(sanitizedHtml, parserOpts) as JSX.Element; - } else if (body) { + } else if (hasPlainTextReply) { const strippedBody = trimReplyFromBody(body).replaceAll(/(?:\r\n|\r|\n)/g, ' '); bodyJSX = scaleSystemEmoji(strippedBody); } else if (eventType === StateEvent.RoomMember && !!replyEvent) { @@ -237,6 +241,13 @@ export const Reply = as<'div', ReplyProps>( ); } + let replyContent = bodyJSX; + if (isBlockedSender) { + replyContent = ; + } else if (badEncryption) { + replyContent = ; + } + return ( {threadRootId && ( @@ -261,11 +272,7 @@ export const Reply = as<'div', ReplyProps>( > {replyEvent !== undefined && !isPendingDecrypt ? ( - {(() => { - if (isBlockedSender) return ; - if (badEncryption) return ; - return bodyJSX; - })()} + {replyContent} ) : ( (isRedacted && ) || ( diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx index 7e29f3d49..133dc940e 100644 --- a/src/app/components/message/modals/MessageForward.tsx +++ b/src/app/components/message/modals/MessageForward.tsx @@ -23,7 +23,7 @@ import { allRoomsAtom } from '$state/room-list/roomList'; import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; import { factoryRoomIdByActivity } from '$utils/sort'; import * as css from '$features/room/message/styles.css'; -import { sanitizeCustomHtml } from '$utils/sanitize'; +import { sanitizeCustomHtml, sanitizeText } from '$utils/sanitize'; import { getStateEvents } from '$utils/room'; import { StateEvent } from '$types/matrix/room'; import { createDebugLogger } from '$utils/debugLogger'; @@ -206,12 +206,12 @@ export function MessageForwardInternal({ const safeHtml = originalFormattedBody === undefined - ? sanitizeCustomHtml(originalBody).replaceAll('\n', '
') + ? sanitizeText(originalBody).replaceAll('\n', '
') : sanitizeCustomHtml(originalFormattedBody); newBodyHtml = `
` + - `

${sanitizeCustomHtml(bodyModifText)}

` + + `

${sanitizeText(bodyModifText)}

` + `
${safeHtml}
` + `
`; } diff --git a/src/app/components/url-preview/ClientPreview.tsx b/src/app/components/url-preview/ClientPreview.tsx index 948f48095..ac35059e7 100644 --- a/src/app/components/url-preview/ClientPreview.tsx +++ b/src/app/components/url-preview/ClientPreview.tsx @@ -168,21 +168,19 @@ function parseYoutubeLink(url: string): YoutubeLink | null { [videoId] = split; params = split[1]?.split('&'); } else if (url.includes('/shorts/')) { - const split = path.split('/shorts/'); + const split = path.split('?'); [videoId] = split; - params = split[1]?.split('shorts'); + params = split[1]?.split('&') ?? []; } else if (url.includes('youtube.com')) { - params = path.split('?')[1].split('&'); - videoId = params.find((s) => s.startsWith('v='), params)?.split('v=')[1]; + params = path.split('?')[1]?.split('&') ?? []; + videoId = params.find((s) => s.startsWith('v='))?.split('v=')[1]; } else return null; if (!videoId) return null; // playlist is not used for the embed, it can be appended as is - const playlist = params ? params.find((s) => s.startsWith('list='), params) : undefined; - const timestamp = params - ? params.find((s) => s.startsWith('t='), params)?.split('t=')[1] - : undefined; + const playlist = params ? params.find((s) => s.startsWith('list=')) : undefined; + const timestamp = params ? params.find((s) => s.startsWith('t='))?.split('t=')[1] : undefined; return { videoId, diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index 1f924a909..70eca4dc2 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -144,7 +144,7 @@ import { } from '$hooks/usePerMessageProfile'; import { Microphone, Stop } from '@phosphor-icons/react'; import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec'; -import { sanitizeCustomHtml } from '$utils/sanitize'; +import { sanitizeText } from '$utils/sanitize'; import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler'; import { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler'; import { SchedulePickerDialog } from './schedule-send'; @@ -812,7 +812,7 @@ export const RoomInput = forwardRef( /** * html escaped version of the display name */ - const escapedName = sanitizeCustomHtml(perMessageProfile.name); + const escapedName = sanitizeText(perMessageProfile.name); const htmlPrefix = `${escapedName}: `; diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index 22c63ce26..ad25ba45f 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -72,7 +72,7 @@ import { HTMLReactParserOptions } from 'html-react-parser'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { Opts as LinkifyOpts } from 'linkifyjs'; import { GetContentCallback } from '$types/matrix/room'; -import { sanitizeCustomHtml } from '$utils/sanitize'; +import { sanitizeText } from '$utils/sanitize'; type MessageEditorProps = { roomId: string; @@ -204,7 +204,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( plainText = bodyPrefix + plainText; } - const escapedName = sanitizeCustomHtml(pmpDisplayname); + const escapedName = sanitizeText(pmpDisplayname); const htmlPrefix = `${escapedName}: `; if (!customHtml.startsWith(htmlPrefix)) { customHtml = htmlPrefix + customHtml; diff --git a/src/app/features/settings/Persona/PerMessageProfileOverview.tsx b/src/app/features/settings/Persona/PerMessageProfileOverview.tsx index 6ed0dcef0..7a3ba574a 100644 --- a/src/app/features/settings/Persona/PerMessageProfileOverview.tsx +++ b/src/app/features/settings/Persona/PerMessageProfileOverview.tsx @@ -6,6 +6,7 @@ import { } from '$hooks/usePerMessageProfile'; import { useEffect, useState } from 'react'; import { Box, Button, Text } from 'folds'; +import { generateShortId } from '$utils/shortIdGen'; import { PerMessageProfileEditor } from './PerMessageProfileEditor'; /** @@ -36,7 +37,7 @@ export function PerMessageProfileOverview() {