mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 09:01:17 -08:00
Merge remote-tracking branch 'upstream/dev' into msc4095
This commit is contained in:
commit
8aef658bbb
23 files changed
+960
-446
No files matched your search
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Add youtube shorts support to stop it from crashing sable.
|
||||
@@ -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}}'
|
||||
@@ -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
|
||||
|
||||
+2
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sable",
|
||||
"version": "1.13.0",
|
||||
"version": "1.13.1",
|
||||
"description": "An almost stable Matrix client",
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]+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",
|
||||
|
||||
Generated
+10
-40
@@ -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([email protected]([email protected]))([email protected])
|
||||
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/[email protected]':
|
||||
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-n9wjs8bCOTyN/ynwD8s/nTcTreIHB1vf31vhLMGqUPNHaweKC4/fAl4Dj+hUlCTKYgm4P3k83fmiFfzkZ6sgMA==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||
|
||||
@@ -3514,6 +3508,9 @@ packages:
|
||||
resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
|
||||
engines: {node: '>= 4'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
|
||||
|
||||
@@ -4082,9 +4079,6 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-uxbSI98wmFT/G4P2zXx4OVx04qWUmyFPrD2/CNepa2Zo3GPNaCaaxElDgwUrwYWkK1nr9fft0Ya8dws8coDLLQ==}
|
||||
|
||||
@@ -4689,9 +4683,6 @@ packages:
|
||||
resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==}
|
||||
|
||||
@@ -4971,9 +4962,6 @@ packages:
|
||||
resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-ehFCW+q1a4CSOWRAdX97BX/6/PDEkCqw7/0JXZAGQV57FQB3YOkTa/rrzHPeJ+Aghy4vZAFfWMYyfxIiB7F/gw==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
|
||||
engines: {node: '>=v12.22.7'}
|
||||
@@ -8500,10 +8488,6 @@ snapshots:
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
htmlparser2: 10.1.0
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
'@types/[email protected]': {}
|
||||
@@ -9247,6 +9231,10 @@ snapshots:
|
||||
dependencies:
|
||||
domelementtype: 2.3.0
|
||||
|
||||
[email protected]:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
dom-serializer: 2.0.0
|
||||
@@ -10002,13 +9990,6 @@ snapshots:
|
||||
domutils: 3.2.2
|
||||
entities: 7.0.1
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
domelementtype: 2.3.0
|
||||
domhandler: 5.0.3
|
||||
domutils: 3.2.2
|
||||
entities: 4.5.0
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
domelementtype: 2.3.0
|
||||
@@ -10644,8 +10625,6 @@ snapshots:
|
||||
json-parse-even-better-errors: 2.3.1
|
||||
lines-and-columns: 1.2.4
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
entities: 6.0.1
|
||||
@@ -10979,15 +10958,6 @@ snapshots:
|
||||
es-errors: 1.3.0
|
||||
is-regex: 1.2.1
|
||||
|
||||
[email protected]:
|
||||
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
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
xmlchars: 2.2.0
|
||||
|
||||
@@ -88,6 +88,7 @@ function RenderMessageContentInternal({
|
||||
[CaptionPosition.Inline]: 'row',
|
||||
[CaptionPosition.Hidden]: 'row',
|
||||
} satisfies Record<CaptionPosition, React.CSSProperties['flexDirection']>;
|
||||
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}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
@@ -188,54 +191,53 @@ function RenderMessageContentInternal({
|
||||
return null;
|
||||
};
|
||||
|
||||
const renderFile = () => (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MFile
|
||||
content={content}
|
||||
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
|
||||
<FileContent
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
renderAsPdfFile={() => (
|
||||
<ReadPdfFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <PdfViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
renderAsTextFile={() => (
|
||||
<ReadTextFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <TextViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<DownloadFile
|
||||
function renderCaptionedAttachment(attachment: JSX.Element): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: attachmentDirection,
|
||||
}}
|
||||
>
|
||||
<div>{attachment}</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const renderFile = () =>
|
||||
renderCaptionedAttachment(
|
||||
<MFile
|
||||
content={content}
|
||||
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
|
||||
<FileContent
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
renderAsPdfFile={() => (
|
||||
<ReadPdfFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
info={info}
|
||||
renderViewer={(p) => <PdfViewer {...p} />}
|
||||
/>
|
||||
</FileContent>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
);
|
||||
)}
|
||||
renderAsTextFile={() => (
|
||||
<ReadTextFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <TextViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<DownloadFile body={body} mimeType={mimeType} url={url} encInfo={encInfo} info={info} />
|
||||
</FileContent>
|
||||
)}
|
||||
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 (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MImage
|
||||
content={content}
|
||||
renderImageContent={(imageProps) => (
|
||||
<ImageContent
|
||||
{...imageProps}
|
||||
autoPlay={mediaAutoLoad}
|
||||
renderImage={(p) => {
|
||||
if (isGif && !autoplayGifs && p.src) {
|
||||
return (
|
||||
<ClientSideHoverFreeze src={p.src}>
|
||||
<Image {...p} loading="lazy" />
|
||||
</ClientSideHoverFreeze>
|
||||
);
|
||||
}
|
||||
return <Image {...p} loading="lazy" />;
|
||||
}}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
return renderCaptionedAttachment(
|
||||
<MImage
|
||||
content={content}
|
||||
renderImageContent={(imageProps) => (
|
||||
<ImageContent
|
||||
{...imageProps}
|
||||
autoPlay={mediaAutoLoad}
|
||||
renderImage={(p) => {
|
||||
if (isGif && !autoplayGifs && p.src) {
|
||||
return (
|
||||
<ClientSideHoverFreeze src={p.src}>
|
||||
<Image {...p} loading="lazy" />
|
||||
</ClientSideHoverFreeze>
|
||||
);
|
||||
}
|
||||
return <Image {...p} loading="lazy" />;
|
||||
}}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (msgType === MsgType.Video) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MVideo
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderVideoContent={({ body, info, ...videoProps }) => (
|
||||
<VideoContent
|
||||
body={body}
|
||||
info={info}
|
||||
{...videoProps}
|
||||
renderThumbnail={
|
||||
mediaAutoLoad
|
||||
? () => (
|
||||
<ThumbnailContent
|
||||
info={info}
|
||||
renderImage={(src) => (
|
||||
<Image alt={body} title={body} src={src} loading="lazy" />
|
||||
)}
|
||||
/>
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
renderVideo={(p) => <PersistedVolumeVideo {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
return renderCaptionedAttachment(
|
||||
<MVideo
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderVideoContent={({ body, info, ...videoProps }) => (
|
||||
<VideoContent
|
||||
body={body}
|
||||
info={info}
|
||||
{...videoProps}
|
||||
renderThumbnail={
|
||||
mediaAutoLoad
|
||||
? () => (
|
||||
<ThumbnailContent
|
||||
info={info}
|
||||
renderImage={(src) => (
|
||||
<Image alt={body} title={body} src={src} loading="lazy" />
|
||||
)}
|
||||
/>
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
renderVideo={(p) => <PersistedVolumeVideo {...p} />}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (msgType === MsgType.Audio) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MAudio
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderAudioContent={(audioProps) => (
|
||||
<AudioContent {...audioProps} renderMediaControl={(p) => <MediaControl {...p} />} />
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
return renderCaptionedAttachment(
|
||||
<MAudio
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderAudioContent={(audioProps) => (
|
||||
<AudioContent {...audioProps} renderMediaControl={(p) => <MediaControl {...p} />} />
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<Linkify key={key} options={linkifyOpts}>
|
||||
{getRenderedBodyText(text, highlightRegex)}
|
||||
</Linkify>
|
||||
);
|
||||
}
|
||||
|
||||
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 <MessageEmptyContent />;
|
||||
return parse(sanitizeCustomHtml(customBody), htmlReactParserOptions);
|
||||
}
|
||||
if (body === '') return <MessageEmptyContent />;
|
||||
@@ -122,24 +139,12 @@ export function RenderBody({
|
||||
const definition = abbrMap.get(seg.termKey) ?? '';
|
||||
return <AbbreviationTerm key={seg.id} text={seg.text} definition={definition} />;
|
||||
}
|
||||
return (
|
||||
<Linkify key={seg.id} options={linkifyOpts}>
|
||||
{highlightRegex
|
||||
? highlightText(highlightRegex, scaleSystemEmoji(seg.text))
|
||||
: scaleSystemEmoji(seg.text)}
|
||||
</Linkify>
|
||||
);
|
||||
return renderLinkifiedBodyText(seg.text, linkifyOpts, highlightRegex, seg.id);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Linkify options={linkifyOpts}>
|
||||
{highlightRegex
|
||||
? highlightText(highlightRegex, scaleSystemEmoji(body))
|
||||
: scaleSystemEmoji(body)}
|
||||
</Linkify>
|
||||
);
|
||||
return renderLinkifiedBodyText(body, linkifyOpts, highlightRegex);
|
||||
}
|
||||
@@ -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<typeof import('jotai')>();
|
||||
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<typeof import('$utils/room')>();
|
||||
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(
|
||||
'<mx-reply><blockquote>quoted<script>alert(1)</script></blockquote></mx-reply>' +
|
||||
'<span data-mx-color="#ff0000" style="color:#00ff00">visible</span>' +
|
||||
'<img src="https://example.com/not-allowed.png" alt="blocked image" />'
|
||||
)
|
||||
);
|
||||
|
||||
render(
|
||||
<Reply
|
||||
room={{ roomId: '!room:example.com', getMember: () => 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(
|
||||
'<img data-mx-emoticon src="mxc://mozilla.org/ca2ed58example" alt="blobcat" title="blobcat" height="32" />'
|
||||
)
|
||||
);
|
||||
|
||||
const { container } = render(
|
||||
<Reply
|
||||
room={{ roomId: '!room:example.com', getMember: () => undefined } as any}
|
||||
replyEventId="$reply:example.com"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container.querySelector('img[src^="mxc://"]')).toBeNull();
|
||||
expect(warnSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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(/<br\s*\/?>/gi, ' ')
|
||||
.replaceAll(/<\/p>\s*<p[^>]*>/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 = <MessageBlockedContent />;
|
||||
} else if (badEncryption) {
|
||||
replyContent = <MessageBadEncryptedContent />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box direction="Row" gap="200" alignItems="Center" {...props} ref={ref}>
|
||||
{threadRootId && (
|
||||
@@ -261,11 +272,7 @@ export const Reply = as<'div', ReplyProps>(
|
||||
>
|
||||
{replyEvent !== undefined && !isPendingDecrypt ? (
|
||||
<Text size="T300" truncate>
|
||||
{(() => {
|
||||
if (isBlockedSender) return <MessageBlockedContent />;
|
||||
if (badEncryption) return <MessageBadEncryptedContent />;
|
||||
return bodyJSX;
|
||||
})()}
|
||||
{replyContent}
|
||||
</Text>
|
||||
) : (
|
||||
(isRedacted && <MessageDeletedContent />) || (
|
||||
|
||||
@@ -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', '<br>')
|
||||
? sanitizeText(originalBody).replaceAll('\n', '<br>')
|
||||
: sanitizeCustomHtml(originalFormattedBody);
|
||||
|
||||
newBodyHtml =
|
||||
`<div data-forward-marker>` +
|
||||
`<p>${sanitizeCustomHtml(bodyModifText)}</p>` +
|
||||
`<p>${sanitizeText(bodyModifText)}</p>` +
|
||||
`<blockquote>${safeHtml}</blockquote>` +
|
||||
`</div>`;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<HTMLDivElement, RoomInputProps>(
|
||||
/**
|
||||
* html escaped version of the display name
|
||||
*/
|
||||
const escapedName = sanitizeCustomHtml(perMessageProfile.name);
|
||||
const escapedName = sanitizeText(perMessageProfile.name);
|
||||
|
||||
const htmlPrefix = `<strong data-mx-profile-fallback>${escapedName}: </strong>`;
|
||||
|
||||
|
||||
@@ -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 = `<strong data-mx-profile-fallback>${escapedName}: </strong>`;
|
||||
if (!customHtml.startsWith(htmlPrefix)) {
|
||||
customHtml = htmlPrefix + customHtml;
|
||||
|
||||
@@ -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() {
|
||||
<Button
|
||||
onClick={() => {
|
||||
const newProfile: PerMessageProfile = {
|
||||
id: crypto.randomUUID(),
|
||||
id: generateShortId(5),
|
||||
name: 'New Profile',
|
||||
};
|
||||
addOrUpdatePerMessageProfile(mx, newProfile).then(() => {
|
||||
|
||||
@@ -23,8 +23,7 @@ function formatKey(key: string): string {
|
||||
return key
|
||||
.replace(/\bmod\b/g, isMac ? '⌘' : 'Ctrl')
|
||||
.replace(/\balt\b/gi, isMac ? '⌥' : 'Alt')
|
||||
.replace(/\bshift\b/gi, '⇧')
|
||||
.replace(/\+/g, '+');
|
||||
.replace(/\bshift\b/gi, '⇧');
|
||||
}
|
||||
|
||||
const SHORTCUT_CATEGORIES: ShortcutCategory[] = [
|
||||
|
||||
@@ -51,8 +51,8 @@ const FLAG_PAT = String.raw`(?:^|\s)-(\w+)\b`;
|
||||
const FLAG_REG = new RegExp(FLAG_PAT);
|
||||
const FLAG_REG_G = new RegExp(FLAG_PAT, 'g');
|
||||
|
||||
const ADDPMP_REGEX = /(\w+) (name=)?"?([\w\s]*)"? (avatar=)?([\w.:/]+)/;
|
||||
const USEPMP_REGEX = /^(\w+)\s*(-g)?(-o)?(-u)?\s*(\d+)?$/;
|
||||
const ADDPMP_REGEX = /(\S+) (name=)?"?([\w\s]*)"? (avatar=)?([\w.:/]+)/;
|
||||
const USEPMP_REGEX = /^(\S+)\s*(-g)?(-o)?(-u)?\s*(\d+)?$/;
|
||||
|
||||
export const splitPayloadContentAndFlags = (payload: string): [string, string | undefined] => {
|
||||
const flagMatch = new RegExp(FLAG_REG).exec(payload);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { sendFeedback } from '$utils/sendFeedbackToUser';
|
||||
import { MatrixClient, Room } from 'matrix-js-sdk';
|
||||
import { generateShortId } from '$utils/shortIdGen';
|
||||
|
||||
const pkMemberRenameRegex = /^(pk;member)\s+"?([\w\s]+)"?\s*rename\s+"?([\w\s]+)"?$/;
|
||||
const pkMemberNewRegex = /^(pk;member)\s+new\s+"?([\w\s]+)"?$/;
|
||||
@@ -90,7 +91,7 @@ export class PKitCommandMessageHandler {
|
||||
return;
|
||||
}
|
||||
const memberName = cmdParts[2];
|
||||
const generatedID = crypto.randomUUID();
|
||||
const generatedID = generateShortId(5);
|
||||
sendFeedback(
|
||||
`adding new member has been created with id: ${generatedID} and name ${memberName}`,
|
||||
this.room,
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import parse from 'html-react-parser';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { sanitizeCustomHtml } from '$utils/sanitize';
|
||||
import { getReactCustomHtmlParser, LINKIFY_OPTS } from './react-custom-html-parser';
|
||||
|
||||
function createMatrixClient() {
|
||||
return {
|
||||
getRoom: () => undefined,
|
||||
getUserId: () => '@me:example.com',
|
||||
mxcUrlToHttp: () => null,
|
||||
} as any;
|
||||
}
|
||||
|
||||
function renderParsedHtml(
|
||||
html: string,
|
||||
options: {
|
||||
sanitize?: boolean;
|
||||
mx?: any;
|
||||
} = {}
|
||||
) {
|
||||
const { sanitize = true, mx = createMatrixClient() } = options;
|
||||
const parserOptions = getReactCustomHtmlParser(mx, '!room:example.com', {
|
||||
linkifyOpts: LINKIFY_OPTS,
|
||||
});
|
||||
|
||||
return render(<div>{parse(sanitize ? sanitizeCustomHtml(html) : html, parserOptions)}</div>);
|
||||
}
|
||||
|
||||
describe('getReactCustomHtmlParser', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('translates Matrix color data attributes into rendered styles', () => {
|
||||
renderParsedHtml('<span data-mx-color="#ff0000" data-mx-bg-color="#00ff00">colored</span>');
|
||||
|
||||
expect(screen.getByText('colored')).toHaveStyle({
|
||||
color: 'rgb(255, 0, 0)',
|
||||
backgroundColor: 'rgb(0, 255, 0)',
|
||||
});
|
||||
});
|
||||
|
||||
it('drops incoming style attributes even if unsanitized html reaches the parser', () => {
|
||||
renderParsedHtml(
|
||||
'<span style="background-color:#00ff00" data-mx-color="#ff0000">styled</span>',
|
||||
{ sanitize: false }
|
||||
);
|
||||
|
||||
const styled = screen.getByText('styled');
|
||||
|
||||
expect(styled).toHaveStyle({
|
||||
color: 'rgb(255, 0, 0)',
|
||||
});
|
||||
expect(styled).not.toHaveStyle({
|
||||
backgroundColor: 'rgb(0, 255, 0)',
|
||||
});
|
||||
});
|
||||
|
||||
it('renders a readable fallback for unresolved legacy emote MXC images', () => {
|
||||
const { container } = renderParsedHtml(
|
||||
'<img data-mx-emoticon src="mxc://example.org/emote" alt="blobcat" title="blobcat" height="32" />'
|
||||
);
|
||||
|
||||
expect(screen.getByText(':blobcat:')).toBeInTheDocument();
|
||||
expect(container.querySelector('img[src^="mxc://"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('renders a readable fallback for unresolved non-emote MXC images', () => {
|
||||
const { container } = renderParsedHtml(
|
||||
'<img src="mxc://example.org/image" alt="media" title="media" />'
|
||||
);
|
||||
|
||||
expect(screen.getByText('media')).toBeInTheDocument();
|
||||
expect(container.querySelector('img[src^="mxc://"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('renders unresolved MXC fallbacks without emitting debug logs', () => {
|
||||
const logSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
|
||||
renderParsedHtml('<img src="mxc://example.org/image" alt="media" title="media" />');
|
||||
|
||||
expect(logSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
/* eslint-disable jsx-a11y/alt-text */
|
||||
import {
|
||||
CSSProperties,
|
||||
ComponentPropsWithoutRef,
|
||||
lazy,
|
||||
ReactEventHandler,
|
||||
@@ -35,6 +36,7 @@ import { EMOJI_PATTERN, sanitizeForRegex, URL_NEG_LB } from '$utils/regex';
|
||||
import { findAndReplace } from '$utils/findAndReplace';
|
||||
import { onEnterOrSpace } from '$utils/keyboard';
|
||||
import { copyToClipboard } from '$utils/dom';
|
||||
import { isMatrixHexColor } from '$utils/matrixHtml';
|
||||
import { useTimeoutToggle } from '$hooks/useTimeoutToggle';
|
||||
import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze';
|
||||
import {
|
||||
@@ -68,6 +70,42 @@ export const safeDecodeUrl = (url: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const getMatrixColorStyle = (attribs: Record<string, string>): CSSProperties | undefined => {
|
||||
const color = attribs['data-mx-color'];
|
||||
const backgroundColor = attribs['data-mx-bg-color'];
|
||||
|
||||
const style: CSSProperties = {};
|
||||
|
||||
if (typeof color === 'string' && isMatrixHexColor(color)) {
|
||||
style.color = color;
|
||||
}
|
||||
|
||||
if (typeof backgroundColor === 'string' && isMatrixHexColor(backgroundColor)) {
|
||||
style.backgroundColor = backgroundColor;
|
||||
}
|
||||
|
||||
return Object.keys(style).length > 0 ? style : undefined;
|
||||
};
|
||||
|
||||
const stripIncomingStyle = (
|
||||
attribs: Record<string, string>
|
||||
): Omit<ReturnType<typeof attributesToProps>, 'style'> => {
|
||||
const { style, ...props } = attributesToProps(attribs);
|
||||
|
||||
return props;
|
||||
};
|
||||
|
||||
const ensureNoopenerRel = (rel: unknown): string => {
|
||||
if (typeof rel !== 'string') return 'noopener';
|
||||
|
||||
const parts = rel.split(/\s+/).filter(Boolean);
|
||||
if (!parts.includes('noopener')) {
|
||||
parts.push('noopener');
|
||||
}
|
||||
|
||||
return parts.join(' ');
|
||||
};
|
||||
|
||||
export const makeMentionCustomProps = (
|
||||
handleMentionClick?: ReactEventHandler<HTMLElement>,
|
||||
content?: string
|
||||
@@ -363,7 +401,8 @@ export const getReactCustomHtmlParser = (
|
||||
if (domNode instanceof Element && 'name' in domNode) {
|
||||
const { name, attribs, children, parent } = domNode;
|
||||
const renderChildren = () => domToReact(children as any, opts);
|
||||
const props = attributesToProps(attribs);
|
||||
const props = stripIncomingStyle(attribs);
|
||||
const matrixColorStyle = getMatrixColorStyle(attribs);
|
||||
|
||||
if (name === 'h1') {
|
||||
return (
|
||||
@@ -494,8 +533,13 @@ export const getReactCustomHtmlParser = (
|
||||
if (name === 'a' && typeof props.href === 'string') {
|
||||
const encodedHref = props.href;
|
||||
const decodedHref = encodedHref && safeDecodeUrl(encodedHref);
|
||||
const anchorProps = {
|
||||
...props,
|
||||
rel: ensureNoopenerRel(props.rel),
|
||||
};
|
||||
|
||||
if (!decodedHref || !testMatrixTo(decodedHref)) {
|
||||
return undefined;
|
||||
return <a {...anchorProps}>{renderChildren()}</a>;
|
||||
}
|
||||
|
||||
const content = children.find((child) => !(child instanceof DOMText))
|
||||
@@ -523,13 +567,21 @@ export const getReactCustomHtmlParser = (
|
||||
onClick={params.handleSpoilerClick}
|
||||
className={css.Spoiler()}
|
||||
aria-pressed
|
||||
style={{ cursor: 'pointer' }}
|
||||
style={{ ...matrixColorStyle, cursor: 'pointer' }}
|
||||
>
|
||||
{renderChildren()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (name === 'span' && matrixColorStyle) {
|
||||
return (
|
||||
<span {...props} style={matrixColorStyle}>
|
||||
{renderChildren()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (name === 'img') {
|
||||
// Guard: img without a src survives sanitisation (fix for crash #1731)
|
||||
// but we can't convert it — skip rendering rather than passing
|
||||
@@ -537,6 +589,8 @@ export const getReactCustomHtmlParser = (
|
||||
if (!props.src) return null;
|
||||
|
||||
const htmlSrc = mxcUrlToHttp(mx, props.src, params.useAuthentication) ?? undefined;
|
||||
const fallbackLabel = props.alt || props.title || '[media]';
|
||||
const failedToResolveMxc = props.src.startsWith('mxc://') && !htmlSrc;
|
||||
|
||||
// Non-mxc images were already converted to <a> links by the sanitiser,
|
||||
// but handle the edge case defensively here too.
|
||||
@@ -632,6 +686,14 @@ export const getReactCustomHtmlParser = (
|
||||
);
|
||||
}
|
||||
|
||||
if (failedToResolveMxc) {
|
||||
return (
|
||||
<span title={`Failed to load media${props.alt ? `: ${props.alt}` : ''}`}>
|
||||
{fallbackLabel}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (htmlSrc)
|
||||
return (
|
||||
<FallbackImg
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export const MATRIX_HEX_COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;
|
||||
|
||||
export function isMatrixHexColor(value: string): boolean {
|
||||
return MATRIX_HEX_COLOR_REGEX.test(value);
|
||||
}
|
||||
+111
-97
@@ -1,124 +1,138 @@
|
||||
// Tests for sanitizeCustomHtml — security-critical: strips dangerous content from
|
||||
// user-supplied Matrix message HTML before rendering.
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeCustomHtml } from './sanitize';
|
||||
|
||||
describe('sanitizeCustomHtml – tag allowlist', () => {
|
||||
it('passes through permitted tags', () => {
|
||||
expect(sanitizeCustomHtml('<b>bold</b>')).toBe('<b>bold</b>');
|
||||
expect(sanitizeCustomHtml('<i>italic</i>')).toBe('<i>italic</i>');
|
||||
expect(sanitizeCustomHtml('<code>snippet</code>')).toBe('<code>snippet</code>');
|
||||
});
|
||||
|
||||
it('strips disallowed tags but keeps their text content', () => {
|
||||
const result = sanitizeCustomHtml('<marquee>text</marquee>');
|
||||
expect(result).not.toContain('<marquee');
|
||||
expect(result).toContain('text');
|
||||
});
|
||||
|
||||
it('strips <mx-reply> and its content entirely', () => {
|
||||
const result = sanitizeCustomHtml('<mx-reply>quoted message</mx-reply>remaining');
|
||||
expect(result).not.toContain('quoted message');
|
||||
expect(result).toContain('remaining');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – XSS prevention', () => {
|
||||
it('strips <script> tags and their content', () => {
|
||||
const result = sanitizeCustomHtml("<script>alert('xss')</script>");
|
||||
expect(result).not.toContain('<script');
|
||||
expect(result).not.toContain('alert');
|
||||
});
|
||||
|
||||
it('strips inline event handlers', () => {
|
||||
const result = sanitizeCustomHtml('<b onclick="alert(1)">click me</b>');
|
||||
expect(result).not.toContain('onclick');
|
||||
expect(result).toContain('click me');
|
||||
});
|
||||
|
||||
it('strips javascript: href on anchor tags', () => {
|
||||
const result = sanitizeCustomHtml('<a href="javascript:alert(\'xss\')">link</a>');
|
||||
expect(result).not.toMatch(/javascript:/);
|
||||
});
|
||||
|
||||
it('strips data: href on anchor tags', () => {
|
||||
describe('sanitizeCustomHtml', () => {
|
||||
it('keeps permitted Matrix v1.18 tags', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<a href="data:text/html,<script>alert(1)</script>">link</a>'
|
||||
'<details><summary>Summary</summary><table><tbody><tr><td><del>text</del></td></tr></tbody></table></details>'
|
||||
);
|
||||
expect(result).not.toContain('data:');
|
||||
|
||||
expect(result).toContain('<details>');
|
||||
expect(result).toContain('<summary>Summary</summary>');
|
||||
expect(result).toContain('<table>');
|
||||
expect(result).toContain('<del>text</del>');
|
||||
});
|
||||
|
||||
it('strips vbscript: href', () => {
|
||||
const result = sanitizeCustomHtml('<a href="vbscript:msgbox(1)">link</a>');
|
||||
expect(result).not.toContain('vbscript:');
|
||||
it('strips tags outside the Matrix v1.18 allowlist', () => {
|
||||
const result = sanitizeCustomHtml('<font color="#ff0000">font</font><strike>strike</strike>');
|
||||
|
||||
expect(result).not.toContain('<font');
|
||||
expect(result).not.toContain('<strike');
|
||||
expect(result).toContain('font');
|
||||
expect(result).toContain('strike');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – link transformer', () => {
|
||||
it('adds rel and target to http links', () => {
|
||||
const result = sanitizeCustomHtml('<a href="https://example.com">link</a>');
|
||||
expect(result).toContain('rel="noreferrer noopener"');
|
||||
expect(result).toContain('target="_blank"');
|
||||
it('strips mx-reply and its contents entirely', () => {
|
||||
const result = sanitizeCustomHtml('<mx-reply>quoted message</mx-reply><p>remaining</p>');
|
||||
|
||||
expect(result).not.toContain('quoted message');
|
||||
expect(result).toBe('<p>remaining</p>');
|
||||
});
|
||||
|
||||
it('passes through existing href for http links', () => {
|
||||
const result = sanitizeCustomHtml('<a href="https://example.com">link</a>');
|
||||
expect(result).toContain('href="https://example.com"');
|
||||
it('does not accept style attributes anywhere', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<span style="color:#00ff00" data-mx-color="#ff0000">text</span><p style="color:#00ff00">para</p>'
|
||||
);
|
||||
|
||||
expect(result).not.toContain('style=');
|
||||
expect(result).toContain('data-mx-color="#ff0000"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – image transformer', () => {
|
||||
it('keeps <img> tags with mxc:// src', () => {
|
||||
const result = sanitizeCustomHtml('<img src="mxc://example.com/abc" alt="img" />');
|
||||
expect(result).toContain('<img');
|
||||
expect(result).toContain('src="mxc://example.com/abc"');
|
||||
it('only keeps the permitted attributes on each tag', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<span data-mx-color="#ff0000" data-mx-bg-color="#00ff00" data-mx-spoiler="spoiler" data-mx-maths="x" data-md="nope">span</span>' +
|
||||
'<a href="https://example.com" target="_blank" rel="noreferrer">link</a>' +
|
||||
'<ol start="2" type="A"><li>item</li></ol>' +
|
||||
'<code class="language-typescript extra">code</code>' +
|
||||
'<div data-mx-maths="x" data-md="nope">maths</div>'
|
||||
);
|
||||
|
||||
expect(result).toContain('data-mx-color="#ff0000"');
|
||||
expect(result).toContain('data-mx-bg-color="#00ff00"');
|
||||
expect(result).toContain('data-mx-spoiler="spoiler"');
|
||||
expect(result).toContain('data-mx-maths="x"');
|
||||
expect(result).not.toContain('data-md=');
|
||||
expect(result).toContain('<a href="https://example.com" target="_blank">link</a>');
|
||||
expect(result).not.toContain('rel=');
|
||||
expect(result).toContain('<ol start="2">');
|
||||
expect(result).not.toContain('type=');
|
||||
expect(result).not.toContain('class=');
|
||||
expect(result).toContain('<div data-mx-maths="x">maths</div>');
|
||||
});
|
||||
|
||||
it('converts <img> with https:// src to a safe <a> link', () => {
|
||||
const result = sanitizeCustomHtml('<img src="https://example.com/image.jpg" alt="photo" />');
|
||||
expect(result).not.toContain('<img');
|
||||
expect(result).toContain('<a');
|
||||
expect(result).toContain('https://example.com/image.jpg');
|
||||
expect(result).toContain('rel="noreferrer noopener"');
|
||||
it('preserves a code class only when every class starts with language-', () => {
|
||||
expect(sanitizeCustomHtml('<code class="language-typescript">code</code>')).toContain(
|
||||
'class="language-typescript"'
|
||||
);
|
||||
expect(
|
||||
sanitizeCustomHtml('<code class="language-typescript language-js">code</code>')
|
||||
).toContain('class="language-typescript language-js"');
|
||||
expect(sanitizeCustomHtml('<code class="language-typescript extra">code</code>')).not.toContain(
|
||||
'class='
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – style attribute restrictions', () => {
|
||||
// The span transformer unconditionally overwrites the style attribute with
|
||||
// values derived from data-mx-color / data-mx-bg-color. Inline CSS is always
|
||||
// discarded; colors must come from the data-mx-* attributes.
|
||||
it('converts data-mx-color to a CSS color style on span', () => {
|
||||
const result = sanitizeCustomHtml('<span data-mx-color="#ff0000">text</span>');
|
||||
// sanitize-html may normalise whitespace around the colon
|
||||
expect(result).toMatch(/color:\s*#ff0000/);
|
||||
|
||||
it('keeps only valid absolute href schemes on links', () => {
|
||||
expect(sanitizeCustomHtml('<a href="https://example.com">https</a>')).toContain(
|
||||
'href="https://example.com"'
|
||||
);
|
||||
expect(sanitizeCustomHtml('<a href="mailto:[email protected]">mail</a>')).toContain(
|
||||
'href="mailto:[email protected]"'
|
||||
);
|
||||
expect(sanitizeCustomHtml('<a href="magnet:?xt=urn:btih:abcdef">magnet</a>')).toContain(
|
||||
'href="magnet:?xt=urn:btih:abcdef"'
|
||||
);
|
||||
|
||||
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>');
|
||||
});
|
||||
|
||||
it('discards plain inline style on span (use data-mx-color instead)', () => {
|
||||
const result = sanitizeCustomHtml('<span style="color: #ff0000">text</span>');
|
||||
// The transformer replaces style with data-mx-* values; no data-mx-color
|
||||
// present here, so style ends up stripped by the allowedStyles check.
|
||||
expect(result).not.toContain('color: #ff0000');
|
||||
it('keeps only mxc image sources', () => {
|
||||
const allowed = sanitizeCustomHtml('<img src="mxc://example.com/abc123" alt="img" />');
|
||||
const blocked = sanitizeCustomHtml('<img src="https://example.com/image.jpg" alt="img" />');
|
||||
|
||||
expect(allowed).toContain('<img');
|
||||
expect(allowed).toContain('src="mxc://example.com/abc123"');
|
||||
expect(blocked).not.toContain('<img');
|
||||
});
|
||||
|
||||
it('strips non-hex values from data-mx-color', () => {
|
||||
const result = sanitizeCustomHtml('<span data-mx-color="red">text</span>');
|
||||
expect(result).not.toContain('color: red');
|
||||
it('preserves legacy MSC2545 custom-emote markers on mxc images', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<img data-mx-emoticon src="mxc://example.com/abc123" alt="blobcat" title="blobcat" height="32" />'
|
||||
);
|
||||
|
||||
expect(result).toContain('data-mx-emoticon');
|
||||
expect(result).toContain('src="mxc://example.com/abc123"');
|
||||
expect(result).toContain('alt="blobcat"');
|
||||
});
|
||||
|
||||
it('strips disallowed CSS properties', () => {
|
||||
const result = sanitizeCustomHtml('<span style="position: fixed">text</span>');
|
||||
expect(result).not.toContain('position');
|
||||
it('restores only one validated image src after masking duplicate image source attributes', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<img src="mxc://example.com/primary" src="mxc://example.com/secondary" srcset="mxc://example.com/secondary 1x" alt="img" />'
|
||||
);
|
||||
|
||||
expect(result).toContain('src="mxc://example.com/primary"');
|
||||
expect(result).not.toContain('mxc://example.com/secondary');
|
||||
expect(result).not.toContain('srcset=');
|
||||
expect(result.match(/\ssrc=/g)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – code block class handling', () => {
|
||||
it('preserves language class on code blocks', () => {
|
||||
const result = sanitizeCustomHtml('<code class="language-typescript">const x = 1;</code>');
|
||||
expect(result).toContain('class="language-typescript"');
|
||||
it('drops invalid Matrix color attributes instead of translating them to style', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<span data-mx-color="red" data-mx-bg-color="#123">text</span>'
|
||||
);
|
||||
|
||||
expect(result).toBe('<span>text</span>');
|
||||
});
|
||||
|
||||
it('strips arbitrary classes not matching language-*', () => {
|
||||
const result = sanitizeCustomHtml('<code class="evil-class">code</code>');
|
||||
expect(result).not.toContain('evil-class');
|
||||
it('enforces the 100-level nesting limit', () => {
|
||||
const deepHtml = `${'<div>'.repeat(101)}text${'</div>'.repeat(101)}`;
|
||||
const result = sanitizeCustomHtml(deepHtml);
|
||||
|
||||
expect(result).toContain('text');
|
||||
expect((result.match(/<div>/g) ?? []).length).toBeLessThanOrEqual(100);
|
||||
});
|
||||
});
|
||||
+271
-113
@@ -1,9 +1,10 @@
|
||||
import sanitizeHtml, { Transformer } from 'sanitize-html';
|
||||
import DOMPurify from 'dompurify';
|
||||
import { isMatrixHexColor } from './matrixHtml';
|
||||
|
||||
const MAX_TAG_NESTING = 100;
|
||||
const INTERNAL_IMG_SRC_ATTR = 'data-sable-img-src';
|
||||
|
||||
const permittedHtmlTags = [
|
||||
'font',
|
||||
'del',
|
||||
'h1',
|
||||
'h2',
|
||||
@@ -24,7 +25,6 @@ const permittedHtmlTags = [
|
||||
'u',
|
||||
'strong',
|
||||
'em',
|
||||
'strike',
|
||||
's',
|
||||
'code',
|
||||
'hr',
|
||||
@@ -42,123 +42,27 @@ const permittedHtmlTags = [
|
||||
'img',
|
||||
'details',
|
||||
'summary',
|
||||
];
|
||||
|
||||
const urlSchemes = ['https', 'http', 'ftp', 'mailto', 'magnet'];
|
||||
] as const;
|
||||
|
||||
const permittedTagToAttributes = {
|
||||
font: ['style', 'data-mx-bg-color', 'data-mx-color', 'color'],
|
||||
span: [
|
||||
'style',
|
||||
'data-mx-bg-color',
|
||||
'data-mx-color',
|
||||
'data-mx-spoiler',
|
||||
'data-mx-maths',
|
||||
'data-mx-pill',
|
||||
'data-mx-ping',
|
||||
'data-md',
|
||||
],
|
||||
span: ['data-mx-bg-color', 'data-mx-color', 'data-mx-spoiler', 'data-mx-maths'],
|
||||
a: ['target', 'href'],
|
||||
img: ['width', 'height', 'alt', 'title', 'src', 'data-mx-emoticon'], // data-mx-emoticon is for MSC2545
|
||||
ol: ['start'],
|
||||
code: ['class'],
|
||||
div: ['data-mx-maths'],
|
||||
blockquote: ['data-md'],
|
||||
h1: ['data-md'],
|
||||
h2: ['data-md'],
|
||||
h3: ['data-md'],
|
||||
h4: ['data-md'],
|
||||
h5: ['data-md'],
|
||||
h6: ['data-md'],
|
||||
pre: ['data-md', 'class'],
|
||||
ol: ['start', 'type', 'data-md'],
|
||||
ul: ['data-md'],
|
||||
a: ['name', 'target', 'href', 'rel', 'data-md'],
|
||||
img: ['width', 'height', 'alt', 'title', 'src', 'data-mx-emoticon'],
|
||||
code: ['class', 'data-md'],
|
||||
strong: ['data-md'],
|
||||
i: ['data-md'],
|
||||
em: ['data-md'],
|
||||
u: ['data-md'],
|
||||
s: ['data-md'],
|
||||
del: ['data-md'],
|
||||
sub: ['data-md'],
|
||||
hr: ['data-md'],
|
||||
};
|
||||
} as const satisfies Record<string, readonly string[]>;
|
||||
|
||||
const transformFontTag: Transformer = (tagName, attribs) => ({
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
style: `background-color: ${attribs['data-mx-bg-color']}; color: ${attribs['data-mx-color']}`,
|
||||
},
|
||||
});
|
||||
const permittedHtmlAttributes = Array.from(new Set(Object.values(permittedTagToAttributes).flat()));
|
||||
|
||||
const transformSpanTag: Transformer = (tagName, attribs) => ({
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
style: `background-color: ${attribs['data-mx-bg-color']}; color: ${attribs['data-mx-color']}`,
|
||||
},
|
||||
});
|
||||
const allowedLinkSchemes = new Set(['https', 'http', 'ftp', 'mailto', 'magnet']);
|
||||
const forbiddenContentTags = ['mx-reply', 'script', 'style', 'textarea', 'option', 'noscript'];
|
||||
|
||||
const transformATag: Transformer = (tagName, attribs) => ({
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
rel: 'noreferrer noopener',
|
||||
target: '_blank',
|
||||
},
|
||||
});
|
||||
const codeLanguageClassRegex = /^language-[A-Za-z0-9_-]+$/;
|
||||
const orderedListStartRegex = /^-?\d+$/;
|
||||
const allowedUriRegex = /^(?:https?|ftp|mailto|magnet|mxc):/i;
|
||||
|
||||
const transformImgTag: Transformer = (tagName, attribs) => {
|
||||
const { src } = attribs;
|
||||
if (typeof src === 'string' && src.startsWith('mxc://') === false) {
|
||||
return {
|
||||
tagName: 'a',
|
||||
attribs: {
|
||||
href: src,
|
||||
rel: 'noreferrer noopener',
|
||||
target: '_blank',
|
||||
},
|
||||
text: attribs.alt || src,
|
||||
};
|
||||
}
|
||||
return {
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const sanitizeCustomHtml = (customHtml: string): string =>
|
||||
sanitizeHtml(customHtml, {
|
||||
allowedTags: permittedHtmlTags,
|
||||
allowedAttributes: permittedTagToAttributes,
|
||||
disallowedTagsMode: 'discard',
|
||||
allowedSchemes: urlSchemes,
|
||||
allowedSchemesByTag: {
|
||||
a: urlSchemes,
|
||||
},
|
||||
allowedSchemesAppliedToAttributes: ['href'],
|
||||
allowProtocolRelative: false,
|
||||
allowedClasses: {
|
||||
code: ['language-*'],
|
||||
},
|
||||
allowedStyles: {
|
||||
'*': {
|
||||
color: [/^#(?:[0-9a-fA-F]{3}){1,2}$/],
|
||||
'background-color': [/^#(?:[0-9a-fA-F]{3}){1,2}$/],
|
||||
},
|
||||
},
|
||||
transformTags: {
|
||||
font: transformFontTag,
|
||||
span: transformSpanTag,
|
||||
a: transformATag,
|
||||
img: transformImgTag,
|
||||
},
|
||||
nonTextTags: ['style', 'script', 'textarea', 'option', 'noscript', 'mx-reply'],
|
||||
nestingLimit: MAX_TAG_NESTING,
|
||||
});
|
||||
|
||||
export const sanitizeText = (body: string) => {
|
||||
export function sanitizeText(body: string): string {
|
||||
const tagsToReplace: Record<string, string> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
@@ -166,5 +70,259 @@ export const sanitizeText = (body: string) => {
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
};
|
||||
|
||||
return body.replace(/[&<>'"]/g, (tag) => tagsToReplace[tag] || tag);
|
||||
}
|
||||
|
||||
function tagAllowsAttribute(tagName: string, attrName: string): boolean {
|
||||
const allowedAttributes =
|
||||
permittedTagToAttributes[tagName as keyof typeof permittedTagToAttributes];
|
||||
|
||||
return allowedAttributes ? (allowedAttributes as readonly string[]).includes(attrName) : false;
|
||||
}
|
||||
|
||||
function isAllowedAbsoluteLink(value: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
return allowedLinkSchemes.has(parsed.protocol.slice(0, -1));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isAllowedMxcUri(value: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
return (
|
||||
parsed.protocol === 'mxc:' &&
|
||||
parsed.host.length > 0 &&
|
||||
parsed.pathname.length > 1 &&
|
||||
parsed.username === '' &&
|
||||
parsed.password === '' &&
|
||||
parsed.search === '' &&
|
||||
parsed.hash === ''
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCodeClasses(attrValue: string): string | undefined {
|
||||
const classes = attrValue.split(/\s+/).filter(Boolean);
|
||||
if (
|
||||
classes.length === 0 ||
|
||||
classes.some((className) => !codeLanguageClassRegex.test(className))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return classes.join(' ');
|
||||
}
|
||||
|
||||
function getValidatedAttributeValue(
|
||||
tagName: string,
|
||||
attrName: string,
|
||||
attrValue: string
|
||||
): string | undefined {
|
||||
if (attrName === 'style') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (
|
||||
(attrName === 'data-mx-color' || attrName === 'data-mx-bg-color') &&
|
||||
!isMatrixHexColor(attrValue)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (tagName === 'a' && attrName === 'href' && !isAllowedAbsoluteLink(attrValue)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (tagName === 'img' && attrName === 'src' && !isAllowedMxcUri(attrValue)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (tagName === 'ol' && attrName === 'start' && !orderedListStartRegex.test(attrValue)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (tagName === 'code' && attrName === 'class') {
|
||||
return normalizeCodeClasses(attrValue);
|
||||
}
|
||||
|
||||
return attrValue;
|
||||
}
|
||||
|
||||
function getValidatedProtectedImageSource(
|
||||
sourceId: string | null,
|
||||
protectedSources?: Map<string, string>
|
||||
): string | undefined {
|
||||
const rawSrc = sourceId ? protectedSources?.get(sourceId) : undefined;
|
||||
|
||||
return typeof rawSrc === 'string' ? getValidatedAttributeValue('img', 'src', rawSrc) : undefined;
|
||||
}
|
||||
|
||||
function protectImageSources(customHtml: string): {
|
||||
protectedHtml: string;
|
||||
protectedSources: Map<string, string>;
|
||||
} {
|
||||
const protectedSources = new Map<string, string>();
|
||||
const protectedHtml = customHtml.replace(/<img\b[^>]*>/gi, (imgTag) => {
|
||||
let protectedSourceId: string | undefined;
|
||||
|
||||
const strippedTag = imgTag.replace(
|
||||
/\s(src|srcset)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi,
|
||||
(_match, attrName: string, _value, doubleQuoted, singleQuoted, bareValue) => {
|
||||
if (attrName.toLowerCase() !== 'src') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (protectedSourceId !== undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const rawSrc = doubleQuoted ?? singleQuoted ?? bareValue ?? '';
|
||||
protectedSourceId = `${protectedSources.size}`;
|
||||
protectedSources.set(protectedSourceId, rawSrc);
|
||||
|
||||
return ` ${INTERNAL_IMG_SRC_ATTR}="${protectedSourceId}"`;
|
||||
}
|
||||
);
|
||||
|
||||
return strippedTag;
|
||||
});
|
||||
|
||||
return {
|
||||
protectedHtml,
|
||||
protectedSources,
|
||||
};
|
||||
}
|
||||
|
||||
function restoreProtectedImageSources(
|
||||
sanitizedHtml: string,
|
||||
protectedSources: Map<string, string>
|
||||
): string {
|
||||
return sanitizedHtml.replace(
|
||||
new RegExp(`\\s${INTERNAL_IMG_SRC_ATTR}="([^"]+)"`, 'g'),
|
||||
(_match, sourceId: string) => {
|
||||
const validatedSrc = getValidatedProtectedImageSource(sourceId, protectedSources);
|
||||
if (!validatedSrc) return '';
|
||||
|
||||
return ` src="${sanitizeText(validatedSrc)}"`;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const enforceNestingLimit = (fragment: DocumentFragment): void => {
|
||||
const overlyNestedElements: Array<{ depth: number; element: Element }> = [];
|
||||
|
||||
const collect = (node: ParentNode, depth: number) => {
|
||||
Array.from(node.childNodes).forEach((child) => {
|
||||
if (!(child instanceof Element)) return;
|
||||
|
||||
const childDepth = depth + 1;
|
||||
if (childDepth > MAX_TAG_NESTING) {
|
||||
overlyNestedElements.push({ depth: childDepth, element: child });
|
||||
}
|
||||
|
||||
collect(child, childDepth);
|
||||
});
|
||||
};
|
||||
|
||||
collect(fragment, 0);
|
||||
|
||||
overlyNestedElements
|
||||
.sort((a, b) => b.depth - a.depth)
|
||||
.forEach(({ element }) => {
|
||||
if (!element.parentNode) return;
|
||||
element.replaceWith(...Array.from(element.childNodes));
|
||||
});
|
||||
};
|
||||
|
||||
const pruneInvalidEmptyElements = (
|
||||
fragment: DocumentFragment,
|
||||
protectedSources?: Map<string, string>
|
||||
): void => {
|
||||
fragment.querySelectorAll('img').forEach((img) => {
|
||||
const validatedProtectedSource = getValidatedProtectedImageSource(
|
||||
img.getAttribute(INTERNAL_IMG_SRC_ATTR),
|
||||
protectedSources
|
||||
);
|
||||
|
||||
if (!img.getAttribute('src') && !validatedProtectedSource) {
|
||||
img.remove();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const sanitizeCustomHtml = (customHtml: string): string => {
|
||||
if (typeof window === 'undefined') {
|
||||
return sanitizeText(customHtml);
|
||||
}
|
||||
|
||||
const { protectedHtml, protectedSources } = protectImageSources(customHtml);
|
||||
const purify = DOMPurify(window);
|
||||
const allowedHtmlAttributes = [...permittedHtmlAttributes, INTERNAL_IMG_SRC_ATTR];
|
||||
|
||||
purify.addHook('uponSanitizeAttribute', (currentNode, hookEvent) => {
|
||||
const tagName = currentNode.tagName.toLowerCase();
|
||||
const attrName = hookEvent.attrName.toLowerCase();
|
||||
|
||||
if (tagName === 'img' && attrName === INTERNAL_IMG_SRC_ATTR) {
|
||||
if (!protectedSources.has(hookEvent.attrValue)) {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.keepAttr = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.forceKeepAttr = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!tagAllowsAttribute(tagName, attrName)) {
|
||||
// DOMPurify exposes attribute decisions by mutating the hook event.
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.keepAttr = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const validatedAttrValue = getValidatedAttributeValue(tagName, attrName, hookEvent.attrValue);
|
||||
if (validatedAttrValue === undefined) {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.keepAttr = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.attrValue = validatedAttrValue;
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.forceKeepAttr = true;
|
||||
});
|
||||
|
||||
const sanitizedNode = purify.sanitize(protectedHtml, {
|
||||
ALLOWED_TAGS: [...permittedHtmlTags],
|
||||
ALLOWED_ATTR: allowedHtmlAttributes,
|
||||
ALLOW_ARIA_ATTR: false,
|
||||
ALLOW_DATA_ATTR: true,
|
||||
FORBID_ATTR: ['style'],
|
||||
FORBID_TAGS: ['mx-reply'],
|
||||
FORBID_CONTENTS: forbiddenContentTags,
|
||||
KEEP_CONTENT: true,
|
||||
ALLOWED_URI_REGEXP: allowedUriRegex,
|
||||
RETURN_DOM_FRAGMENT: true,
|
||||
});
|
||||
|
||||
if (!(sanitizedNode instanceof window.DocumentFragment)) {
|
||||
return sanitizeText(customHtml);
|
||||
}
|
||||
|
||||
const fragment = sanitizedNode;
|
||||
enforceNestingLimit(fragment);
|
||||
pruneInvalidEmptyElements(fragment, protectedSources);
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.append(fragment);
|
||||
return restoreProtectedImageSources(container.innerHTML, protectedSources);
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
export function generateShortId(length: number): string {
|
||||
const uuid = crypto.randomUUID();
|
||||
return uuid.replaceAll('-', '').substring(0, length);
|
||||
}
|
||||
Reference in new issue
Block a user