Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(collab): sanitized markdown keeps angle-bracket text and working footnotes (#2177)

Maurice348d584a02a6
diff --git a/client/src/components/Collab/CollabNotes.test.tsx b/client/src/components/Collab/CollabNotes.test.tsx
index 1ac19112d..34f01347f 100644
--- a/client/src/components/Collab/CollabNotes.test.tsx
+++ b/client/src/components/Collab/CollabNotes.test.tsx
@@ -1327,6 +1327,14 @@ function wsHandler(): (msg: Record<string, unknown>) => void {
return (addListener as ReturnType<typeof vi.fn>).mock.calls[0][0];
}
+function openedNoteBody(): Promise<HTMLElement> {
+ return waitFor(() => {
+ const md = document.querySelector('.collab-note-md-full');
+ if (!md) throw new Error('view modal not open yet');
+ return md as HTMLElement;
+ });
+}
+
describe('CollabNotes details', () => {
let addToast: ReturnType<typeof vi.fn<AddToast>>;
let filesChanged: number;
@@ -1912,4 +1920,31 @@ describe('CollabNotes details', () => {
// …and both rejected writes are one message, not one each.
expect(addToast).toHaveBeenCalledTimes(1);
});
+
+ it('FE-W5CNT-033: a placeholder in angle brackets survives sanitizing', async () => {
+ const user = userEvent.setup();
+ serveNotes({ notes: [buildNote({ id: 7, title: 'Hotel', content: 'Zimmernummer <TBD> bestaetigen' })] });
+ render(<CollabNotes {...defaultProps} />);
+ await screen.findByText('Hotel');
+ await user.click(screen.getByTitle('collab.notes.expand'));
+ const full = await openedNoteBody();
+ // Notes written before markdown rendering existed keep reading the way they
+ // were typed (#2177).
+ expect(within(full).getByText('Zimmernummer <TBD> bestaetigen')).toBeInTheDocument();
+ });
+
+ it('FE-W5CNT-034: a footnote reference lands on the footnote instead of a new tab', async () => {
+ const user = userEvent.setup();
+ serveNotes({ notes: [buildNote({ id: 8, title: 'Booking', content: 'Hotel gebucht[^1]\n\n[^1]: Bestaetigung ABC123' })] });
+ render(<CollabNotes {...defaultProps} />);
+ await screen.findByText('Booking');
+ await user.click(screen.getByTitle('collab.notes.expand'));
+ const full = await openedNoteBody();
+
+ const ref = within(full).getByRole('link', { name: '1' });
+ const href = ref.getAttribute('href')!;
+ expect(href.startsWith('#')).toBe(true);
+ expect(full.querySelector(`[id="${href.slice(1)}"]`)).not.toBeNull();
+ expect(ref).not.toHaveAttribute('target');
+ });
});
diff --git a/client/src/components/Collab/CollabNotes.tsx b/client/src/components/Collab/CollabNotes.tsx
index 0c72e3978..434373379 100644
--- a/client/src/components/Collab/CollabNotes.tsx
+++ b/client/src/components/Collab/CollabNotes.tsx
@@ -2,8 +2,7 @@ import { useState, useEffect, useCallback, useMemo } from 'react'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
-import rehypeSanitize from 'rehype-sanitize'
-import { markdownLinkComponents } from '../shared/markdownLink'
+import { sanitizedMarkdownComponents, sanitizedMarkdownPlugins } from '../shared/markdownSanitize'
import { createPortal } from 'react-dom'
import { Plus, Pencil, X, StickyNote, Settings } from 'lucide-react'
import { collabApi } from '../../api/client'
@@ -447,7 +446,7 @@ function ViewNoteModal(S: NotesState) {
</div>
</div>
<div className="collab-note-md-full" style={{ padding: '16px 20px', overflowY: 'auto', fontSize: 'calc(14px * var(--fs-scale-body, 1))', color: 'var(--text-primary)', lineHeight: 1.7 }}>
- <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={[rehypeSanitize]} components={markdownLinkComponents}>{viewingNote.content || ''}</Markdown>
+ <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={sanitizedMarkdownPlugins} components={sanitizedMarkdownComponents}>{viewingNote.content || ''}</Markdown>
{(viewingNote.attachments || []).length > 0 && (
<div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--border-primary)' }}>
<div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>{t('files.title')}</div>
diff --git a/client/src/components/Collab/CollabNotesCard.tsx b/client/src/components/Collab/CollabNotesCard.tsx
index 1bfe466ff..4da68ee0e 100644
--- a/client/src/components/Collab/CollabNotesCard.tsx
+++ b/client/src/components/Collab/CollabNotesCard.tsx
@@ -3,8 +3,7 @@ import { avatarSrc } from '../../utils/avatarSrc'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
-import rehypeSanitize from 'rehype-sanitize'
-import { markdownLinkComponents } from '../shared/markdownLink'
+import { sanitizedMarkdownPlugins, sanitizedMarkdownComponents } from '../shared/markdownSanitize'
import { Trash2, Pin, PinOff, Pencil, Maximize2 } from 'lucide-react'
import { FONT } from './CollabNotes.constants'
import { AuthedImg } from './CollabNotesAuthedImg'
@@ -144,7 +143,7 @@ export function NoteCard({ note, currentUser, canEdit, onUpdate, onDelete, onEdi
maxHeight: '4.5em', overflow: 'hidden',
wordBreak: 'break-word', fontFamily: FONT,
}}>
- <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={[rehypeSanitize]} components={markdownLinkComponents}>{note.content}</Markdown>
+ <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={sanitizedMarkdownPlugins} components={sanitizedMarkdownComponents}>{note.content}</Markdown>
</div>
)}
</div>
diff --git a/client/src/components/Collab/CollabPolls.test.tsx b/client/src/components/Collab/CollabPolls.test.tsx
index 16ecbf98b..59491533d 100644
--- a/client/src/components/Collab/CollabPolls.test.tsx
+++ b/client/src/components/Collab/CollabPolls.test.tsx
@@ -851,4 +851,27 @@ describe('CollabPolls markdown & multiline', () => {
expect(label.style.overflowWrap).toBe('anywhere');
expect(label.style.minWidth).toBe('0px');
});
+
+ it('FE-COMP-POLLS-023: a placeholder in angle brackets survives sanitizing', async () => {
+ server.use(
+ http.get('/api/trips/1/collab/polls', () =>
+ HttpResponse.json({ polls: [buildPoll({ question: 'Treffpunkt <noch offen> oder Hotel?' })] }),
+ ),
+ );
+ render(<CollabPolls {...defaultProps} />);
+ // Questions written before markdown rendering existed must keep reading the
+ // way they were typed, and they cannot be edited afterwards (#2177).
+ expect(await screen.findByText('Treffpunkt <noch offen> oder Hotel?')).toBeInTheDocument();
+ });
+
+ it('FE-COMP-POLLS-024: a script tag is shown as text, never as an element', async () => {
+ server.use(
+ http.get('/api/trips/1/collab/polls', () =>
+ HttpResponse.json({ polls: [buildPoll({ question: 'Plan <script>alert("xss")</script>' })] }),
+ ),
+ );
+ render(<CollabPolls {...defaultProps} />);
+ expect(await screen.findByText('Plan <script>alert("xss")</script>')).toBeInTheDocument();
+ expect(document.querySelector('script')).toBeNull();
+ });
});
diff --git a/client/src/components/Collab/CollabPolls.tsx b/client/src/components/Collab/CollabPolls.tsx
index 042f16a12..276931c25 100644
--- a/client/src/components/Collab/CollabPolls.tsx
+++ b/client/src/components/Collab/CollabPolls.tsx
@@ -3,8 +3,7 @@ import { Plus, Trash2, X, Check, BarChart3, Lock, Clock } from 'lucide-react'
import ReactMarkdown, { type Components } from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
-import rehypeSanitize from 'rehype-sanitize'
-import { markdownLinkComponents } from '../shared/markdownLink'
+import { sanitizedMarkdownComponents, sanitizedMarkdownPlugins } from '../shared/markdownSanitize'
import { collabApi } from '../../api/client'
import { addListener, removeListener } from '../../api/websocket'
import { useTranslation } from '../../i18n'
@@ -43,10 +42,11 @@ const FONT = "var(--font-system)"
// Block styling for the markdown question (#2177). Tailwind's preflight resets
// headings/lists, so the sizes are set here — in em, on purpose: they scale with
// the surrounding calc(13px * var(--fs-scale-body)) base, so the user's
-// text-size setting keeps working. Links come from markdownLinkComponents
-// (#1629): new tab plus rel protection, this is cross-user content.
+// text-size setting keeps working. Links and sanitizing come from
+// markdownSanitize (#1629): new tab plus rel protection, this is cross-user
+// content.
const pollMarkdownComponents: Components = {
- ...markdownLinkComponents,
+ ...sanitizedMarkdownComponents,
p: ({ children }) => (
<p style={{ margin: '0 0 0.55em' }}>{children}</p>
),
@@ -256,7 +256,7 @@ function PollCard({ poll, currentUser, canEdit, onVote, onClose, onDelete, t }:
}}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 700, color: 'var(--text-primary)', lineHeight: 1.35, wordBreak: 'break-word' }}>
- <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={[rehypeSanitize]} components={pollMarkdownComponents}>
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={sanitizedMarkdownPlugins} components={pollMarkdownComponents}>
{poll.question}
</ReactMarkdown>
</div>
diff --git a/client/src/components/shared/markdownSanitize.tsx b/client/src/components/shared/markdownSanitize.tsx
new file mode 100644
index 000000000..8d78abaa9
--- /dev/null
+++ b/client/src/components/shared/markdownSanitize.tsx
@@ -0,0 +1,51 @@
+import type { Components, Options } from 'react-markdown'
+import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'
+
+type HastNode = { type: string; children?: HastNode[] }
+
+/**
+ * react-markdown never builds an element out of raw HTML, it shows the markup
+ * verbatim instead. It does that after the rehype plugins ran, though, so the
+ * sanitizer gets the raw nodes first and drops them without a trace: a note
+ * reading "Zimmernummer <TBD>" loses the placeholder on screen while the stored
+ * text still has it (#2177). Turning raw into text up front keeps it readable
+ * and still yields no element.
+ */
+function rehypeRawAsText() {
+ return (tree: HastNode) => {
+ const walk = (node: HastNode) => {
+ if (node.type === 'raw') node.type = 'text'
+ for (const child of node.children || []) walk(child)
+ }
+ walk(tree)
+ }
+}
+
+// remark-gfm already writes footnote ids with the `user-content-` prefix, and
+// the hrefs pointing at them carry it too. Clobbering them a second time only
+// makes target and reference disagree.
+const schema = { ...defaultSchema, clobberPrefix: '' }
+
+export const sanitizedMarkdownPlugins: NonNullable<Options['rehypePlugins']> = [
+ rehypeRawAsText,
+ [rehypeSanitize, schema],
+]
+
+/**
+ * Links as in markdownLinkComponents (#1629): own tab plus `rel` protection.
+ * The exception is a footnote or heading link, which points inside the text
+ * that is already on screen, so opening a tab for it would only reload the trip
+ * somewhere else.
+ */
+export const sanitizedMarkdownComponents: Components = {
+ a: ({ children, href, ...rest }) =>
+ href?.startsWith('#') ? (
+ <a {...rest} href={href}>
+ {children}
+ </a>
+ ) : (
+ <a {...rest} href={href} target="_blank" rel="noopener noreferrer nofollow">
+ {children}
+ </a>
+ ),
+}
diff --git a/client/src/mobile/screens/trip/tabs/MCollabNotes.tsx b/client/src/mobile/screens/trip/tabs/MCollabNotes.tsx
index 647b56f14..5a47312ed 100644
--- a/client/src/mobile/screens/trip/tabs/MCollabNotes.tsx
+++ b/client/src/mobile/screens/trip/tabs/MCollabNotes.tsx
@@ -2,8 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
-import rehypeSanitize from 'rehype-sanitize'
-import { markdownLinkComponents } from '../../../../components/shared/markdownLink'
+import { sanitizedMarkdownPlugins, sanitizedMarkdownComponents } from '../../../../components/shared/markdownSanitize'
import { Check, FileText, Paperclip, Pin, PinOff, Plus, StickyNote, Trash2, X } from 'lucide-react'
import MDancingTrek from '../../../components/MDancingTrek'
import { collabApi } from '../../../../api/client'
@@ -338,7 +337,7 @@ function NoteCardRow({ note, color, canEdit, onTap, onTogglePin, onDelete, t }:
<button type="button" onClick={onTap} className="block w-full px-3 pb-3 pt-[9px] text-left">
{note.content && (
<div className="line-clamp-3 font-geist text-[0.75rem] leading-[1.5] text-m-muted [&_a]:underline [&_ol]:list-decimal [&_ol]:pl-4 [&_p]:mb-1 [&_strong]:font-bold [&_ul]:list-disc [&_ul]:pl-4">
- <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={[rehypeSanitize]} components={markdownLinkComponents}>{note.content}</Markdown>
+ <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={sanitizedMarkdownPlugins} components={sanitizedMarkdownComponents}>{note.content}</Markdown>
</div>
)}
<div className={`flex items-center gap-[6px] ${note.content ? 'mt-2' : ''}`}>
@@ -602,7 +601,7 @@ function NoteViewSheet({ open, note, onClose, t }: {
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-4 pt-1">
{snapshot?.content && (
<div className="font-geist text-[0.8125rem] leading-[1.6] text-m-ink [&_a]:underline [&_ol]:list-decimal [&_ol]:pl-5 [&_p]:mb-2 [&_strong]:font-bold [&_ul]:list-disc [&_ul]:pl-5">
- <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={[rehypeSanitize]} components={markdownLinkComponents}>{snapshot.content}</Markdown>
+ <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={sanitizedMarkdownPlugins} components={sanitizedMarkdownComponents}>{snapshot.content}</Markdown>
</div>
)}
{(snapshot?.attachments.length ?? 0) > 0 && (
diff --git a/client/src/mobile/screens/trip/tabs/MCollabPolls.tsx b/client/src/mobile/screens/trip/tabs/MCollabPolls.tsx
index 189ebe7be..c5031ff5d 100644
--- a/client/src/mobile/screens/trip/tabs/MCollabPolls.tsx
+++ b/client/src/mobile/screens/trip/tabs/MCollabPolls.tsx
@@ -3,9 +3,8 @@ import { BarChart3, Check, Clock, Lock, Plus, Trash2, X } from 'lucide-react'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
-import rehypeSanitize from 'rehype-sanitize'
+import { sanitizedMarkdownPlugins, sanitizedMarkdownComponents } from '../../../../components/shared/markdownSanitize'
import MDancingTrek from '../../../components/MDancingTrek'
-import { markdownLinkComponents } from '../../../../components/shared/markdownLink'
import { collabApi } from '../../../../api/client'
import { addListener, removeListener } from '../../../../api/websocket'
import { useAuthStore } from '../../../../store/authStore'
@@ -262,7 +261,7 @@ function PollCardRow({ poll, canEdit, currentUserId, t, onVote, onClosePoll, onD
inert, links open in a new tab with rel protection (#1629).
Heading/list sizes are em-based so they follow the text scale. */}
<div className="break-words text-[0.8125rem] font-bold leading-[1.35] text-m-ink [&_a]:underline [&_h1]:mb-1 [&_h1]:text-[1.35em] [&_h1]:leading-[1.2] [&_h2]:mb-1 [&_h2]:text-[1.2em] [&_h2]:leading-[1.25] [&_h3]:mb-1 [&_h3]:text-[1.1em] [&_h3]:leading-[1.3] [&_ol]:list-decimal [&_ol]:pl-4 [&_p]:mb-1 [&_ul]:list-disc [&_ul]:pl-4">
- <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={[rehypeSanitize]} components={markdownLinkComponents}>
+ <Markdown remarkPlugins={[remarkGfm, remarkBreaks]} rehypePlugins={sanitizedMarkdownPlugins} components={sanitizedMarkdownComponents}>
{poll.question}
</Markdown>
</div>