Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-matrix-to-link-wrapping.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
default: patch
---

Matrix.to links sent without explicit markdown formatting are sent as raw links instead of html links.
45 changes: 43 additions & 2 deletions src/app/plugins/markdown/markdownToHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,39 @@ const decodeHtmlEntities = (text: string): string => {
return result;
};

const MATRIX_TO_PLACEHOLDER_PREFIX = 'MATRIXTORAWLINKTOKEN';

const escapeHtml = (text: string): string =>
text
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');

const shieldBareMatrixToLinks = (
input: string
): { shielded: string; placeholders: Map<string, string> } => {
const placeholders = new Map<string, string>();
let index = 0;

const shielded = input.replace(/(?<!\]\()https?:\/\/matrix\.to\/[^\s<)]+/gi, (url) => {
const key = `${MATRIX_TO_PLACEHOLDER_PREFIX}${index++}X`;
placeholders.set(key, url);
return key;
});

return { shielded, placeholders };
};

const unshieldBareMatrixToLinks = (html: string, placeholders: Map<string, string>): string => {
let result = html;
for (const [key, url] of placeholders.entries()) {
result = result.split(key).join(escapeHtml(url));
}
return result;
};

/**
* Converts markdown string to sanitized Matrix-compatible HTML.
* Uses marked for parsing and DOMPurify for sanitization per Matrix spec.
Expand All @@ -67,7 +100,10 @@ export function markdownToHtml(markdown: string): string {

const preprocessed = preprocessEmoticon(blockquotePrefixed);

const mathInput = shieldDollarRunsForMarked(maskDollarSignsInsideMarkdownCode(preprocessed));
const { shielded: matrixToShielded, placeholders: matrixToPlaceholders } =
shieldBareMatrixToLinks(preprocessed);

const mathInput = shieldDollarRunsForMarked(maskDollarSignsInsideMarkdownCode(matrixToShielded));

// Parse markdown to HTML using marked with our Matrix extensions
const html = processor.parse(mathInput) as string;
Expand Down Expand Up @@ -164,5 +200,10 @@ export function markdownToHtml(markdown: string): string {
}
);

return restoredMxEmoticonHeight.replace(/<li>(<p><\/p>)?<\/li>/gi, '<li><br></li>');
const unshieldedMatrixTo = unshieldBareMatrixToLinks(
restoredMxEmoticonHeight,
matrixToPlaceholders
);

return unshieldedMatrixTo.replace(/<li>(<p><\/p>)?<\/li>/gi, '<li><br></li>');
}
Loading