diff --git a/cli/src/modules/common/generatedImages.test.ts b/cli/src/modules/common/generatedImages.test.ts index 4f465b19..6672cc37 100644 --- a/cli/src/modules/common/generatedImages.test.ts +++ b/cli/src/modules/common/generatedImages.test.ts @@ -1,9 +1,16 @@ import { describe, expect, it } from 'vitest' import { mkdirSync, writeFileSync } from 'node:fs' +import { execFile, spawn } from 'node:child_process' +import { once } from 'node:events' +import { promisify } from 'node:util' import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { clearGeneratedImages, decodeGeneratedImageBase64, detectAudioMimeType, detectDisplayMediaMimeType, detectImageMimeType, detectVideoMimeType, getGeneratedImage, MAX_GENERATED_IMAGE_BASE64_CHARS, MAX_GENERATED_IMAGE_BYTES, readBoundedRegularFile, registerGeneratedImage, registerGeneratedImageFromAcpBlock, registerGeneratedImageFromPath, safeAcpFileName } from './generatedImages' +const execFileAsync = promisify(execFile) + describe('generatedImages', () => { it('detects supported image MIME types from file bytes', () => { expect(detectImageMimeType(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toBe('image/png') @@ -244,6 +251,46 @@ describe('generatedImages', () => { await expect(readBoundedRegularFile(path, MAX_GENERATED_IMAGE_BYTES)).resolves.toHaveLength(1024) }) + it.skipIf(process.platform === 'win32')('rejects a POSIX FIFO without waiting for a writer', async () => { + const dir = await mkdtemp(join(tmpdir(), 'hapi-bounded-fifo-')) + const fifo = join(dir, 'image.png') + try { + await execFileAsync('mkfifo', [fifo]) + const moduleUrl = pathToFileURL(join(process.cwd(), 'src/modules/common/generatedImages.ts')).href + const script = ` + const { readBoundedRegularFile } = await import(${JSON.stringify(moduleUrl)}) + try { + await readBoundedRegularFile(process.env.HAPI_FIFO_PATH, 1024) + console.log('unexpected success') + } catch (error) { + console.log(error instanceof Error ? error.message : String(error)) + } + ` + const bunExec = process.env.HAPI_BUN_EXEC + if (!bunExec) throw new Error('HAPI_BUN_EXEC is required for the FIFO subprocess test') + const child = spawn(bunExec, ['--eval', script], { + cwd: process.cwd(), + env: { ...process.env, HAPI_FIFO_PATH: fifo }, + stdio: ['ignore', 'pipe', 'pipe'], + }) + const stdout: Buffer[] = [] + child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk)) + const result = await Promise.race([ + once(child, 'close').then(([code]) => ({ timedOut: false, code: code as number | null })), + new Promise<{ timedOut: true }>((resolve) => setTimeout(() => resolve({ timedOut: true }), 2000)), + ]) + if (result.timedOut) { + child.kill('SIGKILL') + await once(child, 'close').catch(() => undefined) + throw new Error('bounded FIFO read timed out') + } + expect(result.code).toBe(0) + expect(Buffer.concat(stdout).toString()).toContain('Path is not a regular file') + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) + it('safeAcpFileName rejects data URIs and strips signed URL query secrets', async () => { expect(safeAcpFileName('data:image/png;base64,AAAA')).toBeNull() expect(safeAcpFileName('https://cdn.example/img/shot.png?token=secret')).toBe('shot.png') diff --git a/cli/src/modules/common/generatedImages.ts b/cli/src/modules/common/generatedImages.ts index bc048d07..f0dd744a 100644 --- a/cli/src/modules/common/generatedImages.ts +++ b/cli/src/modules/common/generatedImages.ts @@ -1,6 +1,6 @@ import { basename, extname } from 'node:path' -import { fileURLToPath } from 'node:url' import { constants } from 'node:fs' +import { fileURLToPath } from 'node:url' import { open } from 'node:fs/promises' import { randomUUID } from 'node:crypto' import { asString, isObject } from '@hapi/protocol' @@ -13,9 +13,12 @@ import { asString, isObject } from '@hapi/protocol' * or other special file from hanging the caller before its type can be checked. */ export async function readBoundedRegularFile(path: string, maxBytes: number): Promise { + // O_NONBLOCK prevents opening a POSIX FIFO without a writer from hanging + // the session file RPC before the regular-file check can run. Windows does + // not expose the same FIFO open semantics, so retain its normal read flag. const flags = process.platform === 'win32' ? 'r' - : constants.O_RDONLY | constants.O_NONBLOCK + : constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) const handle = await open(path, flags) try { const info = await handle.stat() diff --git a/cli/src/modules/common/handlers/files.test.ts b/cli/src/modules/common/handlers/files.test.ts index 09354717..7dd0064b 100644 --- a/cli/src/modules/common/handlers/files.test.ts +++ b/cli/src/modules/common/handlers/files.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mkdir, rm, stat, writeFile } from 'fs/promises' +import { mkdir, rm, stat, symlink, truncate, writeFile } from 'fs/promises' import { join } from 'path' import { tmpdir } from 'os' import { RpcHandlerManager } from '../../../api/rpc/RpcHandlerManager' @@ -46,4 +46,98 @@ describe('file RPC handlers', () => { expect(parsed.size).toBe(expectedStats.size) expect(parsed.modified).toBe(expectedStats.mtime.getTime()) }) + + it('rejects bounded reads before loading an oversized file', async () => { + const filePath = join(rootDir, 'large.png') + await writeFile(filePath, Buffer.alloc(32)) + + const response = await rpc.handleRequest({ + method: 'session-test:readFile', + params: JSON.stringify({ path: 'large.png', maxBytes: 16 }) + }) + const parsed = JSON.parse(response) as { success: boolean; error?: string } + + expect(parsed.success).toBe(false) + expect(parsed.error).toContain('too large') + }) + + it('rejects bounded reads of non-regular files', async () => { + const directoryPath = join(rootDir, 'directory.png') + await mkdir(directoryPath) + + const response = await rpc.handleRequest({ + method: 'session-test:readFile', + params: JSON.stringify({ path: 'directory.png', maxBytes: 1024 }) + }) + const parsed = JSON.parse(response) as { success: boolean; error?: string } + + expect(parsed.success).toBe(false) + expect(parsed.error).toContain('regular file') + }) + + it('keeps bounded reads within the limit when the file is sparse and oversized', async () => { + const filePath = join(rootDir, 'growth.png') + await writeFile(filePath, Buffer.from('small')) + await truncate(filePath, 32) + + const response = await rpc.handleRequest({ + method: 'session-test:readFile', + params: JSON.stringify({ path: 'growth.png', maxBytes: 16 }) + }) + const parsed = JSON.parse(response) as { success: boolean; error?: string } + + expect(parsed.success).toBe(false) + expect(parsed.error).toContain('too large') + }) + + it('does not follow a symlink to a non-regular target for bounded reads', async () => { + const target = join(rootDir, 'target-directory') + const link = join(rootDir, 'linked.png') + await mkdir(target) + try { + await symlink(target, link, process.platform === 'win32' ? 'junction' : 'dir') + } catch { + return + } + + const response = await rpc.handleRequest({ + method: 'session-test:readFile', + params: JSON.stringify({ path: 'linked.png', maxBytes: 1024 }) + }) + const parsed = JSON.parse(response) as { success: boolean; error?: string } + + expect(parsed.success).toBe(false) + expect(parsed.error).toContain('regular file') + }) + + it('rejects bounded reads through a symlink to an outside regular file', async () => { + const outsideDir = await createTempDir('hapi-file-handler-outside') + const outsidePath = join(outsideDir, 'secret.png') + const link = join(rootDir, 'linked-secret.png') + await writeFile(outsidePath, Buffer.from('secret')) + + try { + if (process.platform === 'win32') { + await symlink(outsidePath, link, 'file') + } else { + await symlink(outsidePath, link) + } + } catch { + await rm(outsideDir, { recursive: true, force: true }) + return + } + + try { + const response = await rpc.handleRequest({ + method: 'session-test:readFile', + params: JSON.stringify({ path: 'linked-secret.png', maxBytes: 1024 }) + }) + const parsed = JSON.parse(response) as { success: boolean; error?: string } + + expect(parsed.success).toBe(false) + expect(parsed.error).toContain('outside') + } finally { + await rm(outsideDir, { recursive: true, force: true }) + } + }) }) diff --git a/cli/src/modules/common/handlers/files.ts b/cli/src/modules/common/handlers/files.ts index 282e8d7b..02623edc 100644 --- a/cli/src/modules/common/handlers/files.ts +++ b/cli/src/modules/common/handlers/files.ts @@ -1,16 +1,17 @@ import { logger } from '@/ui/logger' -import { readFile, stat, writeFile } from 'fs/promises' +import { readFile, realpath, stat, writeFile } from 'fs/promises' import { createHash } from 'crypto' -import { resolve } from 'path' +import { isAbsolute, relative, resolve, sep } from 'path' import type { FileReadResponse, GeneratedImageResponse } from '@hapi/protocol/apiTypes' import { RPC_METHODS } from '@hapi/protocol/rpcMethods' import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager' import { validatePath } from '../pathSecurity' -import { getGeneratedImage } from '../generatedImages' +import { getGeneratedImage, readBoundedRegularFile } from '../generatedImages' import { getErrorMessage, rpcError } from '../rpcResponses' interface ReadFileRequest { path: string + maxBytes?: number } type ReadFileResponse = FileReadResponse @@ -33,6 +34,18 @@ interface WriteFileResponse { error?: string } +async function resolveReadablePath(path: string, workingDirectory: string): Promise { + const [realWorkingDirectory, realPath] = await Promise.all([ + realpath(workingDirectory), + realpath(path), + ]) + const relativePath = relative(realWorkingDirectory, realPath) + if (relativePath === '..' || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) { + throw new Error('Access denied: resolved path is outside the working directory') + } + return realPath +} + export function registerFileHandlers(rpcHandlerManager: RpcHandlerManager, workingDirectory: string): void { rpcHandlerManager.registerHandler(RPC_METHODS.ReadFile, async (data) => { logger.debug('Read file request:', data.path) @@ -43,15 +56,21 @@ export function registerFileHandlers(rpcHandlerManager: RpcHandlerManager, worki } try { - const resolvedPath = resolve(workingDirectory, data.path) - const stats = await stat(resolvedPath) - const buffer = await readFile(resolvedPath) + const resolvedPath = await resolveReadablePath(resolve(workingDirectory, data.path), workingDirectory) + const maxBytes = typeof data.maxBytes === 'number' && Number.isFinite(data.maxBytes) && data.maxBytes > 0 + ? Math.min(Math.floor(data.maxBytes), 10 * 1024 * 1024) + : undefined + const stats = maxBytes === undefined ? await stat(resolvedPath) : undefined + const buffer = maxBytes === undefined + ? await readFile(resolvedPath) + : await readBoundedRegularFile(resolvedPath, maxBytes) + const finalStats = maxBytes === undefined ? stats! : await stat(resolvedPath) const content = buffer.toString('base64') return { success: true, content, - size: stats.size, - modified: stats.mtime.getTime() + size: finalStats.size, + modified: finalStats.mtime.getTime() } } catch (error) { logger.debug('Failed to read file:', error) diff --git a/cli/src/modules/common/workspaceFileHandlers.ts b/cli/src/modules/common/workspaceFileHandlers.ts index a2860a44..b1aed458 100644 --- a/cli/src/modules/common/workspaceFileHandlers.ts +++ b/cli/src/modules/common/workspaceFileHandlers.ts @@ -27,6 +27,7 @@ export type WorkspaceFilePathPolicy = { type WorkspaceReadFileRequest = { cwd?: unknown path?: unknown + maxBytes?: unknown } type WorkspaceListDirectoryRequest = { @@ -180,7 +181,11 @@ export function registerWorkspaceFileHandlers( if (!stats.isFile()) { throw new Error('Path is not a regular file') } - const buffer = await readBoundedRegularFile(resolved.path, MAX_WORKSPACE_FILE_BYTES) + const requestedMaxBytes = typeof data.maxBytes === 'number' && Number.isFinite(data.maxBytes) && data.maxBytes > 0 + ? Math.floor(data.maxBytes) + : MAX_WORKSPACE_FILE_BYTES + const maxBytes = Math.min(requestedMaxBytes, MAX_WORKSPACE_FILE_BYTES) + const buffer = await readBoundedRegularFile(resolved.path, maxBytes) return { success: true, content: buffer.toString('base64'), diff --git a/e2e/file-md-preview.spec.ts b/e2e/file-md-preview.spec.ts index 7456ade0..89f45679 100644 --- a/e2e/file-md-preview.spec.ts +++ b/e2e/file-md-preview.spec.ts @@ -20,6 +20,8 @@ test.describe('file markdown preview e2e', () => { await expect(page.getByRole('heading', { name: 'Teams and channels' })).toBeVisible() await expect(page.getByRole('cell', { name: 'general' })).toBeVisible() await expect(page.locator('.aui-md-codeblock')).toBeVisible() + await expect(page.getByRole('link', { name: 'Related note' })).toHaveAttribute('href', /\/sessions\/session-1\/file\?path=/) + await expect(page.getByRole('img', { name: 'Page 001' })).toHaveAttribute('src', /^data:image\/png;base64,/) await page.getByTestId('markdown-mode-source').click() await expect(page.getByTestId('markdown-source-view')).toContainText('# Teams and channels') @@ -30,4 +32,16 @@ test.describe('file markdown preview e2e', () => { await page.screenshot({ path: SCREENSHOT_PATH, fullPage: true }) }) + + test('routes relative Markdown links through memory history', async ({ page }) => { + await page.goto('/e2e-fixtures/file-md-preview-fixture.html') + await page.getByRole('link', { name: 'Related note' }).click() + await expect(page.getByTestId('file-target-route')).toBeVisible() + }) + + test('routes session references through memory history', async ({ page }) => { + await page.goto('/e2e-fixtures/file-md-preview-fixture.html') + await page.getByRole('link', { name: 'Session reference' }).click() + await expect(page.getByTestId('session-target-route')).toBeVisible() + }) }) diff --git a/hub/src/sync/rpcGateway.ts b/hub/src/sync/rpcGateway.ts index 03172bb6..4b98fae1 100644 --- a/hub/src/sync/rpcGateway.ts +++ b/hub/src/sync/rpcGateway.ts @@ -410,8 +410,8 @@ export class RpcGateway { return await this.sessionRpc(sessionId, RPC_METHODS.GitDiffFile, options) as RpcCommandResponse } - async readSessionFile(sessionId: string, path: string): Promise { - return await this.sessionRpc(sessionId, RPC_METHODS.ReadFile, { path }) as RpcReadFileResponse + async readSessionFile(sessionId: string, path: string, options?: { maxBytes?: number }): Promise { + return await this.sessionRpc(sessionId, RPC_METHODS.ReadFile, { path, ...options }) as RpcReadFileResponse } async readGeneratedImage(sessionId: string, imageId: string): Promise { diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 54f29278..f31eaa0a 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -4425,12 +4425,14 @@ export class SyncEngine { } } - async readSessionFile(sessionId: string, path: string): Promise { + async readSessionFile(sessionId: string, path: string, options?: { maxBytes?: number }): Promise { try { - return await this.rpcGateway.readSessionFile(sessionId, path) + return options === undefined + ? await this.rpcGateway.readSessionFile(sessionId, path) + : await this.rpcGateway.readSessionFile(sessionId, path, options) } catch (error) { return await this.withInactiveWorkspaceFallback(sessionId, error, ({ machineId, cwd }) => - this.rpcGateway.readWorkspaceFile(machineId, { cwd, path }) + this.rpcGateway.readWorkspaceFile(machineId, { cwd, path, ...options }) ) } } diff --git a/hub/src/web/routes/git.test.ts b/hub/src/web/routes/git.test.ts index a368c3ad..514933cd 100644 --- a/hub/src/web/routes/git.test.ts +++ b/hub/src/web/routes/git.test.ts @@ -83,6 +83,25 @@ describe('generated images route', () => { }) }) +describe('session file route', () => { + it('forwards a bounded read size to the session RPC', async () => { + const session = { id: 'session-1', namespace: 'default', active: true, metadata: { path: '/workspace' } } as unknown as Session + let readOptions: { maxBytes?: number } | undefined + const engine = { + resolveSessionAccess: () => ({ ok: true as const, sessionId: 'session-1', session }), + readSessionFile: async (_sessionId: string, _path: string, options?: { maxBytes?: number }) => { + readOptions = options + return { success: true, content: '' } + } + } as unknown as Partial + + const response = await buildApp(engine).request('/api/sessions/session-1/file?path=images%2Fpage.png&maxBytes=1024') + + expect(response.status).toBe(200) + expect(readOptions).toEqual({ maxBytes: 1024 }) + }) +}) + describe('file search route', () => { it('normalizes Windows path separators in search queries before invoking ripgrep', async () => { const session = { diff --git a/hub/src/web/routes/git.ts b/hub/src/web/routes/git.ts index 24dde9c5..7f8bbbcf 100644 --- a/hub/src/web/routes/git.ts +++ b/hub/src/web/routes/git.ts @@ -18,6 +18,10 @@ const filePathSchema = z.object({ path: z.string().min(1) }) +const boundedFileReadSchema = filePathSchema.extend({ + maxBytes: z.coerce.number().int().min(1).max(10 * 1024 * 1024).optional() +}) + const generatedImageSchema = z.object({ imageId: z.string().min(1) }) @@ -149,12 +153,16 @@ export function createGitRoutes(getSyncEngine: () => SyncEngine | null): Hono engine.readSessionFile(sessionResult.sessionId, parsed.data.path)) + const result = await runRpc(() => engine.readSessionFile( + sessionResult.sessionId, + parsed.data.path, + parsed.data.maxBytes === undefined ? undefined : { maxBytes: parsed.data.maxBytes } + )) return c.json(result) }) diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 0b12ec8d..3047d023 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -830,6 +830,7 @@ export type MachinePathsExistsResponse = PathExistsResponse export type WorkspaceReadFileRequest = { cwd: string path: string + maxBytes?: number } export type WorkspaceListDirectoryRequest = { diff --git a/web/e2e-fixtures/chat-markdown-images-fixture.tsx b/web/e2e-fixtures/chat-markdown-images-fixture.tsx new file mode 100644 index 00000000..d5ef105a --- /dev/null +++ b/web/e2e-fixtures/chat-markdown-images-fixture.tsx @@ -0,0 +1,50 @@ +import ReactDOM from 'react-dom/client' +import type { ApiClient } from '../src/api/client' +import { MarkdownRenderer } from '../src/components/MarkdownRenderer' +import { HappyChatProvider, type HappyChatContextValue } from '../src/components/AssistantChat/context' +import { I18nProvider } from '../src/lib/i18n-context' +import '../src/index.css' + +const SVG_CONTENT = 'chat local image' +const SVG_BASE64 = btoa(SVG_CONTENT) +const CONTENT = `# Chat Markdown image fixture + +![Local chart](images/chart.svg) + +![Remote chart](https://example.com/chart.png) + +![Blocked chart](/outside/secret.png)` + +const API = { + readSessionFile: async (_sessionId: string, path: string, _maxBytes?: number) => { + if (path === 'images/chart.svg') { + return { success: true, content: SVG_BASE64, size: SVG_CONTENT.length } + } + return { success: false, error: 'outside workspace' } + }, +} as unknown as ApiClient + +const chatValue: HappyChatContextValue = { + api: API, + sessionId: 'fixture-session', + metadata: { path: '/workspace', host: 'fixture' }, + terminalToolDisplayMode: 'compact', + showSessionSummaryInChat: false, + disabled: false, + onRefresh: () => {}, + hasMoreMessages: false, + isSyncingTail: false, + isLoadingMoreMessages: false, + loadOlderMessagesPreservingScroll: async () => 'loaded', +} + +const root = document.getElementById('root') +if (!root) throw new Error('missing #root') + +ReactDOM.createRoot(root).render( + + + + + +) diff --git a/web/e2e-fixtures/chat-markdown-images.html b/web/e2e-fixtures/chat-markdown-images.html new file mode 100644 index 00000000..93ed98fc --- /dev/null +++ b/web/e2e-fixtures/chat-markdown-images.html @@ -0,0 +1,17 @@ + + + + + + HAPI chat Markdown images e2e fixture + + + +
+ + + diff --git a/web/e2e-fixtures/file-md-preview-fixture.tsx b/web/e2e-fixtures/file-md-preview-fixture.tsx index 7e2f2754..9fd9d526 100644 --- a/web/e2e-fixtures/file-md-preview-fixture.tsx +++ b/web/e2e-fixtures/file-md-preview-fixture.tsx @@ -6,7 +6,11 @@ import React from 'react' import ReactDOM from 'react-dom/client' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { Outlet, createMemoryHistory, createRootRoute, createRoute, createRouter, RouterProvider } from '@tanstack/react-router' +import type { ApiClient } from '../src/api/client' import '../src/index.css' +import { AppContextProvider } from '../src/lib/app-context' import { I18nProvider } from '../src/lib/i18n-context' import { MarkdownRenderer } from '../src/components/MarkdownRenderer' import { @@ -18,6 +22,12 @@ import { useTranslation } from '../src/lib/use-translation' const SAMPLE_MARKDOWN = `# Teams and channels +[Related note](error-notes.md) + +[Session reference](/sessions/session-42) + +![Page 001](images/page-001.png) + | Channel | Purpose | | --- | --- | | general | Day-to-day coordination | @@ -30,6 +40,28 @@ export const ok = true > Preview uses the same markdown pipeline as chat. ` +const ONE_PIXEL_PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=' + +const FILE_PREVIEW_API = { + readSessionFile: async (_sessionId: string, path: string, _maxBytes?: number) => ({ + success: true, + content: path === 'notes/images/page-001.png' ? ONE_PIXEL_PNG : '', + size: path === 'notes/images/page-001.png' ? 68 : 0, + }), + listSessionDirectory: async (_sessionId: string, path?: string) => ({ + success: true, + entries: path === 'notes/images' + ? [{ name: 'page-001.png', type: 'file' as const, size: 68 }] + : [], + }), +} as unknown as ApiClient + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + }, +}) + function FileMarkdownPreviewFixture() { const { t } = useTranslation() const [mode, setMode] = React.useState(() => getInitialMarkdownPreviewMode()) @@ -69,20 +101,59 @@ function FileMarkdownPreviewFixture() { ) : (
- +
)} ) } +function FileTargetRoute() { + return
Opened sibling Markdown file
+} + +function SessionTargetRoute() { + return
Opened session reference
+} + +const rootRoute = createRootRoute({ component: Outlet }) +const fixtureRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: FileMarkdownPreviewFixture, +}) +const fileTargetRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/sessions/$sessionId/file', + component: FileTargetRoute, +}) +const sessionTargetRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/sessions/$sessionId', + component: SessionTargetRoute, +}) +const router = createRouter({ + routeTree: rootRoute.addChildren([fixtureRoute, fileTargetRoute, sessionTargetRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), +}) + const rootEl = document.getElementById('root') if (rootEl) { ReactDOM.createRoot(rootEl).render( - - - + + + + + + + ) } diff --git a/web/e2e/chat-markdown-images.spec.ts b/web/e2e/chat-markdown-images.spec.ts new file mode 100644 index 00000000..5157709f --- /dev/null +++ b/web/e2e/chat-markdown-images.spec.ts @@ -0,0 +1,16 @@ +import { expect, test } from '@playwright/test' + +test('renders local chat Markdown images through the session API', async ({ page }) => { + await page.goto('/e2e-fixtures/chat-markdown-images.html') + + const localImage = page.locator('img[alt="Local chart"]') + await expect(localImage).toHaveCount(1) + await expect(localImage).toHaveAttribute('src', /^data:image\/svg\+xml;base64,/) + + const remoteImage = page.locator('img[alt="Remote chart"]') + await expect(remoteImage).toHaveCount(1) + await expect(remoteImage).toHaveAttribute('src', 'https://example.com/chart.png') + + const blockedImage = page.locator('[data-hapi-markdown-image-fallback="true"][aria-label="Blocked chart"]') + await expect(blockedImage).toHaveCount(1) +}) diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts index bdd3c4ea..c7eb92bc 100644 --- a/web/src/api/client.test.ts +++ b/web/src/api/client.test.ts @@ -12,6 +12,18 @@ describe('ApiClient error mapping', () => { globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch }) + it('passes an optional maxBytes bound to session file reads', async () => { + fetchMock.mockResolvedValueOnce( + new Response(JSON.stringify({ success: true, content: '' }), { status: 200 }) + ) + + const api = new ApiClient('test-token') + await api.readSessionFile('session-1', 'images/page.png', 10 * 1024 * 1024) + + expect(String(fetchMock.mock.calls[0]?.[0])).toContain('path=images%2Fpage.png') + expect(String(fetchMock.mock.calls[0]?.[0])).toContain('maxBytes=10485760') + }) + afterEach(() => { globalThis.fetch = originalFetch }) diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 9440abcc..6fd90fa6 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -499,9 +499,10 @@ export class ApiClient { return await res.blob() } - async readSessionFile(sessionId: string, path: string): Promise { + async readSessionFile(sessionId: string, path: string, maxBytes?: number): Promise { const params = new URLSearchParams() params.set('path', path) + if (maxBytes !== undefined) params.set('maxBytes', String(maxBytes)) return await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/file?${params.toString()}`) } diff --git a/web/src/components/assistant-ui/markdown-image.test.tsx b/web/src/components/assistant-ui/markdown-image.test.tsx new file mode 100644 index 00000000..c3af7ba2 --- /dev/null +++ b/web/src/components/assistant-ui/markdown-image.test.tsx @@ -0,0 +1,121 @@ +import { describe, expect, it, vi } from 'vitest' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import type { ApiClient } from '@/api/client' +import { MarkdownRenderer } from '@/components/MarkdownRenderer' +import { HappyChatProvider, type HappyChatContextValue } from '@/components/AssistantChat/context' +import { I18nProvider } from '@/lib/i18n-context' +import { encodeBase64 } from '@/lib/utils' +import { MAX_MARKDOWN_IMAGE_BYTES } from '@/lib/markdown-file-assets' +import { ChatMarkdownImage } from './markdown-image' + +function chatValue(api: ApiClient, metadataPath: string | null = '/home/ada/coding/hapi'): HappyChatContextValue { + return { + api, + sessionId: 'session-1', + metadata: metadataPath ? { path: metadataPath, host: 'local' } : null, + terminalToolDisplayMode: 'compact', + showSessionSummaryInChat: false, + disabled: false, + onRefresh: () => {}, + hasMoreMessages: false, + isSyncingTail: false, + isLoadingMoreMessages: false, + loadOlderMessagesPreservingScroll: async () => 'loaded', + } +} + +function renderImage(props: { src: string; alt: string; api?: ApiClient; metadataPath?: string | null }) { + const api = props.api ?? ({ readSessionFile: vi.fn() } as unknown as ApiClient) + return render( + + + + + + ) +} + +describe('ChatMarkdownImage', () => { + it('loads a relative workspace image through the authenticated session API', async () => { + const readSessionFile = vi.fn(async () => ({ + success: true, + content: encodeBase64('png-bytes'), + size: 9, + })) + const api = { readSessionFile } as unknown as ApiClient + + renderImage({ src: 'images/chart.png', alt: 'Chart', api }) + + await waitFor(() => expect(screen.getByRole('img', { name: 'Chart', hidden: false }).tagName).toBe('IMG')) + expect(screen.getByRole('img', { name: 'Chart' })).toHaveAttribute('src', 'data:image/png;base64,cG5nLWJ5dGVz') + expect(readSessionFile).toHaveBeenCalledWith('session-1', 'images/chart.png', MAX_MARKDOWN_IMAGE_BYTES) + }) + + it('renders a relative workspace image through the conversation Markdown renderer', async () => { + const readSessionFile = vi.fn(async () => ({ + success: true, + content: encodeBase64('png-bytes'), + size: 9, + })) + const api = { readSessionFile } as unknown as ApiClient + + render( + + + + + + ) + + await waitFor(() => expect(screen.getByRole('img', { name: 'Chart' }).tagName).toBe('IMG')) + expect(readSessionFile).toHaveBeenCalledWith('session-1', 'images/chart.png', MAX_MARKDOWN_IMAGE_BYTES) + }) + + it('loads reachable HTTPS images directly without reading a session file', () => { + const readSessionFile = vi.fn() + const api = { readSessionFile } as unknown as ApiClient + + renderImage({ src: 'https://example.com/chart.png', alt: 'Remote chart', api }) + + expect(screen.getByRole('img', { name: 'Remote chart' })).toHaveAttribute('src', 'https://example.com/chart.png') + expect(readSessionFile).not.toHaveBeenCalled() + }) + + it('shows a fallback when a remote image fails to load', async () => { + renderImage({ src: 'https://example.com/missing.png', alt: 'Missing remote' }) + + const image = screen.getByRole('img', { name: 'Missing remote' }) + fireEvent.error(image) + + await waitFor(() => expect(screen.getByRole('img', { name: 'Missing remote' })).toHaveAttribute('data-hapi-markdown-image-fallback', 'true')) + }) + + it.each([ + ['../outside.png', 'parent traversal'], + ['/etc/secret.png', 'outside absolute path'], + ['data:image/png;base64,ZmFrZQ==', 'data URI'], + ['file:///tmp/secret.png', 'file URI'], + ])('does not read %s (%s)', (src) => { + const readSessionFile = vi.fn() + const api = { readSessionFile } as unknown as ApiClient + + renderImage({ src, alt: 'Blocked image', api }) + + expect(screen.getByRole('img', { name: 'Blocked image' })).toHaveAttribute('data-hapi-markdown-image-fallback', 'true') + expect(readSessionFile).not.toHaveBeenCalled() + }) + + it('keeps an in-workspace absolute path behind the session file API', async () => { + const readSessionFile = vi.fn(async () => ({ + success: true, + content: encodeBase64('png-bytes'), + size: 9, + })) + const api = { readSessionFile } as unknown as ApiClient + + renderImage({ src: '/home/ada/coding/hapi/images/chart.png', alt: 'Absolute chart', api }) + + await waitFor(() => expect(screen.getByRole('img', { name: 'Absolute chart' }).tagName).toBe('IMG')) + expect(readSessionFile).toHaveBeenCalledWith('session-1', '/home/ada/coding/hapi/images/chart.png', MAX_MARKDOWN_IMAGE_BYTES) + }) +}) diff --git a/web/src/components/assistant-ui/markdown-image.tsx b/web/src/components/assistant-ui/markdown-image.tsx new file mode 100644 index 00000000..ac621cd7 --- /dev/null +++ b/web/src/components/assistant-ui/markdown-image.tsx @@ -0,0 +1,122 @@ +import { useEffect, useState, type ComponentPropsWithoutRef } from 'react' +import { useOptionalHappyChatContext } from '@/components/AssistantChat/context' +import { cn } from '@/lib/utils' +import { + getMarkdownImageMimeType, + MAX_MARKDOWN_IMAGE_BYTES, + resolveMarkdownFileImage, + type MarkdownAssetTarget, +} from '@/lib/markdown-file-assets' + +type ChatMarkdownImageTarget = Extract + +function resolveChatMarkdownImage(src: string, workspacePath: string | null | undefined): ChatMarkdownImageTarget { + const target = resolveMarkdownFileImage('.hapi-chat-message.md', src, { workspacePath }) + if (target.kind === 'local' || target.kind === 'remote') return target + return { kind: 'inert', href: src } +} + +function markdownImageFallback(props: { label?: string; source: string; className?: string }) { + return ( + + {props.label || 'Image unavailable'} + + ) +} + +function markdownImageLoading(props: { label?: string; className?: string }) { + return ( + + {props.label || 'Loading image'} + + ) +} + +export function ChatMarkdownImage(props: ComponentPropsWithoutRef<'img'>) { + const { src, alt, onError, className, ...imageProps } = props + const chat = useOptionalHappyChatContext() + const workspacePath = chat?.metadata?.path ?? null + const source = typeof src === 'string' + ? resolveChatMarkdownImage(src, workspacePath) + : { kind: 'inert', href: '' } as const + const localPath = source.kind === 'local' ? source.path : null + const sourceKey = source.kind === 'local' ? source.path : source.href + const api = chat?.api + const sessionId = chat?.sessionId + const [state, setState] = useState<{ key: string; dataUrl: string | null; failed: boolean }>(() => ({ + key: sourceKey, + dataUrl: null, + failed: source.kind === 'inert' || (source.kind === 'local' && (!api || !sessionId)), + })) + + useEffect(() => { + let active = true + if (!localPath || !api || !sessionId) { + setState({ key: sourceKey, dataUrl: null, failed: source.kind !== 'remote' }) + return () => { + active = false + } + } + + setState({ key: sourceKey, dataUrl: null, failed: false }) + void api.readSessionFile(sessionId, localPath, MAX_MARKDOWN_IMAGE_BYTES).then((result) => { + if (!active) return + const mimeType = getMarkdownImageMimeType(localPath) + const tooLarge = result.size !== undefined && result.size > MAX_MARKDOWN_IMAGE_BYTES + if (!result.success || !result.content || !mimeType || tooLarge) { + setState({ key: sourceKey, dataUrl: null, failed: true }) + return + } + setState({ + key: sourceKey, + dataUrl: `data:${mimeType};base64,${result.content}`, + failed: false, + }) + }).catch(() => { + if (active) setState({ key: sourceKey, dataUrl: null, failed: true }) + }) + + return () => { + active = false + } + }, [api, localPath, sessionId, source.kind, sourceKey, workspacePath]) + + if (localPath && state.key === sourceKey && !state.failed && !state.dataUrl) { + return markdownImageLoading({ label: alt, className }) + } + + if (state.key !== sourceKey || state.failed) { + return markdownImageFallback({ label: alt, source: typeof src === 'string' ? src : '', className }) + } + + const resolvedSrc = localPath ? state.dataUrl : source.kind === 'remote' ? source.href : null + if (!resolvedSrc) { + return markdownImageFallback({ label: alt, source: typeof src === 'string' ? src : '', className }) + } + + return ( + {alt} { + onError?.(event) + setState({ key: sourceKey, dataUrl: null, failed: true }) + }} + /> + ) +} diff --git a/web/src/components/assistant-ui/markdown-text.tsx b/web/src/components/assistant-ui/markdown-text.tsx index 99dee4c4..2bfb6048 100644 --- a/web/src/components/assistant-ui/markdown-text.tsx +++ b/web/src/components/assistant-ui/markdown-text.tsx @@ -38,6 +38,17 @@ import { remarkSessionPathLinks } from '@/lib/remark-session-path-links' import { buildSessionReferencePath, parseSessionPathHref } from '@/lib/sessionReference' import { UriConfirmDialog } from '@/components/UriConfirmDialog' import { DEFAULT_OPEN_EXTERNAL_LINKS_IN_NEW_TAB, useOpenExternalLinksInNewTab } from '@/hooks/useOpenExternalLinksInNewTab' +import { ChatMarkdownImage } from '@/components/assistant-ui/markdown-image' +import { + classifyScheme, + denyOnlyTransform, + hasScheme, + isDeniedScheme, + isExternalHttpHref, + normalizedScheme, +} from '@/lib/markdown-uri-policy' + +export { classifyScheme, denyOnlyTransform, isExternalHttpHref } from '@/lib/markdown-uri-policy' import type { MarkdownTextPrimitiveProps } from '@assistant-ui/react-markdown' @@ -138,28 +149,8 @@ export const MARKDOWN_COMPONENTS_BY_LANGUAGE = { }, } satisfies NonNullable -// ── URI scheme policy (inlined from url-scheme-policy.ts) ─────────────────── -// -// IANA-registered safe schemes — mirrors react-markdown defaultUrlTransform exactly. -// Source: node_modules/react-markdown/lib/index.js:124 /^(https?|ircs?|mailto|xmpp)$/i -const IANA_SAFE_SCHEMES: ReadonlySet = new Set([ - 'http', - 'https', - 'irc', - 'ircs', - 'mailto', - 'xmpp', -]) - -// Schemes that must always be blocked regardless of user preference. -// Includes file: because Chromium denies navigation from http(s) origins. -const DENY_SCHEMES: ReadonlySet = new Set([ - 'javascript', - 'data', - 'vbscript', - 'file', -]) - +// URI classification and deny-only URL transformation live in +// `markdown-uri-policy.ts` so file assets and chat Markdown share one policy. /** * Extract the normalised scheme from a URL string. * @@ -175,25 +166,6 @@ const DENY_SCHEMES: ReadonlySet = new Set([ * * Returns null when no valid scheme separator is found. */ -function normalizedScheme(url: string): string | null { - let value = url.trimStart() - for (let i = 0; i < 2; i++) { - try { - const next = decodeURIComponent(value) - if (next === value) break - value = next - } catch { - break - } - } - const colonIndex = value.indexOf(':') - if (colonIndex <= 0) return null - // Strip ASCII control chars (U+0000–U+001F, DEL U+007F) and all whitespace - // from the scheme name. Browsers strip exactly these characters during - // navigation, so `java\nscript` navigates as `javascript`. - return value.slice(0, colonIndex).replace(/[\x00-\x1F\x7F\s]/g, '').toLowerCase() -} - /** * Classify a URL string by its scheme. * @@ -203,14 +175,6 @@ function normalizedScheme(url: string): string | null { * * @returns 'iana' | 'deny' | 'custom' */ -export function classifyScheme(url: string): 'iana' | 'deny' | 'custom' { - const scheme = normalizedScheme(url) - if (scheme === null) return 'deny' - if (DENY_SCHEMES.has(scheme)) return 'deny' - if (IANA_SAFE_SCHEMES.has(scheme)) return 'iana' - return 'custom' -} - /** * Returns true when href contains a URL scheme (i.e. a "scheme:" prefix that * appears before any path/query/fragment delimiter). @@ -226,13 +190,6 @@ export function classifyScheme(url: string): 'iana' | 'deny' | 'custom' { * as 'iana' so the browser/router can handle them normally (fixing the regression * where relative markdown links were silently blocked by the onClick deny guard). */ -function hasScheme(href: string): boolean { - const colonIdx = href.indexOf(':') - if (colonIdx <= 0) return false - const boundaryIdx = href.search(/[/?#]/) - return boundaryIdx < 0 || colonIdx < boundaryIdx -} - /** * True when href is a genuine external http(s) link — as opposed to a * relative/SPA href (no scheme, e.g. `/settings`) or another scheme @@ -243,13 +200,6 @@ function hasScheme(href: string): boolean { * a relative href would open the whole app in a second tab instead of * navigating in-app, so this must stay scoped to real http(s) URLs. */ -export function isExternalHttpHref(href: string | null | undefined): boolean { - if (!href || !hasScheme(href)) return false - const colonIdx = href.indexOf(':') - const scheme = href.slice(0, colonIdx).toLowerCase() - return scheme === 'http' || scheme === 'https' -} - // ── URL sanitize transform (deny-only) ────────────────────────────────────── // Passed as urlTransform to MarkdownTextPrimitive. Only deny-listed schemes // are stripped; every other scheme (IANA + custom) passes through so the @@ -266,17 +216,6 @@ export function isExternalHttpHref(href: string | null | undefined): boolean { // is also stripped because DENY_SCHEMES includes 'data'. However, // react-markdown's own defaultUrlTransform strips all data: URLs identically, // so this is not a regression introduced by this PR. -export function denyOnlyTransform(url: string): string { - if (!url) return url - const trimmed = url.trimStart() - const colonIdx = trimmed.indexOf(':') - const slashIdx = trimmed.search(/[/?#]/) - if (colonIdx < 0 || (slashIdx >= 0 && slashIdx < colonIdx)) { - return url - } - return classifyScheme(url) === 'deny' ? '' : url -} - // ── Allowed-schemes state (inlined from useAllowedSchemes.ts) ─────────────── const STORAGE_KEY = 'hapi-allowed-schemes' @@ -305,7 +244,7 @@ function readAllowedFromStorage(): Set { return new Set( parsed .filter((s): s is string => typeof s === 'string') - .filter((s) => !DENY_SCHEMES.has(s)) + .filter((s) => !isDeniedScheme(s)) ) } catch { return new Set() @@ -350,7 +289,7 @@ function useAllowedSchemes() { }, []) const allow = useCallback((scheme: string) => { - if (DENY_SCHEMES.has(scheme)) return + if (isDeniedScheme(scheme)) return setAllowed((prev) => { if (prev.has(scheme)) return prev const next = new Set(prev) @@ -362,7 +301,7 @@ function useAllowedSchemes() { const isAllowed = useCallback( (scheme: string): boolean => { - if (DENY_SCHEMES.has(scheme)) return false + if (isDeniedScheme(scheme)) return false return allowed.has(scheme) }, [allowed] @@ -586,13 +525,14 @@ function FilePathAnchor(props: ComponentPropsWithoutRef<'a'> & { } function SessionPathAnchor(props: ComponentPropsWithoutRef<'a'> & { targetSessionId: string }) { + const { targetSessionId, ...anchorProps } = props const navigate = useNavigate() - const rel = props.target === '_blank' ? (props.rel ?? 'noreferrer') : props.rel + const rel = anchorProps.target === '_blank' ? (anchorProps.rel ?? 'noreferrer') : anchorProps.rel // Preserve Vite BASE_URL for copy / open-in-new-tab (SPA click uses navigate). const href = buildSessionReferencePath(props.targetSessionId) const handleClick = (event: MouseEvent) => { - props.onClick?.(event) + anchorProps.onClick?.(event) if (event.defaultPrevented) return if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return @@ -606,7 +546,7 @@ function SessionPathAnchor(props: ComponentPropsWithoutRef<'a'> & { targetSessio return ( ) { if (fileBase && path) { return } - return + return } type DefaultComponentsMap = { diff --git a/web/src/lib/markdown-file-assets.test.ts b/web/src/lib/markdown-file-assets.test.ts new file mode 100644 index 00000000..ff4f04eb --- /dev/null +++ b/web/src/lib/markdown-file-assets.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from 'vitest' +import { + getMarkdownImageMimeType, + resolveMarkdownFileImage, + resolveMarkdownFileLink, +} from './markdown-file-assets' + +describe('markdown file assets', () => { + it('resolves sibling links relative to the current Markdown file', () => { + expect(resolveMarkdownFileLink('notes/notes-01.md', 'error-notes.md')).toEqual({ + kind: 'local', + path: 'notes/error-notes.md', + }) + }) + + it('resolves nested relative image paths and normalizes dot segments', () => { + expect(resolveMarkdownFileImage('notes/notes-01.md', './images/../images/page-001.png')).toEqual({ + kind: 'local', + path: 'notes/images/page-001.png', + }) + }) + + it('rejects paths that escape the session root', () => { + expect(resolveMarkdownFileLink('notes/notes-01.md', '../../secret.md')).toEqual({ + kind: 'inert', + href: '../../secret.md', + }) + }) + + it('keeps safe absolute in-workspace paths as local targets', () => { + expect(resolveMarkdownFileLink('/workspace/notes/notes-01.md', '/workspace/notes/error-notes.md', { workspacePath: '/workspace' })).toEqual({ + kind: 'local', + path: '/workspace/notes/error-notes.md', + }) + }) + + it('keeps out-of-workspace absolute paths inert', () => { + expect(resolveMarkdownFileLink('/workspace/notes/notes-01.md', '/etc/secret.md', { workspacePath: '/workspace' })).toEqual({ + kind: 'inert', + href: '/etc/secret.md', + }) + }) + + it('rejects traversal beyond the root of an absolute current file path', () => { + expect(resolveMarkdownFileLink('/workspace/notes/readme.md', '../../../secret.md', { workspacePath: '/workspace' })).toEqual({ + kind: 'inert', + href: '../../../secret.md', + }) + }) + + it('recognizes Windows drive paths and applies workspace containment', () => { + expect(resolveMarkdownFileLink('C:\\workspace\\notes\\notes-01.md', 'C:\\workspace\\notes\\error-notes.md', { workspacePath: 'C:\\workspace' })).toEqual({ + kind: 'local', + path: 'C:/workspace/notes/error-notes.md', + }) + expect(resolveMarkdownFileLink('C:\\workspace\\notes\\notes-01.md', 'C:\\Users\\other\\secret.md', { workspacePath: 'C:\\workspace' })).toEqual({ + kind: 'inert', + href: 'C:\\Users\\other\\secret.md', + }) + }) + + it('passes HTTPS images through as remote targets', () => { + expect(resolveMarkdownFileImage('notes/notes-01.md', 'https://example.com/page.png')).toEqual({ + kind: 'remote', + href: 'https://example.com/page.png', + }) + }) + + it('preserves safe non-HTTP URI links for the shared link policy', () => { + expect(resolveMarkdownFileLink('notes/notes-01.md', 'mailto:help@example.com')).toEqual({ + kind: 'uri', + href: 'mailto:help@example.com', + }) + }) + + it('keeps anchors and known app routes navigable', () => { + expect(resolveMarkdownFileLink('notes/notes-01.md', '#section')).toEqual({ kind: 'anchor', href: '#section' }) + expect(resolveMarkdownFileLink('notes/notes-01.md', '/settings')).toEqual({ kind: 'anchor', href: '/settings' }) + }) + + it('maps supported image extensions to MIME types', () => { + expect(getMarkdownImageMimeType('images/page-001.PNG')).toBe('image/png') + expect(getMarkdownImageMimeType('images/animation.apng')).toBe('image/apng') + expect(getMarkdownImageMimeType('images/scan.tif')).toBe('image/tiff') + expect(getMarkdownImageMimeType('images/scan.tiff')).toBe('image/tiff') + expect(getMarkdownImageMimeType('docs/readme.md')).toBeNull() + }) + + it('resolves image extensions declared in the MIME map', () => { + expect(resolveMarkdownFileImage('notes/readme.md', 'images/animation.apng')).toEqual({ + kind: 'local', + path: 'notes/images/animation.apng', + }) + }) +}) diff --git a/web/src/lib/markdown-file-assets.ts b/web/src/lib/markdown-file-assets.ts new file mode 100644 index 00000000..eed25267 --- /dev/null +++ b/web/src/lib/markdown-file-assets.ts @@ -0,0 +1,148 @@ +import { classifyScheme } from '@/lib/markdown-uri-policy' +import { hasKnownFileExtension, isKnownSpaHref, isWithinWorkspace } from '@/lib/markdown-href-policy' + +export const MAX_MARKDOWN_IMAGE_BYTES = 10 * 1024 * 1024 + +const IMAGE_MIME_BY_EXTENSION: Record = { + apng: 'image/apng', + avif: 'image/avif', + bmp: 'image/bmp', + gif: 'image/gif', + ico: 'image/x-icon', + jpeg: 'image/jpeg', + jpg: 'image/jpeg', + png: 'image/png', + svg: 'image/svg+xml', + tif: 'image/tiff', + tiff: 'image/tiff', + webp: 'image/webp', +} + +export type MarkdownAssetTarget = + | { kind: 'local'; path: string } + | { kind: 'remote'; href: string } + | { kind: 'uri'; href: string } + | { kind: 'anchor'; href: string } + | { kind: 'inert'; href: string } + +export interface MarkdownAssetResolutionOptions { + workspacePath?: string | null +} + +function decodeHref(value: string): string { + try { + return decodeURIComponent(value) + } catch { + return value + } +} + +function stripHrefMeta(value: string): string { + const hashIndex = value.indexOf('#') + const queryIndex = value.indexOf('?') + const cut = hashIndex < 0 + ? queryIndex + : queryIndex < 0 + ? hashIndex + : Math.min(hashIndex, queryIndex) + return cut < 0 ? value : value.slice(0, cut) +} + +function hasScheme(value: string): boolean { + return /^[A-Za-z][A-Za-z0-9+.-]*:/.test(value) +} + +function isWindowsAbsolutePath(value: string): boolean { + return /^[A-Za-z]:[\\/]/.test(value) || /^[A-Za-z]:%5[cC]/.test(value) +} + +function isAbsolutePath(value: string): boolean { + return value.startsWith('/') || isWindowsAbsolutePath(value) +} + +function normalizeLocalPath(currentFilePath: string, target: string): string | null { + const current = currentFilePath.replaceAll('\\', '/') + const rawTarget = target.replaceAll('\\', '/') + const absolute = rawTarget.startsWith('/') || /^[A-Za-z]:\//.test(rawTarget) + const currentAbsolute = current.startsWith('/') || /^[A-Za-z]:\//.test(current) + const baseParts = absolute ? [] : current.split('/').slice(0, -1) + const targetParts = rawTarget.split('/') + const parts = absolute ? [] : [...baseParts] + const rootBoundary = absolute + ? (/^[A-Za-z]:\//.test(rawTarget) ? 1 : 0) + : (currentAbsolute ? 1 : 0) + + if (absolute && /^[A-Za-z]:\//.test(rawTarget)) { + parts.push(rawTarget.slice(0, 2)) + targetParts.shift() + } + + for (const part of targetParts) { + if (!part || part === '.') continue + if (part === '..') { + if (parts.length <= rootBoundary || (parts.length === 1 && /^[A-Za-z]:$/.test(parts[0]!))) { + return null + } + parts.pop() + continue + } + parts.push(part) + } + + if (parts.length === 0) return absolute ? '/' : null + const joined = parts.join('/') + if (absolute && joined.length === 2 && /^[A-Za-z]:$/.test(joined)) return `${joined}/` + return absolute && !joined.startsWith('/') && !/^[A-Za-z]:/.test(joined) + ? `/${joined}` + : joined +} + +function classifyTarget(currentFilePath: string, href: string, options: MarkdownAssetResolutionOptions = {}): MarkdownAssetTarget { + const raw = href.trim() + if (!raw) return { kind: 'inert', href } + if (raw.startsWith('#') || raw.startsWith('?')) return { kind: 'anchor', href: raw } + if (raw.startsWith('//') || /^https?:\/\//i.test(raw)) return { kind: 'remote', href: raw } + if (hasScheme(raw) && !isWindowsAbsolutePath(raw)) { + return classifyScheme(raw) === 'deny' + ? { kind: 'inert', href: raw } + : { kind: 'uri', href: raw } + } + if (isKnownSpaHref(raw)) return { kind: 'anchor', href: raw } + + const decoded = decodeHref(stripHrefMeta(raw)) + if (!decoded || decoded.startsWith('~/')) return { kind: 'inert', href: raw } + if (!hasKnownFileExtension(decoded) && !getMarkdownImageMimeType(decoded)) return { kind: 'inert', href: raw } + + const absoluteTarget = isAbsolutePath(decoded) + const absoluteCurrent = isAbsolutePath(currentFilePath) + if (absoluteTarget && (!options.workspacePath || !isWithinWorkspace(decoded, options.workspacePath))) { + return { kind: 'inert', href: raw } + } + if (absoluteCurrent && !options.workspacePath) { + return { kind: 'inert', href: raw } + } + + const path = normalizeLocalPath(currentFilePath, decoded) + if (!path) return { kind: 'inert', href: raw } + if (options.workspacePath && isAbsolutePath(path) && !isWithinWorkspace(path, options.workspacePath)) { + return { kind: 'inert', href: raw } + } + return { kind: 'local', path } +} + +export function resolveMarkdownFileLink(currentFilePath: string, href: string, options?: MarkdownAssetResolutionOptions): MarkdownAssetTarget { + return classifyTarget(currentFilePath, href, options) +} + +export function resolveMarkdownFileImage(currentFilePath: string, src: string, options?: MarkdownAssetResolutionOptions): MarkdownAssetTarget { + const target = classifyTarget(currentFilePath, src, options) + if (target.kind === 'uri' || (target.kind === 'local' && !getMarkdownImageMimeType(target.path))) { + return { kind: 'inert', href: src } + } + return target +} + +export function getMarkdownImageMimeType(path: string): string | null { + const extension = path.split(/[./\\]/).pop()?.toLowerCase() + return extension ? IMAGE_MIME_BY_EXTENSION[extension] ?? null : null +} diff --git a/web/src/lib/markdown-uri-policy.ts b/web/src/lib/markdown-uri-policy.ts new file mode 100644 index 00000000..cb43b68b --- /dev/null +++ b/web/src/lib/markdown-uri-policy.ts @@ -0,0 +1,77 @@ +// ── Markdown URI scheme policy ────────────────────────────────────────────── +// +// Keep URL classification independent from the React Markdown components so +// file-asset resolution can reuse the same security policy without creating a +// component-to-library import cycle. + +const IANA_SAFE_SCHEMES: ReadonlySet = new Set([ + 'http', + 'https', + 'irc', + 'ircs', + 'mailto', + 'xmpp', +]) + +const DENY_SCHEMES: ReadonlySet = new Set([ + 'javascript', + 'data', + 'vbscript', + 'file', +]) + +/** Extract and normalize a URL scheme after decoding common bypass forms. */ +export function normalizedScheme(url: string): string | null { + let value = url.trimStart() + for (let i = 0; i < 2; i++) { + try { + const next = decodeURIComponent(value) + if (next === value) break + value = next + } catch { + break + } + } + const colonIndex = value.indexOf(':') + if (colonIndex <= 0) return null + return value.slice(0, colonIndex).replace(/[\x00-\x1F\x7F\s]/g, '').toLowerCase() +} + +export function classifyScheme(url: string): 'iana' | 'deny' | 'custom' { + const scheme = normalizedScheme(url) + if (scheme === null) return 'deny' + if (DENY_SCHEMES.has(scheme)) return 'deny' + if (IANA_SAFE_SCHEMES.has(scheme)) return 'iana' + return 'custom' +} + +export function isDeniedScheme(scheme: string): boolean { + return DENY_SCHEMES.has(scheme.toLowerCase()) +} + +/** Return true when href contains a scheme before any path/query delimiter. */ +export function hasScheme(href: string): boolean { + const colonIdx = href.indexOf(':') + if (colonIdx <= 0) return false + const boundaryIdx = href.search(/[/?#]/) + return boundaryIdx < 0 || colonIdx < boundaryIdx +} + +export function isExternalHttpHref(href: string | null | undefined): boolean { + if (!href || !hasScheme(href)) return false + const colonIdx = href.indexOf(':') + const scheme = href.slice(0, colonIdx).toLowerCase() + return scheme === 'http' || scheme === 'https' +} + +/** Strip only deny-listed schemes; preserve relative and custom URLs. */ +export function denyOnlyTransform(url: string): string { + if (!url) return url + const trimmed = url.trimStart() + const colonIdx = trimmed.indexOf(':') + const slashIdx = trimmed.search(/[/?#]/) + if (colonIdx < 0 || (slashIdx >= 0 && slashIdx < colonIdx)) { + return url + } + return classifyScheme(url) === 'deny' ? '' : url +}