Merge branch 'develop' into florianduros/tooltip-update
This commit is contained in:
@@ -17,32 +17,25 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { LegacyRef, ReactElement, ReactNode } from "react";
|
||||
import React, { LegacyRef, ReactNode } from "react";
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
import classNames from "classnames";
|
||||
import EMOJIBASE_REGEX from "emojibase-regex";
|
||||
import { merge } from "lodash";
|
||||
import katex from "katex";
|
||||
import { decode } from "html-entities";
|
||||
import { IContent } from "matrix-js-sdk/src/matrix";
|
||||
import { Optional } from "matrix-events-sdk";
|
||||
import _Linkify from "linkify-react";
|
||||
import escapeHtml from "escape-html";
|
||||
import GraphemeSplitter from "graphemer";
|
||||
import { getEmojiFromUnicode } from "@matrix-org/emojibase-bindings";
|
||||
|
||||
import {
|
||||
_linkifyElement,
|
||||
_linkifyString,
|
||||
ELEMENT_URL_PATTERN,
|
||||
options as linkifyMatrixOptions,
|
||||
} from "./linkify-matrix";
|
||||
import { IExtendedSanitizeOptions } from "./@types/sanitize-html";
|
||||
import SettingsStore from "./settings/SettingsStore";
|
||||
import { tryTransformPermalinkToLocalHref } from "./utils/permalinks/Permalinks";
|
||||
import { mediaFromMxc } from "./customisations/Media";
|
||||
import { stripHTMLReply, stripPlainReply } from "./utils/Reply";
|
||||
import { PERMITTED_URL_SCHEMES } from "./utils/UrlUtils";
|
||||
import { sanitizeHtmlParams, transformTags } from "./Linkify";
|
||||
|
||||
export { Linkify, linkifyElement, linkifyAndSanitizeHtml } from "./Linkify";
|
||||
|
||||
// Anything outside the basic multilingual plane will be a surrogate pair
|
||||
const SURROGATE_PAIR_PATTERN = /([\ud800-\udbff])([\udc00-\udfff])/;
|
||||
@@ -58,10 +51,6 @@ const EMOJI_SEPARATOR_REGEX = /[\u200D\u200B\s]|\uFE0F/g;
|
||||
|
||||
const BIGEMOJI_REGEX = new RegExp(`^(${EMOJIBASE_REGEX.source})+$`, "i");
|
||||
|
||||
const COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;
|
||||
|
||||
const MEDIA_API_MXC_REGEX = /\/_matrix\/media\/r0\/(?:download|thumbnail)\/(.+?)\/(.+?)(?:[?/]|$)/;
|
||||
|
||||
/*
|
||||
* Return true if the given string contains emoji
|
||||
* Uses a much, much simpler regex than emojibase's so will give false
|
||||
@@ -120,182 +109,6 @@ export function isUrlPermitted(inputUrl: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
const transformTags: IExtendedSanitizeOptions["transformTags"] = {
|
||||
// custom to matrix
|
||||
// add blank targets to all hyperlinks except vector URLs
|
||||
"a": function (tagName: string, attribs: sanitizeHtml.Attributes) {
|
||||
if (attribs.href) {
|
||||
attribs.target = "_blank"; // by default
|
||||
|
||||
const transformed = tryTransformPermalinkToLocalHref(attribs.href); // only used to check if it is a link that can be handled locally
|
||||
if (
|
||||
transformed !== attribs.href || // it could be converted so handle locally symbols e.g. @user:server.tdl, matrix: and matrix.to
|
||||
attribs.href.match(ELEMENT_URL_PATTERN) // for https links to Element domains
|
||||
) {
|
||||
delete attribs.target;
|
||||
}
|
||||
} else {
|
||||
// Delete the href attrib if it is falsy
|
||||
delete attribs.href;
|
||||
}
|
||||
|
||||
attribs.rel = "noreferrer noopener"; // https://mathiasbynens.github.io/rel-noopener/
|
||||
return { tagName, attribs };
|
||||
},
|
||||
"img": function (tagName: string, attribs: sanitizeHtml.Attributes) {
|
||||
let src = attribs.src;
|
||||
// Strip out imgs that aren't `mxc` here instead of using allowedSchemesByTag
|
||||
// because transformTags is used _before_ we filter by allowedSchemesByTag and
|
||||
// we don't want to allow images with `https?` `src`s.
|
||||
// We also drop inline images (as if they were not present at all) when the "show
|
||||
// images" preference is disabled. Future work might expose some UI to reveal them
|
||||
// like standalone image events have.
|
||||
if (!src || !SettingsStore.getValue("showImages")) {
|
||||
return { tagName, attribs: {} };
|
||||
}
|
||||
|
||||
if (!src.startsWith("mxc://")) {
|
||||
const match = MEDIA_API_MXC_REGEX.exec(src);
|
||||
if (match) {
|
||||
src = `mxc://${match[1]}/${match[2]}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!src.startsWith("mxc://")) {
|
||||
return { tagName, attribs: {} };
|
||||
}
|
||||
|
||||
const requestedWidth = Number(attribs.width);
|
||||
const requestedHeight = Number(attribs.height);
|
||||
const width = Math.min(requestedWidth || 800, 800);
|
||||
const height = Math.min(requestedHeight || 600, 600);
|
||||
// specify width/height as max values instead of absolute ones to allow object-fit to do its thing
|
||||
// we only allow our own styles for this tag so overwrite the attribute
|
||||
attribs.style = `max-width: ${width}px; max-height: ${height}px;`;
|
||||
if (requestedWidth) {
|
||||
attribs.style += "width: 100%;";
|
||||
}
|
||||
if (requestedHeight) {
|
||||
attribs.style += "height: 100%;";
|
||||
}
|
||||
|
||||
attribs.src = mediaFromMxc(src).getThumbnailOfSourceHttp(width, height)!;
|
||||
return { tagName, attribs };
|
||||
},
|
||||
"code": function (tagName: string, attribs: sanitizeHtml.Attributes) {
|
||||
if (typeof attribs.class !== "undefined") {
|
||||
// Filter out all classes other than ones starting with language- for syntax highlighting.
|
||||
const classes = attribs.class.split(/\s/).filter(function (cl) {
|
||||
return cl.startsWith("language-") && !cl.startsWith("language-_");
|
||||
});
|
||||
attribs.class = classes.join(" ");
|
||||
}
|
||||
return { tagName, attribs };
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
"*": function (tagName: string, attribs: sanitizeHtml.Attributes) {
|
||||
// Delete any style previously assigned, style is an allowedTag for font, span & img,
|
||||
// because attributes are stripped after transforming.
|
||||
// For img this is trusted as it is generated wholly within the img transformation method.
|
||||
if (tagName !== "img") {
|
||||
delete attribs.style;
|
||||
}
|
||||
|
||||
// Sanitise and transform data-mx-color and data-mx-bg-color to their CSS
|
||||
// equivalents
|
||||
const customCSSMapper: Record<string, string> = {
|
||||
"data-mx-color": "color",
|
||||
"data-mx-bg-color": "background-color",
|
||||
// $customAttributeKey: $cssAttributeKey
|
||||
};
|
||||
|
||||
let style = "";
|
||||
Object.keys(customCSSMapper).forEach((customAttributeKey) => {
|
||||
const cssAttributeKey = customCSSMapper[customAttributeKey];
|
||||
const customAttributeValue = attribs[customAttributeKey];
|
||||
if (
|
||||
customAttributeValue &&
|
||||
typeof customAttributeValue === "string" &&
|
||||
COLOR_REGEX.test(customAttributeValue)
|
||||
) {
|
||||
style += cssAttributeKey + ":" + customAttributeValue + ";";
|
||||
delete attribs[customAttributeKey];
|
||||
}
|
||||
});
|
||||
|
||||
if (style) {
|
||||
attribs.style = style + (attribs.style || "");
|
||||
}
|
||||
|
||||
return { tagName, attribs };
|
||||
},
|
||||
};
|
||||
|
||||
const sanitizeHtmlParams: IExtendedSanitizeOptions = {
|
||||
allowedTags: [
|
||||
"font", // custom to matrix for IRC-style font coloring
|
||||
"del", // for markdown
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"blockquote",
|
||||
"p",
|
||||
"a",
|
||||
"ul",
|
||||
"ol",
|
||||
"sup",
|
||||
"sub",
|
||||
"nl",
|
||||
"li",
|
||||
"b",
|
||||
"i",
|
||||
"u",
|
||||
"strong",
|
||||
"em",
|
||||
"strike",
|
||||
"code",
|
||||
"hr",
|
||||
"br",
|
||||
"div",
|
||||
"table",
|
||||
"thead",
|
||||
"caption",
|
||||
"tbody",
|
||||
"tr",
|
||||
"th",
|
||||
"td",
|
||||
"pre",
|
||||
"span",
|
||||
"img",
|
||||
"details",
|
||||
"summary",
|
||||
],
|
||||
allowedAttributes: {
|
||||
// attribute sanitization happens after transformations, so we have to accept `style` for font, span & img
|
||||
// but strip during the transformation.
|
||||
// custom ones first:
|
||||
font: ["color", "data-mx-bg-color", "data-mx-color", "style"], // custom to matrix
|
||||
span: ["data-mx-maths", "data-mx-bg-color", "data-mx-color", "data-mx-spoiler", "style"], // custom to matrix
|
||||
div: ["data-mx-maths"],
|
||||
a: ["href", "name", "target", "rel"], // remote target: custom to matrix
|
||||
// img tags also accept width/height, we just map those to max-width & max-height during transformation
|
||||
img: ["src", "alt", "title", "style"],
|
||||
ol: ["start"],
|
||||
code: ["class"], // We don't actually allow all classes, we filter them in transformTags
|
||||
},
|
||||
// Lots of these won't come up by default because we don't allow them
|
||||
selfClosing: ["img", "br", "hr", "area", "base", "basefont", "input", "link", "meta"],
|
||||
// URL schemes we permit
|
||||
allowedSchemes: PERMITTED_URL_SCHEMES,
|
||||
allowProtocolRelative: false,
|
||||
transformTags,
|
||||
// 50 levels deep "should be enough for anyone"
|
||||
nestingLimit: 50,
|
||||
};
|
||||
|
||||
// this is the same as the above except with less rewriting
|
||||
const composerSanitizeHtmlParams: IExtendedSanitizeOptions = {
|
||||
...sanitizeHtmlParams,
|
||||
@@ -535,7 +348,7 @@ export function bodyToHtml(content: IContent, highlights: Optional<string[]>, op
|
||||
isHtmlMessage = !isPlainText;
|
||||
|
||||
if (isHtmlMessage && SettingsStore.getValue("feature_latex_maths")) {
|
||||
[...phtml.querySelectorAll<HTMLElement>("div, span[data-mx-maths]")].forEach((e) => {
|
||||
[...phtml.querySelectorAll<HTMLElement>("div[data-mx-maths], span[data-mx-maths]")].forEach((e) => {
|
||||
e.outerHTML = katex.renderToString(decode(e.getAttribute("data-mx-maths")), {
|
||||
throwOnError: false,
|
||||
displayMode: e.tagName == "DIV",
|
||||
@@ -657,48 +470,6 @@ export function topicToHtml(
|
||||
);
|
||||
}
|
||||
|
||||
/* Wrapper around linkify-react merging in our default linkify options */
|
||||
export function Linkify({ as, options, children }: React.ComponentProps<typeof _Linkify>): ReactElement {
|
||||
return (
|
||||
<_Linkify as={as} options={merge({}, linkifyMatrixOptions, options)}>
|
||||
{children}
|
||||
</_Linkify>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Linkifies the given string. This is a wrapper around 'linkifyjs/string'.
|
||||
*
|
||||
* @param {string} str string to linkify
|
||||
* @param {object} [options] Options for linkifyString. Default: linkifyMatrixOptions
|
||||
* @returns {string} Linkified string
|
||||
*/
|
||||
export function linkifyString(str: string, options = linkifyMatrixOptions): string {
|
||||
return _linkifyString(str, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Linkifies the given DOM element. This is a wrapper around 'linkifyjs/element'.
|
||||
*
|
||||
* @param {object} element DOM element to linkify
|
||||
* @param {object} [options] Options for linkifyElement. Default: linkifyMatrixOptions
|
||||
* @returns {object}
|
||||
*/
|
||||
export function linkifyElement(element: HTMLElement, options = linkifyMatrixOptions): HTMLElement {
|
||||
return _linkifyElement(element, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Linkify the given string and sanitize the HTML afterwards.
|
||||
*
|
||||
* @param {string} dirtyHtml The HTML string to sanitize and linkify
|
||||
* @param {object} [options] Options for linkifyString. Default: linkifyMatrixOptions
|
||||
* @returns {string}
|
||||
*/
|
||||
export function linkifyAndSanitizeHtml(dirtyHtml: string, options = linkifyMatrixOptions): string {
|
||||
return sanitizeHtml(linkifyString(dirtyHtml, options), sanitizeHtmlParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns if a node is a block element or not.
|
||||
* Only takes html nodes into account that are allowed in matrix messages.
|
||||
|
||||
253
src/Linkify.tsx
Normal file
253
src/Linkify.tsx
Normal file
@@ -0,0 +1,253 @@
|
||||
/*
|
||||
Copyright 2024 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { ReactElement } from "react";
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
import { merge } from "lodash";
|
||||
import _Linkify from "linkify-react";
|
||||
|
||||
import {
|
||||
_linkifyElement,
|
||||
_linkifyString,
|
||||
ELEMENT_URL_PATTERN,
|
||||
options as linkifyMatrixOptions,
|
||||
} from "./linkify-matrix";
|
||||
import { IExtendedSanitizeOptions } from "./@types/sanitize-html";
|
||||
import SettingsStore from "./settings/SettingsStore";
|
||||
import { tryTransformPermalinkToLocalHref } from "./utils/permalinks/Permalinks";
|
||||
import { mediaFromMxc } from "./customisations/Media";
|
||||
import { PERMITTED_URL_SCHEMES } from "./utils/UrlUtils";
|
||||
|
||||
const COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;
|
||||
const MEDIA_API_MXC_REGEX = /\/_matrix\/media\/r0\/(?:download|thumbnail)\/(.+?)\/(.+?)(?:[?/]|$)/;
|
||||
|
||||
export const transformTags: NonNullable<IExtendedSanitizeOptions["transformTags"]> = {
|
||||
// custom to matrix
|
||||
// add blank targets to all hyperlinks except vector URLs
|
||||
"a": function (tagName: string, attribs: sanitizeHtml.Attributes) {
|
||||
if (attribs.href) {
|
||||
attribs.target = "_blank"; // by default
|
||||
|
||||
const transformed = tryTransformPermalinkToLocalHref(attribs.href); // only used to check if it is a link that can be handled locally
|
||||
if (
|
||||
transformed !== attribs.href || // it could be converted so handle locally symbols e.g. @user:server.tdl, matrix: and matrix.to
|
||||
attribs.href.match(ELEMENT_URL_PATTERN) // for https links to Element domains
|
||||
) {
|
||||
delete attribs.target;
|
||||
}
|
||||
} else {
|
||||
// Delete the href attrib if it is falsy
|
||||
delete attribs.href;
|
||||
}
|
||||
|
||||
attribs.rel = "noreferrer noopener"; // https://mathiasbynens.github.io/rel-noopener/
|
||||
return { tagName, attribs };
|
||||
},
|
||||
"img": function (tagName: string, attribs: sanitizeHtml.Attributes) {
|
||||
let src = attribs.src;
|
||||
// Strip out imgs that aren't `mxc` here instead of using allowedSchemesByTag
|
||||
// because transformTags is used _before_ we filter by allowedSchemesByTag and
|
||||
// we don't want to allow images with `https?` `src`s.
|
||||
// We also drop inline images (as if they were not present at all) when the "show
|
||||
// images" preference is disabled. Future work might expose some UI to reveal them
|
||||
// like standalone image events have.
|
||||
if (!src || !SettingsStore.getValue("showImages")) {
|
||||
return { tagName, attribs: {} };
|
||||
}
|
||||
|
||||
if (!src.startsWith("mxc://")) {
|
||||
const match = MEDIA_API_MXC_REGEX.exec(src);
|
||||
if (match) {
|
||||
src = `mxc://${match[1]}/${match[2]}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!src.startsWith("mxc://")) {
|
||||
return { tagName, attribs: {} };
|
||||
}
|
||||
|
||||
const requestedWidth = Number(attribs.width);
|
||||
const requestedHeight = Number(attribs.height);
|
||||
const width = Math.min(requestedWidth || 800, 800);
|
||||
const height = Math.min(requestedHeight || 600, 600);
|
||||
// specify width/height as max values instead of absolute ones to allow object-fit to do its thing
|
||||
// we only allow our own styles for this tag so overwrite the attribute
|
||||
attribs.style = `max-width: ${width}px; max-height: ${height}px;`;
|
||||
if (requestedWidth) {
|
||||
attribs.style += "width: 100%;";
|
||||
}
|
||||
if (requestedHeight) {
|
||||
attribs.style += "height: 100%;";
|
||||
}
|
||||
|
||||
attribs.src = mediaFromMxc(src).getThumbnailOfSourceHttp(width, height)!;
|
||||
return { tagName, attribs };
|
||||
},
|
||||
"code": function (tagName: string, attribs: sanitizeHtml.Attributes) {
|
||||
if (typeof attribs.class !== "undefined") {
|
||||
// Filter out all classes other than ones starting with language- for syntax highlighting.
|
||||
const classes = attribs.class.split(/\s/).filter(function (cl) {
|
||||
return cl.startsWith("language-") && !cl.startsWith("language-_");
|
||||
});
|
||||
attribs.class = classes.join(" ");
|
||||
}
|
||||
return { tagName, attribs };
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
"*": function (tagName: string, attribs: sanitizeHtml.Attributes) {
|
||||
// Delete any style previously assigned, style is an allowedTag for font, span & img,
|
||||
// because attributes are stripped after transforming.
|
||||
// For img this is trusted as it is generated wholly within the img transformation method.
|
||||
if (tagName !== "img") {
|
||||
delete attribs.style;
|
||||
}
|
||||
|
||||
// Sanitise and transform data-mx-color and data-mx-bg-color to their CSS
|
||||
// equivalents
|
||||
const customCSSMapper: Record<string, string> = {
|
||||
"data-mx-color": "color",
|
||||
"data-mx-bg-color": "background-color",
|
||||
// $customAttributeKey: $cssAttributeKey
|
||||
};
|
||||
|
||||
let style = "";
|
||||
Object.keys(customCSSMapper).forEach((customAttributeKey) => {
|
||||
const cssAttributeKey = customCSSMapper[customAttributeKey];
|
||||
const customAttributeValue = attribs[customAttributeKey];
|
||||
if (
|
||||
customAttributeValue &&
|
||||
typeof customAttributeValue === "string" &&
|
||||
COLOR_REGEX.test(customAttributeValue)
|
||||
) {
|
||||
style += cssAttributeKey + ":" + customAttributeValue + ";";
|
||||
delete attribs[customAttributeKey];
|
||||
}
|
||||
});
|
||||
|
||||
if (style) {
|
||||
attribs.style = style + (attribs.style || "");
|
||||
}
|
||||
|
||||
return { tagName, attribs };
|
||||
},
|
||||
};
|
||||
|
||||
export const sanitizeHtmlParams: IExtendedSanitizeOptions = {
|
||||
allowedTags: [
|
||||
"font", // custom to matrix for IRC-style font coloring
|
||||
"del", // for markdown
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"blockquote",
|
||||
"p",
|
||||
"a",
|
||||
"ul",
|
||||
"ol",
|
||||
"sup",
|
||||
"sub",
|
||||
"nl",
|
||||
"li",
|
||||
"b",
|
||||
"i",
|
||||
"u",
|
||||
"strong",
|
||||
"em",
|
||||
"strike",
|
||||
"code",
|
||||
"hr",
|
||||
"br",
|
||||
"div",
|
||||
"table",
|
||||
"thead",
|
||||
"caption",
|
||||
"tbody",
|
||||
"tr",
|
||||
"th",
|
||||
"td",
|
||||
"pre",
|
||||
"span",
|
||||
"img",
|
||||
"details",
|
||||
"summary",
|
||||
],
|
||||
allowedAttributes: {
|
||||
// attribute sanitization happens after transformations, so we have to accept `style` for font, span & img
|
||||
// but strip during the transformation.
|
||||
// custom ones first:
|
||||
font: ["color", "data-mx-bg-color", "data-mx-color", "style"], // custom to matrix
|
||||
span: ["data-mx-maths", "data-mx-bg-color", "data-mx-color", "data-mx-spoiler", "style"], // custom to matrix
|
||||
div: ["data-mx-maths"],
|
||||
a: ["href", "name", "target", "rel"], // remote target: custom to matrix
|
||||
// img tags also accept width/height, we just map those to max-width & max-height during transformation
|
||||
img: ["src", "alt", "title", "style"],
|
||||
ol: ["start"],
|
||||
code: ["class"], // We don't actually allow all classes, we filter them in transformTags
|
||||
},
|
||||
// Lots of these won't come up by default because we don't allow them
|
||||
selfClosing: ["img", "br", "hr", "area", "base", "basefont", "input", "link", "meta"],
|
||||
// URL schemes we permit
|
||||
allowedSchemes: PERMITTED_URL_SCHEMES,
|
||||
allowProtocolRelative: false,
|
||||
transformTags,
|
||||
// 50 levels deep "should be enough for anyone"
|
||||
nestingLimit: 50,
|
||||
};
|
||||
|
||||
/* Wrapper around linkify-react merging in our default linkify options */
|
||||
export function Linkify({ as, options, children }: React.ComponentProps<typeof _Linkify>): ReactElement {
|
||||
return (
|
||||
<_Linkify as={as} options={merge({}, linkifyMatrixOptions, options)}>
|
||||
{children}
|
||||
</_Linkify>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Linkifies the given string. This is a wrapper around 'linkifyjs/string'.
|
||||
*
|
||||
* @param {string} str string to linkify
|
||||
* @param {object} [options] Options for linkifyString. Default: linkifyMatrixOptions
|
||||
* @returns {string} Linkified string
|
||||
*/
|
||||
export function linkifyString(str: string, options = linkifyMatrixOptions): string {
|
||||
return _linkifyString(str, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Linkifies the given DOM element. This is a wrapper around 'linkifyjs/element'.
|
||||
*
|
||||
* @param {object} element DOM element to linkify
|
||||
* @param {object} [options] Options for linkifyElement. Default: linkifyMatrixOptions
|
||||
* @returns {object}
|
||||
*/
|
||||
export function linkifyElement(element: HTMLElement, options = linkifyMatrixOptions): HTMLElement {
|
||||
return _linkifyElement(element, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Linkify the given string and sanitize the HTML afterwards.
|
||||
*
|
||||
* @param {string} dirtyHtml The HTML string to sanitize and linkify
|
||||
* @param {object} [options] Options for linkifyString. Default: linkifyMatrixOptions
|
||||
* @returns {string}
|
||||
*/
|
||||
export function linkifyAndSanitizeHtml(dirtyHtml: string, options = linkifyMatrixOptions): string {
|
||||
return sanitizeHtml(linkifyString(dirtyHtml, options), sanitizeHtmlParams);
|
||||
}
|
||||
@@ -38,7 +38,6 @@ import SettingsStore from "../../settings/SettingsStore";
|
||||
import { SettingLevel } from "../../settings/SettingLevel";
|
||||
import ResizeHandle from "../views/elements/ResizeHandle";
|
||||
import { CollapseDistributor, Resizer } from "../../resizer";
|
||||
import MatrixClientContext from "../../contexts/MatrixClientContext";
|
||||
import ResizeNotifier from "../../utils/ResizeNotifier";
|
||||
import PlatformPeg from "../../PlatformPeg";
|
||||
import { DefaultTagID } from "../../stores/room-list/models";
|
||||
@@ -75,6 +74,7 @@ import { UserOnboardingPage } from "../views/user-onboarding/UserOnboardingPage"
|
||||
import { PipContainer } from "./PipContainer";
|
||||
import { monitorSyncedPushRules } from "../../utils/pushRules/monitorSyncedPushRules";
|
||||
import { ConfigOptions } from "../../SdkConfig";
|
||||
import { MatrixClientContextProvider } from "./MatrixClientContextProvider";
|
||||
|
||||
// We need to fetch each pinned message individually (if we don't already have it)
|
||||
// so each pinned message may trigger a request. Limit the number per room for sanity.
|
||||
@@ -672,7 +672,7 @@ class LoggedInView extends React.Component<IProps, IState> {
|
||||
});
|
||||
|
||||
return (
|
||||
<MatrixClientContext.Provider value={this._matrixClient}>
|
||||
<MatrixClientContextProvider client={this._matrixClient}>
|
||||
<div
|
||||
onPaste={this.onPaste}
|
||||
onKeyDown={this.onReactKeyDown}
|
||||
@@ -707,7 +707,7 @@ class LoggedInView extends React.Component<IProps, IState> {
|
||||
<PipContainer />
|
||||
<NonUrgentToastContainer />
|
||||
{audioFeedArraysForCalls}
|
||||
</MatrixClientContext.Provider>
|
||||
</MatrixClientContextProvider>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
104
src/components/structures/MatrixClientContextProvider.tsx
Normal file
104
src/components/structures/MatrixClientContextProvider.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
Copyright 2024 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { PropsWithChildren, useEffect, useState } from "react";
|
||||
import { CryptoEvent, MatrixClient } from "matrix-js-sdk/src/matrix";
|
||||
import { logger } from "matrix-js-sdk/src/logger";
|
||||
|
||||
import MatrixClientContext from "../../contexts/MatrixClientContext";
|
||||
import { useEventEmitter } from "../../hooks/useEventEmitter";
|
||||
import { LocalDeviceVerificationStateContext } from "../../contexts/LocalDeviceVerificationStateContext";
|
||||
|
||||
/**
|
||||
* A React hook whose value is whether the local device has been "verified".
|
||||
*
|
||||
* Figuring out if we are verified is an async operation, so on the first render this always returns `false`, but
|
||||
* fires off a background job to update a state variable. It also registers an event listener to update the state
|
||||
* variable changes.
|
||||
*
|
||||
* @param client - Matrix client.
|
||||
* @returns A boolean which is `true` if the local device has been verified.
|
||||
*
|
||||
* @remarks
|
||||
*
|
||||
* Some notes on implementation.
|
||||
*
|
||||
* It turns out "is this device verified?" isn't a question that is easy to answer as you might think.
|
||||
*
|
||||
* Roughly speaking, it normally means "do we believe this device actually belongs to the person it claims to belong
|
||||
* to", and that data is available via `getDeviceVerificationStatus().isVerified()`. However, the problem is that for
|
||||
* the local device, that "do we believe..." question is trivially true, and `isVerified()` always returns true.
|
||||
*
|
||||
* Instead, when we're talking about the local device, what we really mean is one of:
|
||||
* * "have we completed a verification dance (either interactive verification with a device with access to the
|
||||
* cross-signing secrets, or typing in the 4S key)?", or
|
||||
* * "will other devices consider this one to be verified?"
|
||||
*
|
||||
* (The first is generally required but not sufficient for the second to be true.)
|
||||
*
|
||||
* The second question basically amounts to "has this device been signed by our cross-signing key". So one option here
|
||||
* is to use `getDeviceVerificationStatus().isCrossSigningVerified()`. That might work, but it's a bit annoying because
|
||||
* it needs a `/keys/query` request to complete after the actual verification process completes.
|
||||
*
|
||||
* A slightly less rigorous check is just to find out if we have validated our own public cross-signing keys. If we
|
||||
* have, it's a good indication that we've at least completed a verification dance -- and hopefully, during that dance,
|
||||
* a cross-signature of our own device was published. And it's also easy to monitor via `UserTrustStatusChanged` events.
|
||||
*
|
||||
* Sooo: TL;DR: `getUserVerificationStatus()` is a good proxy for "is the local device verified?".
|
||||
*/
|
||||
function useLocalVerificationState(client: MatrixClient): boolean {
|
||||
const [value, setValue] = useState(false);
|
||||
|
||||
// On the first render, initialise the state variable
|
||||
useEffect(() => {
|
||||
const userId = client.getUserId();
|
||||
if (!userId) return;
|
||||
const crypto = client.getCrypto();
|
||||
crypto?.getUserVerificationStatus(userId).then(
|
||||
(verificationStatus) => setValue(verificationStatus.isCrossSigningVerified()),
|
||||
(error) => logger.error("Error fetching verification status", error),
|
||||
);
|
||||
}, [client]);
|
||||
|
||||
// Update the value whenever our own trust status changes.
|
||||
useEventEmitter(client, CryptoEvent.UserTrustStatusChanged, (userId, verificationStatus) => {
|
||||
if (userId === client.getUserId()) {
|
||||
setValue(verificationStatus.isCrossSigningVerified());
|
||||
}
|
||||
});
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** Matrix client, which is exposed to all child components via {@link MatrixClientContext}. */
|
||||
client: MatrixClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* A React component which exposes a {@link MatrixClientContext} and a {@link LocalDeviceVerificationStateContext}
|
||||
* to its children.
|
||||
*/
|
||||
export function MatrixClientContextProvider(props: PropsWithChildren<Props>): React.JSX.Element {
|
||||
const verificationState = useLocalVerificationState(props.client);
|
||||
return (
|
||||
<MatrixClientContext.Provider value={props.client}>
|
||||
<LocalDeviceVerificationStateContext.Provider value={verificationState}>
|
||||
{props.children}
|
||||
</LocalDeviceVerificationStateContext.Provider>
|
||||
</MatrixClientContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import InteractiveAuth, {
|
||||
} from "../../structures/InteractiveAuth";
|
||||
import { ContinueKind, SSOAuthEntry } from "../auth/InteractiveAuthEntryComponents";
|
||||
import BaseDialog from "./BaseDialog";
|
||||
import { Linkify } from "../../../Linkify";
|
||||
|
||||
type DialogAesthetics = Partial<{
|
||||
[x in AuthType]: {
|
||||
@@ -168,7 +169,9 @@ export default class InteractiveAuthDialog<T> extends React.Component<Interactiv
|
||||
if (this.state.authError) {
|
||||
content = (
|
||||
<div id="mx_Dialog_content">
|
||||
<div role="alert">{this.state.authError.message || this.state.authError.toString()}</div>
|
||||
<Linkify>
|
||||
<div role="alert">{this.state.authError.message || this.state.authError.toString()}</div>
|
||||
</Linkify>
|
||||
<br />
|
||||
<AccessibleButton onClick={this.onDismissClick} className="mx_GeneralButton" autoFocus={true}>
|
||||
{_t("action|dismiss")}
|
||||
|
||||
@@ -36,6 +36,7 @@ import { getKeyBindingsManager } from "../../../../KeyBindingsManager";
|
||||
import { KeyBindingAction } from "../../../../accessibility/KeyboardShortcuts";
|
||||
import { ReleaseAnnouncement } from "../../../structures/ReleaseAnnouncement";
|
||||
import { useIsReleaseAnnouncementOpen } from "../../../../hooks/useIsReleaseAnnouncementOpen";
|
||||
import { useSettingValue } from "../../../../hooks/useSettings";
|
||||
|
||||
interface ThreadsActivityCentreProps {
|
||||
/**
|
||||
@@ -52,6 +53,11 @@ export function ThreadsActivityCentre({ displayButtonLabel }: ThreadsActivityCen
|
||||
const [open, setOpen] = useState(false);
|
||||
const roomsAndNotifications = useUnreadThreadRooms(open);
|
||||
const isReleaseAnnouncementOpen = useIsReleaseAnnouncementOpen("threadsActivityCentre");
|
||||
const settingTACOnlyNotifs = useSettingValue<boolean>("Notifications.tac_only_notifications");
|
||||
|
||||
const emptyCaption = settingTACOnlyNotifs
|
||||
? _t("threads_activity_centre|no_rooms_with_threads_notifs")
|
||||
: _t("threads_activity_centre|no_rooms_with_unread_threads");
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -110,9 +116,7 @@ export function ThreadsActivityCentre({ displayButtonLabel }: ThreadsActivityCen
|
||||
/>
|
||||
))}
|
||||
{roomsAndNotifications.rooms.length === 0 && (
|
||||
<div className="mx_ThreadsActivityCentre_emptyCaption">
|
||||
{_t("threads_activity_centre|no_rooms_with_unreads_threads")}
|
||||
</div>
|
||||
<div className="mx_ThreadsActivityCentre_emptyCaption">{emptyCaption}</div>
|
||||
)}
|
||||
</div>
|
||||
</Menu>
|
||||
|
||||
27
src/contexts/LocalDeviceVerificationStateContext.ts
Normal file
27
src/contexts/LocalDeviceVerificationStateContext.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
Copyright 2024 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { createContext } from "react";
|
||||
|
||||
/**
|
||||
* React context whose value is whether the local device has been verified.
|
||||
*
|
||||
* (Specifically, this is true if we have done enough verification to confirm that the published public cross-signing
|
||||
* keys are genuine -- which normally means that we or another device will have published a signature of this device.)
|
||||
*
|
||||
* This context is available to all components under {@link LoggedInView}, via {@link MatrixClientContextProvider}.
|
||||
*/
|
||||
export const LocalDeviceVerificationStateContext = createContext(false);
|
||||
@@ -3152,8 +3152,7 @@
|
||||
"unable_to_decrypt": "Nepodařilo se dešifrovat zprávu"
|
||||
},
|
||||
"threads_activity_centre": {
|
||||
"header": "Aktivita vláken",
|
||||
"no_rooms_with_unreads_threads": "Zatím nemáte místnosti s nepřečtenými vlákny."
|
||||
"header": "Aktivita vláken"
|
||||
},
|
||||
"time": {
|
||||
"about_day_ago": "před jedním dnem",
|
||||
|
||||
@@ -3167,7 +3167,8 @@
|
||||
},
|
||||
"threads_activity_centre": {
|
||||
"header": "Threads activity",
|
||||
"no_rooms_with_unreads_threads": "You don't have rooms with unread threads yet.",
|
||||
"no_rooms_with_threads_notifs": "You don't have rooms with thread notifications yet.",
|
||||
"no_rooms_with_unread_threads": "You don't have rooms with unread threads yet.",
|
||||
"release_announcement_description": "Threads notifications have moved, find them here from now on.",
|
||||
"release_announcement_header": "Threads Activity Centre"
|
||||
},
|
||||
|
||||
@@ -3096,9 +3096,6 @@
|
||||
"show_thread_filter": "Näita:",
|
||||
"unable_to_decrypt": "Sõnumi dekrüptimine ei õnnestunud"
|
||||
},
|
||||
"threads_activity_centre": {
|
||||
"no_rooms_with_unreads_threads": "Sul veel pole lugemata jutulõngadega jututubasid."
|
||||
},
|
||||
"time": {
|
||||
"about_day_ago": "umbes päev tagasi",
|
||||
"about_hour_ago": "umbes tund aega tagasi",
|
||||
|
||||
@@ -3145,8 +3145,7 @@
|
||||
"unable_to_decrypt": "Impossibile decifrare il messaggio"
|
||||
},
|
||||
"threads_activity_centre": {
|
||||
"header": "Attività delle conversazioni",
|
||||
"no_rooms_with_unreads_threads": "Non hai ancora stanze con conversazioni non lette."
|
||||
"header": "Attività delle conversazioni"
|
||||
},
|
||||
"time": {
|
||||
"about_day_ago": "circa un giorno fa",
|
||||
|
||||
@@ -1419,6 +1419,7 @@
|
||||
"group_spaces": "Przestrzenie",
|
||||
"group_themes": "Motywy",
|
||||
"group_threads": "Wątki",
|
||||
"group_ui": "Interfejs użytkownika",
|
||||
"group_voip": "Głos i wideo",
|
||||
"group_widgets": "Widżety",
|
||||
"hidebold": "Ukryj kropkę powiadomienia (wyświetlaj tylko licznik plakietek)",
|
||||
@@ -1442,6 +1443,7 @@
|
||||
"oidc_native_flow": "Uwierzytelnianie natywne OIDC",
|
||||
"oidc_native_flow_description": "⚠ OSTRZEŻENIE: Funkcja eksperymentalna. Użyj uwierzytelniania natywnego OIDC, gdy jest wspierane przez serwer.",
|
||||
"pinning": "Przypinanie wiadomości",
|
||||
"release_announcement": "Ogłoszenie o wydaniu",
|
||||
"render_reaction_images": "Renderuj niestandardowe obrazy w reakcjach",
|
||||
"render_reaction_images_description": "Czasami określane jako \"emoji niestandardowe\".",
|
||||
"report_to_moderators": "Zgłoś do moderatorów",
|
||||
@@ -2685,6 +2687,8 @@
|
||||
"cross_signing_self_signing_private_key": "Samo-podpisujący klucz prywatny:",
|
||||
"cross_signing_user_signing_private_key": "Podpisany przez użytkownika klucz prywatny:",
|
||||
"cryptography_section": "Kryptografia",
|
||||
"dehydrated_device_description": "Funkcja urządzenia offline umożliwia odbieranie wiadomości szyfrowanych, nawet jeśli nie jesteś zalogowany na żadnym urządzeniu",
|
||||
"dehydrated_device_enabled": "Urządzenie offline włączone",
|
||||
"delete_backup": "Usuń kopię zapasową",
|
||||
"delete_backup_confirm_description": "Czy jesteś pewien? Stracisz dostęp do wszystkich swoich zaszyfrowanych wiadomości, jeżeli nie utworzyłeś poprawnej kopii zapasowej kluczy.",
|
||||
"e2ee_default_disabled_warning": "Twój administrator serwera wyłączył szyfrowanie end-to-end domyślnie w pokojach prywatnych i wiadomościach bezpośrednich.",
|
||||
@@ -2847,6 +2851,7 @@
|
||||
"show_redaction_placeholder": "Pokaż symbol zastępczy dla usuniętych wiadomości",
|
||||
"show_stickers_button": "Pokaż przycisk naklejek",
|
||||
"show_typing_notifications": "Pokazuj powiadomienia o pisaniu",
|
||||
"showbold": "Pokaż całą aktywność na liście pomieszczeń (kropki lub liczbę nieprzeczytanych wiadomości)",
|
||||
"sidebar": {
|
||||
"metaspaces_favourites_description": "Pogrupuj wszystkie swoje ulubione pokoje i osoby w jednym miejscu.",
|
||||
"metaspaces_home_all_rooms": "Pokaż wszystkie pokoje",
|
||||
@@ -2863,6 +2868,7 @@
|
||||
"title": "Pasek boczny"
|
||||
},
|
||||
"start_automatically": "Uruchom automatycznie po zalogowaniu się do systemu",
|
||||
"tac_only_notifications": "Pokaż powiadomienia tylko w centrum aktywności wątków",
|
||||
"use_12_hour_format": "Pokaż czas w formacie 12-sto godzinnym (np. 2:30pm)",
|
||||
"use_command_enter_send_message": "Użyj Command + Enter, aby wysłać wiadomość",
|
||||
"use_command_f_search": "Użyj Command + F aby przeszukać oś czasu",
|
||||
@@ -3164,7 +3170,10 @@
|
||||
},
|
||||
"threads_activity_centre": {
|
||||
"header": "Aktywność wątków",
|
||||
"no_rooms_with_unreads_threads": "Nie masz jeszcze pokoi z nieprzeczytanymi wątkami."
|
||||
"no_rooms_with_threads_notifs": "Nie masz jeszcze pokoi z powiadomieniami w wątku.",
|
||||
"no_rooms_with_unread_threads": "Nie masz jeszcze pokoi z nieprzeczytanymi wątkami.",
|
||||
"release_announcement_description": "Powiadomienia w wątkach zostały przeniesione, teraz znajdziesz je tutaj.",
|
||||
"release_announcement_header": "Centrum aktywności wątków"
|
||||
},
|
||||
"time": {
|
||||
"about_day_ago": "około dzień temu",
|
||||
@@ -3659,6 +3668,12 @@
|
||||
"toast_title": "Aktualizuj %(brand)s",
|
||||
"unavailable": "Niedostępny"
|
||||
},
|
||||
"update_room_access_modal": {
|
||||
"description": "Aby utworzyć link udostępniania, musisz zezwolić gościom na dołączenie do tego pokoju. Może to zmniejszyć bezpieczeństwo pokoju. Gdy zakończysz połączenie, możesz ustawić pokój jako prywatny z powrotem.",
|
||||
"dont_change_description": "Możesz również zadzwonić w innym pokoju.",
|
||||
"no_change": "Nie chce zmieniać poziomu uprawnień.",
|
||||
"title": "Zmień poziom dostępu pokoju"
|
||||
},
|
||||
"upload_failed_generic": "Nie udało się przesłać pliku '%(fileName)s'.",
|
||||
"upload_failed_size": "Plik '%(fileName)s' przekracza limit rozmiaru dla tego serwera głównego",
|
||||
"upload_failed_title": "Błąd przesyłania",
|
||||
@@ -3694,6 +3709,7 @@
|
||||
"deactivate_confirm_action": "Dezaktywuj użytkownika",
|
||||
"deactivate_confirm_description": "Dezaktywacja tego użytkownika, wyloguje go i uniemożliwi logowanie ponowne. Dodatkowo, opuści wszystkie pokoje, w których się znajdują. Tej akcji nie można cofnąć. Czy na pewno chcesz dezaktywować tego użytkownika?",
|
||||
"deactivate_confirm_title": "Dezaktywować użytkownika?",
|
||||
"dehydrated_device_enabled": "Urządzenie offline włączone",
|
||||
"demote_button": "Degraduj",
|
||||
"demote_self_confirm_description_space": "Nie będziesz mógł cofnąć tej zmiany, ponieważ degradujesz swoje uprawnienia. Jeśli jesteś ostatnim użytkownikiem uprzywilejowanym w tej przestrzeni, nie będziesz mógł ich odzyskać.",
|
||||
"demote_self_confirm_room": "Nie będziesz mógł cofnąć tej zmiany, ponieważ degradujesz swoje uprawnienia. Jeśli jesteś ostatnim użytkownikiem uprzywilejowanym w tym pokoju, nie będziesz mógł ich odzyskać.",
|
||||
|
||||
@@ -3144,8 +3144,7 @@
|
||||
"unable_to_decrypt": "Kunde inte avkryptera meddelande"
|
||||
},
|
||||
"threads_activity_centre": {
|
||||
"header": "Aktivitet för trådar",
|
||||
"no_rooms_with_unreads_threads": "Du har inte rum med olästa trådar än."
|
||||
"header": "Aktivitet för trådar"
|
||||
},
|
||||
"time": {
|
||||
"about_day_ago": "cirka en dag sedan",
|
||||
|
||||
Reference in New Issue
Block a user