Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(chat): restrict rendered external links to HTTP and HTTPS (#9465)

James Dam756f491bf5f2
diff --git a/web-app/package.json b/web-app/package.json
index 6e1bf55a5..0f5954628 100644
--- a/web-app/package.json
+++ b/web-app/package.json
@@ -120,6 +120,7 @@
"@types/lodash.clonedeep": "4.5.9",
"@types/lodash.debounce": "4.0.9",
"@types/matter-js": "^0",
+ "@types/hast": "^3.0.4",
"@types/mdast": "^4.0.4",
"@types/node": "22.14.1",
"@types/react": "19.1.2",
diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsx
index 0a6d95863..17e67f172 100644
--- a/web-app/src/containers/RenderMarkdown.tsx
+++ b/web-app/src/containers/RenderMarkdown.tsx
@@ -18,6 +18,8 @@ import { cjk } from '@streamdown/cjk'
import { code } from '@streamdown/code'
import { mermaid } from '@streamdown/mermaid'
+import { SKIP, visit } from 'unist-util-visit'
+import type { Root } from 'hast'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import rehypeKatex from 'rehype-katex'
@@ -27,6 +29,51 @@ import { CitationLink } from '@/components/CitationLink'
import { WebCitationChip } from '@/components/WebCitationChip'
import { MarkdownTable } from '@/components/MarkdownTable'
+// Do not resolve model-generated links against the app's own origin.
+function isWebLink(href: string | undefined): boolean {
+ if (!href || !/^https?:\/\//i.test(href)) return false
+ try {
+ const { protocol } = new URL(href)
+ return protocol === 'http:' || protocol === 'https:'
+ } catch {
+ return false
+ }
+}
+
+// Citation fragments are model-controlled too: decode defensively and apply the
+// same absolute HTTP(S) policy before letting a chip create its own anchors.
+function webCitationUrl(href: string | undefined): string | undefined {
+ if (!href?.startsWith('#webcite-')) return undefined
+ try {
+ const url = decodeURIComponent(href.slice('#webcite-'.length))
+ return isWebLink(url) ? url : undefined
+ } catch {
+ return undefined
+ }
+}
+
+// The hardener normalizes URLs (including repairing incomplete HTTP schemes)
+// and annotates rejected anchors with " [blocked]". Unwrap them first so only
+// their original, formatted label survives.
+function restrictChatLinks() {
+ return (tree: Root) => {
+ visit(tree, 'element', (node, index, parent) => {
+ if (node.tagName !== 'a') return
+ const href = node.properties.href
+ if (
+ typeof href === 'string' &&
+ (href.startsWith('#cite-') || webCitationUrl(href) || isWebLink(href))
+ ) {
+ return
+ }
+ if (parent && index !== undefined) {
+ parent.children.splice(index, 1, ...node.children)
+ return [SKIP, index]
+ }
+ })
+ }
+}
+
const WEB_CITE_MARKER = /\[\[cite:\s*([^\]\s]+?)\s*\]\]/g
// Models sometimes drop the scheme (e.g. "example.com/x"); normalize to https.
@@ -59,7 +106,7 @@ interface MarkdownProps {
// with a shallow prop compare, and fresh literals here would defeat it, forcing
// a full re-parse + re-highlight on every streamed token.
const REMARK_PLUGINS = [remarkGfm, remarkMath, disableIndentedCodeBlockPlugin]
-const REHYPE_PLUGINS = [rehypeKatex, defaultRehypePlugins.harden]
+const REHYPE_PLUGINS = [rehypeKatex, restrictChatLinks, defaultRehypePlugins.harden]
const STREAMDOWN_PLUGINS = { code, mermaid, cjk }
const STREAMDOWN_CONTROLS = { mermaid: { fullscreen: false } }
const LINK_SAFETY = { enabled: false }
@@ -243,9 +290,14 @@ function RenderMarkdownComponent({
)
}
if (typeof href === 'string' && href.startsWith('#webcite-')) {
- const url = decodeURIComponent(href.slice('#webcite-'.length))
- return <WebCitationChip messageId={messageId} url={url} />
+ const url = webCitationUrl(href)
+ return url ? (
+ <WebCitationChip messageId={messageId} url={url} />
+ ) : (
+ <>{children}</>
+ )
}
+ if (!isWebLink(href)) return <>{children}</>
return <a {...props}>{children}</a>
}
return { a: Anchor, table: MarkdownTable, ...(components ?? {}) } as Components
diff --git a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
index 1b89c1917..52bcf1bd3 100644
--- a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
+++ b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
@@ -489,6 +489,137 @@ describe('RenderMarkdown', () => {
})
})
+ // Exercise the real Streamdown parser and hardener, not a renderer mock:
+ // target/rel on allowed links come from the existing hardener.
+ // Completed-message emphasis normalization inserts an invisible ZWSP; compare
+ // exact visible labels without it (never ignore visible hardener annotations).
+ describe.each([false, true])('chat links (isStreaming=%s)', (isStreaming) => {
+ it.each([
+ 'http://example.com/path?q=1#section',
+ 'https://example.com/path?q=1#section',
+ 'HTTPS://example.com/path',
+ ])('keeps absolute web link %s', (href) => {
+ const { container } = render(
+ <RenderMarkdown
+ content={`[Visit site](${href})`}
+ isStreaming={isStreaming}
+ />
+ )
+ const link = container.querySelector('a')
+ expect(link).toHaveAttribute('href', new URL(href).href)
+ expect(link).toHaveAttribute('target', '_blank')
+ expect(link?.rel.split(/\s+/)).toEqual(
+ expect.arrayContaining(['noopener', 'noreferrer'])
+ )
+ expect(link).toHaveTextContent('Visit site')
+ })
+
+ it.each([
+ 'mailto:[email protected]',
+ 'irc://example.com/channel',
+ 'blob:https://example.com/id',
+ 'jan://settings',
+ 'custom:action',
+ '/settings',
+ './settings',
+ '../settings',
+ 'settings',
+ '//example.com/path',
+ '#section',
+ 'javascript:alert%281%29',
+ 'data:text/html,test',
+ 'file:///etc/passwd',
+ 'https://',
+ 'https://%5Binvalid',
+ 'https:/example.com',
+ 'http:example.com',
+ ])('renders %s as a non-actionable label', (href) => {
+ const { container } = render(
+ <RenderMarkdown
+ content={`[**Bold** and *emphasized* label](${href})`}
+ isStreaming={isStreaming}
+ />
+ )
+ expect(container.textContent?.replace(/\u200b/g, '')).toBe('Bold and emphasized label')
+ expect(
+ container.querySelector('strong, [data-streamdown="strong"]')
+ ).toHaveTextContent('Bold')
+ expect(container.querySelector('em')).toHaveTextContent('emphasized')
+ expect(container.querySelector('a')).toBeNull()
+ expect(container.querySelector('button, [role="link"]')).toBeNull()
+ })
+
+ it.each([
+ '#webcite-mailto%3Aperson%40example.com',
+ '#webcite-javascript%3Aalert%281%29',
+ '#webcite-data%3Atext%2Fhtml%2Ctest',
+ '#webcite-file%3A%2F%2F%2Fetc%2Fpasswd',
+ '#webcite-jan%3A%2F%2Fsettings',
+ '#webcite-%2Fsettings',
+ '#webcite-%2F%2Fexample.com',
+ '#webcite-https%3A%2Fexample.com',
+ '#webcite-https%3A%2F%2F',
+ '#webcite-https%3A%2F%2F%5Binvalid',
+ '#webcite-%E0%A4%A',
+ '#webcite-%FF',
+ '#webcite-%',
+ '#webcite-',
+ '#webcite-https%253A%252F%252Fexample.com',
+ ])('renders forged or malformed citation %s as its original label', (href) => {
+ const { container } = render(
+ <RenderMarkdown
+ content={`[**Bold** and *emphasized* label](${href})`}
+ isStreaming={isStreaming}
+ />
+ )
+ expect(container.textContent?.replace(/\u200b/g, '')).toBe('Bold and emphasized label')
+ expect(
+ container.querySelector('strong, [data-streamdown="strong"]')
+ ).toHaveTextContent('Bold')
+ expect(container.querySelector('em')).toHaveTextContent('emphasized')
+ expect(container.querySelector('a, button, [role="link"], img')).toBeNull()
+ })
+
+ it('keeps exact labels and formatting after content updates', async () => {
+ const { container, rerender } = render(
+ <RenderMarkdown content="[Original](https://example.com)" isStreaming={isStreaming} />
+ )
+ rerender(
+ <RenderMarkdown
+ content="[**Bold** and *emphasized* label](mailto:[email protected]) [second](#webcite-%FF)"
+ isStreaming={isStreaming}
+ />
+ )
+ await waitFor(() =>
+ expect(container.textContent?.replace(/\u200b/g, '')).toBe('Bold and emphasized label second')
+ )
+ expect(
+ container.querySelector('strong, [data-streamdown="strong"]')
+ ).toHaveTextContent('Bold')
+ expect(container.querySelector('em')).toHaveTextContent('emphasized')
+ expect(container.querySelector('a, button, [role="link"], img')).toBeNull()
+ })
+
+ it('preserves internal document and web citation routing', () => {
+ const { container } = render(
+ <RenderMarkdown
+ content={'[1](#cite-message-1) [cite](#webcite-https%3A%2F%2Fexample.com%2Fsource)'}
+ isStreaming={isStreaming}
+ />
+ )
+ // With no grounding-store entry, CitationLink retains its fallback anchor.
+ expect(
+ container.querySelector('a[href="#cite-message-1"]')
+ ).toHaveTextContent('1')
+ const webCitation = container.querySelector(
+ 'a[href="https://example.com/source"]'
+ )
+ expect(webCitation?.querySelector('img')).toBeTruthy()
+ expect(webCitation).toHaveAttribute('target', '_blank')
+ })
+ })
+
describe('web citation markers', () => {
it('renders a [[cite:URL]] marker as a favicon link to the source', () => {
const { container } = render(
diff --git a/yarn.lock b/yarn.lock
index ab0b0c4c6..3cc15344a 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1997,6 +1997,7 @@ __metadata:
"@testing-library/react": "npm:16.3.0"
"@testing-library/user-event": "npm:14.6.1"
"@types/culori": "npm:2.1.1"
+ "@types/hast": "npm:^3.0.4"
"@types/istanbul-lib-report": "npm:3.0.3"
"@types/istanbul-reports": "npm:3.0.4"
"@types/lodash.clonedeep": "npm:4.5.9"