Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

fix(web): allowlist the img style attribute in the editor (#347)

Egor Vasilyev6ba7aa2de2bd
diff --git a/apps/web/src/components/common/editor/EditorResizableImage.tsx b/apps/web/src/components/common/editor/EditorResizableImage.tsx
index b15a6463..d4aafe2a 100644
--- a/apps/web/src/components/common/editor/EditorResizableImage.tsx
+++ b/apps/web/src/components/common/editor/EditorResizableImage.tsx
@@ -6,12 +6,14 @@ import {
} from 'react';
import { NodeViewWrapper, type NodeViewProps } from '@tiptap/react';
import { cn } from '@/lib/utils';
+import { allowedImageStyle } from '@/utils/imageStyle';
// Below this an image is too small to grab again.
const MIN_WIDTH = 60;
// The node's `style` attribute holds raw CSS text; React takes the parsed form.
-function styleObject(css: string | null): CSSProperties {
+function styleObject(style: string | null): CSSProperties {
+ const css = allowedImageStyle(style);
if (!css) return {};
return Object.fromEntries(
css.split(';').flatMap((declaration) => {
diff --git a/apps/web/src/components/common/editor/tiptap-image.test.ts b/apps/web/src/components/common/editor/tiptap-image.test.ts
new file mode 100644
index 00000000..ab09cf97
--- /dev/null
+++ b/apps/web/src/components/common/editor/tiptap-image.test.ts
@@ -0,0 +1,92 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { Editor } from '@tiptap/core';
+import StarterKit from '@tiptap/starter-kit';
+import { Markdown } from 'tiptap-markdown';
+import { JSDOM } from 'jsdom';
+import { ResizableImage } from './tiptap-image';
+
+let dom: JSDOM;
+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;
+
+beforeEach(() => {
+ originalGlobalDescriptors = new Map(
+ ['window', 'document', 'navigator', 'DOMParser', 'Node', 'Element', 'HTMLElement'].map(
+ (name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)],
+ ),
+ );
+ dom = new JSDOM('<!doctype html><div></div>');
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ navigator: { configurable: true, value: dom.window.navigator },
+ DOMParser: { configurable: true, value: dom.window.DOMParser },
+ Node: { configurable: true, value: dom.window.Node },
+ Element: { configurable: true, value: dom.window.Element },
+ HTMLElement: { configurable: true, value: dom.window.HTMLElement },
+ });
+});
+
+afterEach(() => {
+ dom.window.close();
+ for (const [name, descriptor] of originalGlobalDescriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+function imageEditor(content: string): Editor {
+ return new Editor({
+ extensions: [
+ StarterKit.configure({ link: false }),
+ ResizableImage,
+ Markdown.configure({ html: true, linkify: true, breaks: true }),
+ ],
+ content,
+ });
+}
+
+function imageAttrs(editor: Editor): Record<string, unknown> {
+ const image = editor.getJSON().content?.flatMap((node) => node.content ?? [node])[0];
+ assert.equal(image?.type, 'image');
+ return image?.attrs ?? {};
+}
+
+describe('ResizableImage style attribute', () => {
+ it('keeps only the sizing of a raw <img style> in the text', () => {
+ const editor = imageEditor(
+ '<img src="/a.png" alt="a" style="position:fixed;inset:0;width:320px;height:100vh;z-index:9999">',
+ );
+ assert.equal(imageAttrs(editor).style, 'width: 320px');
+ assert.doesNotMatch(editor.getHTML(), /position|inset|z-index|100vh/);
+ assert.equal(
+ editor.storage.markdown.getMarkdown(),
+ '<img src="/a.png" alt="a" style="width: 320px">',
+ );
+ editor.destroy();
+ });
+
+ it('drops a style with nothing allowed in it', () => {
+ const editor = imageEditor('<img src="/a.png" alt="a" style="position:fixed;inset:0">');
+ assert.equal(imageAttrs(editor).style, null);
+ assert.equal(editor.storage.markdown.getMarkdown(), '![a](/a.png)');
+ editor.destroy();
+ });
+
+ it('keeps the max-width an embed carries', () => {
+ const editor = imageEditor('<img src="/a.png" alt="a" style="max-width:50%">');
+ assert.equal(imageAttrs(editor).style, 'max-width: 50%');
+ assert.equal(
+ editor.storage.markdown.getMarkdown(),
+ '<img src="/a.png" alt="a" style="max-width: 50%">',
+ );
+ editor.destroy();
+ });
+
+ it('keeps the width the resizer stores', () => {
+ const editor = imageEditor('<img src="/a.png" alt="a" width="240">');
+ assert.equal(imageAttrs(editor).width, 240);
+ assert.equal(editor.storage.markdown.getMarkdown(), '<img src="/a.png" alt="a" width="240">');
+ editor.destroy();
+ });
+});
diff --git a/apps/web/src/components/common/editor/tiptap-image.ts b/apps/web/src/components/common/editor/tiptap-image.ts
index 9da39573..a52bce57 100644
--- a/apps/web/src/components/common/editor/tiptap-image.ts
+++ b/apps/web/src/components/common/editor/tiptap-image.ts
@@ -1,6 +1,7 @@
import Image from '@tiptap/extension-image';
import { ReactNodeViewRenderer } from '@tiptap/react';
import EditorResizableImage from './EditorResizableImage';
+import { allowedImageStyle } from '@/utils/imageStyle';
// Safe inside a double-quoted HTML attribute: a filename may hold any of these.
const escapeAttribute = (value: string) =>
@@ -26,7 +27,10 @@ export const ResizableImage = Image.extend({
return {
...parent,
// Kept so a raw <img style="max-width:50%"> keeps its sizing.
- style: { default: null },
+ style: {
+ default: null,
+ parseHTML: (element) => allowedImageStyle(element.getAttribute('style')),
+ },
width: {
default: null,
parseHTML: (element) => {
diff --git a/apps/web/src/lib/markdown.test.ts b/apps/web/src/lib/markdown.test.ts
index 39441fc3..7dc2ec38 100644
--- a/apps/web/src/lib/markdown.test.ts
+++ b/apps/web/src/lib/markdown.test.ts
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
-import { markdownSegments } from './markdown';
+import { markdownSegments, renderMarkdown, sanitizeHtml } from './markdown';
const spec =
'{"type":"bar","x":"week","series":[{"key":"created"}],"data":[{"week":"W1","created":3}]}';
@@ -55,3 +55,27 @@ describe('markdownSegments', () => {
]);
});
});
+
+describe('sanitizeHtml image style', () => {
+ const overlay =
+ '<img src="/a.png" style="position:fixed;inset:0;width:100vw;height:100vh;z-index:9999">';
+
+ it('drops an image style that would lay the image over the page', () => {
+ assert.equal(sanitizeHtml(overlay), '<img src="/a.png">');
+ assert.equal(
+ sanitizeHtml(`<p>${overlay}</p>`, { newTabLinks: true }),
+ '<p><img src="/a.png"></p>',
+ );
+ });
+
+ it('keeps the sizing of an image', () => {
+ assert.equal(
+ sanitizeHtml('<img src="/a.png" style="width: 320px; max-width: 100%">'),
+ '<img src="/a.png" style="width: 320px; max-width: 100%">',
+ );
+ });
+
+ it('applies to a raw <img> in markdown text', () => {
+ assert.equal(renderMarkdown(`text\n\n${overlay}`), '<p>text</p>\n<img src="/a.png">');
+ });
+});
diff --git a/apps/web/src/lib/markdown.ts b/apps/web/src/lib/markdown.ts
index 52b8e78f..f167fe45 100644
--- a/apps/web/src/lib/markdown.ts
+++ b/apps/web/src/lib/markdown.ts
@@ -1,7 +1,8 @@
import { marked } from 'marked';
-import DOMPurify from 'isomorphic-dompurify';
+import DOMPurify, { type UponSanitizeAttributeHookEvent } from 'isomorphic-dompurify';
import { parseChartSpec, type ChartSpec } from '@/utils/chartSpec';
import { mediaUrl } from '@/lib/api/core/media';
+import { allowedImageStyle } from '@/utils/imageStyle';
// Content whose links lead away from the current view (release notes, agent chat)
// asks for newTabLinks, so following one does not replace what the reader was on.
@@ -16,15 +17,25 @@ function newTab(node: Element): void {
}
}
+// DOMPurify keeps `style` as it is, and on an image that is enough to cover the
+// page (see allowedImageStyle).
+function restrictImageStyle(node: Element, data: UponSanitizeAttributeHookEvent): void {
+ if (data.attrName !== 'style' || node.tagName !== 'IMG') return;
+ const style = allowedImageStyle(data.attrValue);
+ if (style) data.attrValue = style;
+ else data.keepAttr = false;
+}
+
// HTML that arrives already rendered, made safe for dangerouslySetInnerHTML. Used
// for release notes, which GitHub renders and the api passes through unchanged.
export function sanitizeHtml(html: string, options?: HtmlOptions): string {
- if (!options?.newTabLinks) return DOMPurify.sanitize(html);
- DOMPurify.addHook('afterSanitizeAttributes', newTab);
+ DOMPurify.addHook('uponSanitizeAttribute', restrictImageStyle);
+ if (options?.newTabLinks) DOMPurify.addHook('afterSanitizeAttributes', newTab);
try {
return DOMPurify.sanitize(html);
} finally {
- DOMPurify.removeHook('afterSanitizeAttributes');
+ DOMPurify.removeHook('afterSanitizeAttributes', newTab);
+ DOMPurify.removeHook('uponSanitizeAttribute', restrictImageStyle);
}
}
diff --git a/apps/web/src/utils/imageStyle.test.ts b/apps/web/src/utils/imageStyle.test.ts
new file mode 100644
index 00000000..3f4bac6f
--- /dev/null
+++ b/apps/web/src/utils/imageStyle.test.ts
@@ -0,0 +1,46 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { allowedImageStyle } from './imageStyle';
+
+describe('allowedImageStyle', () => {
+ it('drops every declaration that could lay the image over the page', () => {
+ assert.equal(
+ allowedImageStyle('position:fixed;inset:0;width:100vw;height:100vh;z-index:9999'),
+ null,
+ );
+ assert.equal(allowedImageStyle('position: absolute; top: 0; left: 0; opacity: 0'), null);
+ });
+
+ it('keeps only the sizing next to a hostile declaration', () => {
+ assert.equal(
+ allowedImageStyle('position:fixed;inset:0;width:320px;height:100vh;z-index:9999'),
+ 'width: 320px',
+ );
+ });
+
+ it('keeps a width and max-width', () => {
+ assert.equal(
+ allowedImageStyle('width: 320px; max-width: 100%'),
+ 'width: 320px; max-width: 100%',
+ );
+ assert.equal(allowedImageStyle('max-width:50%'), 'max-width: 50%');
+ assert.equal(allowedImageStyle('WIDTH: AUTO;'), 'width: auto');
+ });
+
+ it('rejects sizing values that are not a plain length', () => {
+ assert.equal(allowedImageStyle('width: 100vw'), null);
+ assert.equal(allowedImageStyle('width: calc(100vw + 1px)'), null);
+ assert.equal(allowedImageStyle('width: 320px !important'), null);
+ assert.equal(allowedImageStyle('max-width: 500%'), null);
+ assert.equal(allowedImageStyle('width: 99999px'), null);
+ assert.equal(allowedImageStyle('width: expression(alert(1))'), null);
+ });
+
+ it('does not throw on malformed style text', () => {
+ for (const css of ['', ';;;', 'width', ':', 'width:', ':320px', 'a:b:c;;width::1']) {
+ assert.equal(allowedImageStyle(css), null, JSON.stringify(css));
+ }
+ assert.equal(allowedImageStyle(null), null);
+ assert.equal(allowedImageStyle(undefined), null);
+ });
+});
diff --git a/apps/web/src/utils/imageStyle.ts b/apps/web/src/utils/imageStyle.ts
new file mode 100644
index 00000000..d855b2b9
--- /dev/null
+++ b/apps/web/src/utils/imageStyle.ts
@@ -0,0 +1,22 @@
+// An image's inline style is applied for every reader of the text that carries
+// it, so only its sizing survives: any other declaration (position, inset,
+// z-index) could lay the image over the whole page.
+const ALLOWED_PROPERTIES = new Set(['width', 'max-width']);
+
+// A pixel or percentage length, capped like the API's image width, or `auto`.
+const LENGTH = /^(?:auto|[1-9]\d{0,3}px|(?:100|[1-9]\d?)%)$/;
+
+export function allowedImageStyle(css: string | null | undefined): string | null {
+ if (!css) return null;
+ const kept = css.split(';').flatMap((declaration) => {
+ const colon = declaration.indexOf(':');
+ if (colon === -1) return [];
+ const property = declaration.slice(0, colon).trim().toLowerCase();
+ const value = declaration
+ .slice(colon + 1)
+ .trim()
+ .toLowerCase();
+ return ALLOWED_PROPERTIES.has(property) && LENGTH.test(value) ? [`${property}: ${value}`] : [];
+ });
+ return kept.length > 0 ? kept.join('; ') : null;
+}