From ba08f5c24ac0c7c71408ba8d4aeeaa137f44dc70 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 20 Jun 2026 20:52:08 -0400 Subject: [PATCH] feat: add conditional caching and allow-same-origin to file preview, add PreviewHtmlButton --- backend/src/routes/files.ts | 48 ++++++++++-- backend/src/services/files.ts | 27 +++++++ backend/test/routes/files.test.ts | 78 +++++++++++-------- .../file-browser/FilePreview.test.tsx | 2 +- .../components/file-browser/FilePreview.tsx | 18 ++--- .../html-preview/HtmlArtifactPanel.test.tsx | 2 +- .../html-preview/HtmlPreviewFrame.tsx | 3 +- .../html-preview/PreviewHtmlButton.tsx | 21 +++++ .../src/components/message/CodePreview.tsx | 9 +-- frontend/src/components/message/TextPart.tsx | 10 +-- 10 files changed, 155 insertions(+), 63 deletions(-) create mode 100644 frontend/src/components/html-preview/PreviewHtmlButton.tsx diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts index 6560413c..eb162372 100644 --- a/backend/src/routes/files.ts +++ b/backend/src/routes/files.ts @@ -57,19 +57,50 @@ function isPreviewableMimeType(mimeType?: string): boolean { return mimeType !== undefined && PREVIEWABLE_MIME_TYPES.has(mimeType) } -function getPreviewHeaders(result: { name: string; size: number; mimeType?: string }): Record { +function buildPreviewValidators(stat: { size: number; lastModified: Date }): { etag: string; lastModified: string } { + return { + etag: `"${stat.size.toString(16)}-${stat.lastModified.getTime().toString(16)}"`, + lastModified: stat.lastModified.toUTCString(), + } +} + +function isPreviewFresh(c: Context, validators: { etag: string; lastModified: string }): boolean { + const ifNoneMatch = c.req.header('if-none-match') + if (ifNoneMatch !== undefined) { + return ifNoneMatch.split(',').some((tag: string) => tag.trim() === validators.etag) + } + + const ifModifiedSince = c.req.header('if-modified-since') + if (ifModifiedSince !== undefined) { + const since = Date.parse(ifModifiedSince) + return !Number.isNaN(since) && Date.parse(validators.lastModified) <= since + } + + return false +} + +function getPreviewHeaders(result: { + name: string + size: number + mimeType?: string + lastModified: Date +}): Record { const isHtmlSvg = result.mimeType === 'text/html' || result.mimeType === 'image/svg+xml' + const validators = buildPreviewValidators(result) const headers: Record = { 'Content-Type': result.mimeType || 'application/octet-stream', 'Content-Length': result.size.toString(), 'Content-Disposition': `inline; filename="${result.name}"`, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', + 'Cache-Control': 'private, must-revalidate, max-age=0', + 'ETag': validators.etag, + 'Last-Modified': validators.lastModified, } if (isHtmlSvg) { headers['Content-Security-Policy'] = [ - 'sandbox allow-scripts;', + 'sandbox allow-scripts allow-same-origin;', "default-src 'self' http: https: data: blob: 'unsafe-inline' 'unsafe-eval';", "script-src 'self' http: https: 'unsafe-inline' 'unsafe-eval';", "style-src 'self' http: https: 'unsafe-inline';", @@ -100,18 +131,23 @@ export function createFileRoutes() { } try { - const result = await fileService.getFile(userPath) + const stat = await fileService.getFilePreviewStat(userPath) - if (result.isDirectory) { + if (stat.isDirectory) { return c.json({ error: 'Cannot preview directories' }, 400) } - if (!isPreviewableMimeType(result.mimeType)) { + if (!isPreviewableMimeType(stat.mimeType)) { return c.json({ error: 'File type cannot be previewed' }, 415) } + const headers = getPreviewHeaders(stat) + + if (isPreviewFresh(c, buildPreviewValidators(stat))) { + return new Response(null, { status: 304, headers }) + } + const content = await fileService.getRawFileContent(userPath) - const headers = getPreviewHeaders(result) return new Response(content, { headers }) } catch (error: unknown) { diff --git a/backend/src/services/files.ts b/backend/src/services/files.ts index e49b7390..5c4b7a4f 100644 --- a/backend/src/services/files.ts +++ b/backend/src/services/files.ts @@ -61,6 +61,33 @@ export async function getRawFileContent(userPath: string): Promise { } } +export interface FilePreviewStat { + isDirectory: boolean + name: string + size: number + mimeType: string + lastModified: Date +} + +export async function getFilePreviewStat(userPath: string): Promise { + const validatedPath = validatePath(userPath) + + const exists = await fileExists(validatedPath) + if (!exists) { + throw { message: 'File not found or cannot be read', statusCode: 404 } + } + + const stats = await getFileStats(validatedPath) + + return { + isDirectory: stats.isDirectory, + name: path.basename(validatedPath), + size: stats.size, + mimeType: getMimeType(validatedPath), + lastModified: stats.lastModified, + } +} + export async function getFile(userPath: string): Promise { const validatedPath = validatePath(userPath) logger.info(`Getting file for path: ${userPath} -> ${validatedPath}`) diff --git a/backend/test/routes/files.test.ts b/backend/test/routes/files.test.ts index 7d8d64a2..ceddc700 100644 --- a/backend/test/routes/files.test.ts +++ b/backend/test/routes/files.test.ts @@ -30,6 +30,7 @@ vi.mock('@opencode-manager/shared/config/env', () => ({ vi.mock('../../src/services/files', () => ({ getFile: vi.fn(), + getFilePreviewStat: vi.fn(), getRawFileContent: vi.fn(), getFileRange: vi.fn(), uploadFile: vi.fn(), @@ -47,6 +48,7 @@ vi.mock('../../src/services/archive', () => ({ })) const getFile = fileService.getFile as MockedFunction +const getFilePreviewStat = fileService.getFilePreviewStat as MockedFunction const getRawFileContent = fileService.getRawFileContent as MockedFunction const getFileRange = fileService.getFileRange as MockedFunction const uploadFile = fileService.uploadFile as MockedFunction @@ -71,18 +73,18 @@ describe('File Routes', () => { }) describe('GET /preview/* - HTML Preview Assets', () => { - const htmlFileInfo: FileInfo = { + const lastModified = new Date('2024-01-01T00:00:00.000Z') + + const htmlStat = { name: 'index.html', - path: 'test-repo/index.html', isDirectory: false, size: 31, - mimeType: 'text/html', - content: '', - lastModified: new Date(), + mimeType: 'text/html' as const, + lastModified, } - it('should serve HTML files with sandbox CSP headers', async () => { - getFile.mockResolvedValue(htmlFileInfo) + it('should serve HTML files with sandbox CSP and caching headers', async () => { + getFilePreviewStat.mockResolvedValue(htmlStat) getRawFileContent.mockResolvedValue(Buffer.from('Hello')) const response = await app.request('/api/files/preview/test-repo/index.html') @@ -94,23 +96,40 @@ describe('File Routes', () => { expect(response.headers.get('Content-Disposition')).toContain('inline') expect(response.headers.get('X-Content-Type-Options')).toBe('nosniff') expect(response.headers.get('Referrer-Policy')).toBe('no-referrer') - expect(response.headers.get('Content-Security-Policy')).toContain('sandbox allow-scripts') + expect(response.headers.get('Content-Security-Policy')).toContain('sandbox allow-scripts allow-same-origin') expect(response.headers.get('Content-Security-Policy')).toContain('https:') - expect(getFile).toHaveBeenCalledWith('test-repo/index.html') + expect(response.headers.get('Cache-Control')).toBe('private, must-revalidate, max-age=0') + expect(response.headers.get('ETag')).toBeTruthy() + expect(response.headers.get('Last-Modified')).toBe(lastModified.toUTCString()) + expect(getFilePreviewStat).toHaveBeenCalledWith('test-repo/index.html') expect(getRawFileContent).toHaveBeenCalledWith('test-repo/index.html') }) + it('should return 304 when ETag matches If-None-Match without reading the file', async () => { + getFilePreviewStat.mockResolvedValue(htmlStat) + getRawFileContent.mockResolvedValue(Buffer.from('Hello')) + + const first = await app.request('/api/files/preview/test-repo/index.html') + const etag = first.headers.get('ETag') as string + await first.text() + getRawFileContent.mockClear() + + const response = await app.request('/api/files/preview/test-repo/index.html', { + headers: { 'If-None-Match': etag }, + }) + + expect(response.status).toBe(304) + expect(getRawFileContent).not.toHaveBeenCalled() + }) + it('should serve CSS files with text/css Content-Type', async () => { - const cssFileInfo: FileInfo = { + getFilePreviewStat.mockResolvedValue({ name: 'styles.css', - path: 'test-repo/styles/app.css', isDirectory: false, size: 50, mimeType: 'text/css', - content: '', - lastModified: new Date(), - } - getFile.mockResolvedValue(cssFileInfo) + lastModified, + }) getRawFileContent.mockResolvedValue(Buffer.from('body { color: red }')) const response = await app.request('/api/files/preview/test-repo/styles/app.css') @@ -118,11 +137,11 @@ describe('File Routes', () => { expect(response.status).toBe(200) expect(response.headers.get('Content-Type')).toContain('text/css') expect(response.headers.get('Content-Security-Policy')).toBeNull() - expect(getFile).toHaveBeenCalledWith('test-repo/styles/app.css') + expect(getFilePreviewStat).toHaveBeenCalledWith('test-repo/styles/app.css') }) it('should support query-based path parameter', async () => { - getFile.mockResolvedValue(htmlFileInfo) + getFilePreviewStat.mockResolvedValue(htmlStat) getRawFileContent.mockResolvedValue(Buffer.from('Hello')) const response = await app.request('/api/files/preview?path=test-repo/index.html') @@ -130,18 +149,17 @@ describe('File Routes', () => { expect(response.status).toBe(200) expect(body).toBe('Hello') - expect(getFile).toHaveBeenCalledWith('test-repo/index.html') + expect(getFilePreviewStat).toHaveBeenCalledWith('test-repo/index.html') }) it('should return 400 for directory results', async () => { - const dirInfo: FileInfo = { + getFilePreviewStat.mockResolvedValue({ name: 'test-repo', - path: 'test-repo', isDirectory: true, size: 0, - lastModified: new Date(), - } - getFile.mockResolvedValue(dirInfo) + mimeType: 'text/plain', + lastModified, + }) const response = await app.request('/api/files/preview/test-repo') @@ -151,22 +169,20 @@ describe('File Routes', () => { }) it('should return 415 for non-previewable MIME types', async () => { - const pdfFileInfo: FileInfo = { + getFilePreviewStat.mockResolvedValue({ name: 'doc.pdf', - path: 'test-repo/doc.pdf', isDirectory: false, size: 100, - mimeType: 'application/pdf', - content: '', - lastModified: new Date(), - } - getFile.mockResolvedValue(pdfFileInfo) + mimeType: 'application/pdf' as never, + lastModified, + }) const response = await app.request('/api/files/preview/test-repo/doc.pdf') expect(response.status).toBe(415) const body = await response.json() as { error: string } expect(body.error).toContain('File type cannot be previewed') + expect(getRawFileContent).not.toHaveBeenCalled() }) it('should return 400 when no path is provided', async () => { @@ -179,7 +195,7 @@ describe('File Routes', () => { it('should return 403 for path traversal attempts', async () => { const error = { message: 'Path traversal detected', statusCode: 403 } - getFile.mockRejectedValue(error) + getFilePreviewStat.mockRejectedValue(error) const response = await app.request('/api/files/preview/test-repo/../outside') diff --git a/frontend/src/components/file-browser/FilePreview.test.tsx b/frontend/src/components/file-browser/FilePreview.test.tsx index c8c3f017..99918745 100644 --- a/frontend/src/components/file-browser/FilePreview.test.tsx +++ b/frontend/src/components/file-browser/FilePreview.test.tsx @@ -47,7 +47,7 @@ describe('FilePreview - HTML preview', () => { const iframe = screen.getByTitle('HTML preview: dashboard.html') expect(iframe).toBeInTheDocument() - expect(iframe).toHaveAttribute('sandbox', 'allow-scripts') + expect(iframe).toHaveAttribute('sandbox', 'allow-scripts allow-same-origin') expect(iframe.getAttribute('src')).toContain('/api/files/preview/test-repo/dashboard.html') }) diff --git a/frontend/src/components/file-browser/FilePreview.tsx b/frontend/src/components/file-browser/FilePreview.tsx index 564094c5..155da0d4 100644 --- a/frontend/src/components/file-browser/FilePreview.tsx +++ b/frontend/src/components/file-browser/FilePreview.tsx @@ -219,6 +219,12 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false, ['application/json', 'application/xml', 'text/javascript', 'text/typescript'].includes(file.mimeType || '') const renderContent = () => { + const htmlPreviewFrame = ( +
+ +
+ ) + if (file.mimeType?.startsWith('image/')) { return (
@@ -236,11 +242,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false, const showMarkdownPreview = isMarkdownFile && markdownPreview && viewMode !== 'edit' if (showHtmlPreview) { - return ( -
- -
- ) + return htmlPreviewFrame } return ( @@ -301,11 +303,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false, } if (isHtmlFile && htmlPreview) { - return ( -
- -
- ) + return htmlPreviewFrame } try { diff --git a/frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx b/frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx index 416d3faf..0f05ce9e 100644 --- a/frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx +++ b/frontend/src/components/html-preview/HtmlArtifactPanel.test.tsx @@ -62,7 +62,7 @@ describe('HtmlArtifactPanel', () => { expect(iframe).toBeInTheDocument() expect(iframe).toHaveAttribute('src') expect(iframe.getAttribute('src')).toContain('/api/files/preview/') - expect(iframe).toHaveAttribute('sandbox', 'allow-scripts') + expect(iframe).toHaveAttribute('sandbox', 'allow-scripts allow-same-origin') }) it('does not include allow-same-origin in sandbox', () => { diff --git a/frontend/src/components/html-preview/HtmlPreviewFrame.tsx b/frontend/src/components/html-preview/HtmlPreviewFrame.tsx index 677c5c45..5fdff014 100644 --- a/frontend/src/components/html-preview/HtmlPreviewFrame.tsx +++ b/frontend/src/components/html-preview/HtmlPreviewFrame.tsx @@ -8,12 +8,13 @@ interface HtmlPreviewFrameProps { } export function HtmlPreviewFrame({ title, src, srcDoc, className }: HtmlPreviewFrameProps) { + const sandbox = src ? 'allow-scripts allow-same-origin' : 'allow-scripts' return (