mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat: add conditional caching and allow-same-origin to file preview, add PreviewHtmlButton
This commit is contained in:
1 parent
7f9403ce5e
commit
ba08f5c24a
10 files changed
+155
-63
No files matched your search
@@ -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<string, string> {
|
||||
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<string, string> {
|
||||
const isHtmlSvg = result.mimeType === 'text/html' || result.mimeType === 'image/svg+xml'
|
||||
const validators = buildPreviewValidators(result)
|
||||
const headers: Record<string, string> = {
|
||||
'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) {
|
||||
|
||||
@@ -61,6 +61,33 @@ export async function getRawFileContent(userPath: string): Promise<Buffer> {
|
||||
}
|
||||
}
|
||||
|
||||
export interface FilePreviewStat {
|
||||
isDirectory: boolean
|
||||
name: string
|
||||
size: number
|
||||
mimeType: string
|
||||
lastModified: Date
|
||||
}
|
||||
|
||||
export async function getFilePreviewStat(userPath: string): Promise<FilePreviewStat> {
|
||||
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<FileInfo> {
|
||||
const validatedPath = validatePath(userPath)
|
||||
logger.info(`Getting file for path: ${userPath} -> ${validatedPath}`)
|
||||
|
||||
@@ -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<typeof fileService.getFile>
|
||||
const getFilePreviewStat = fileService.getFilePreviewStat as MockedFunction<typeof fileService.getFilePreviewStat>
|
||||
const getRawFileContent = fileService.getRawFileContent as MockedFunction<typeof fileService.getRawFileContent>
|
||||
const getFileRange = fileService.getFileRange as MockedFunction<typeof fileService.getFileRange>
|
||||
const uploadFile = fileService.uploadFile as MockedFunction<typeof fileService.uploadFile>
|
||||
@@ -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('<html><body>Hello</body></html>'))
|
||||
|
||||
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('<html><body>Hello</body></html>'))
|
||||
|
||||
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('<html><body>Hello</body></html>'))
|
||||
|
||||
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('<html><body>Hello</body></html>')
|
||||
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')
|
||||
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
|
||||
|
||||
@@ -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 = (
|
||||
<div className="h-[calc(100vh-12rem)] min-h-[480px] rounded border border-border overflow-hidden bg-white">
|
||||
<HtmlPreviewFrame title={`HTML preview: ${file.name}`} src={getFilePreviewUrl(file.path)} />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (file.mimeType?.startsWith('image/')) {
|
||||
return (
|
||||
<div className="flex justify-center p-4">
|
||||
@@ -236,11 +242,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
const showMarkdownPreview = isMarkdownFile && markdownPreview && viewMode !== 'edit'
|
||||
|
||||
if (showHtmlPreview) {
|
||||
return (
|
||||
<div className="h-[calc(100vh-12rem)] min-h-[480px] rounded border border-border overflow-hidden bg-white">
|
||||
<HtmlPreviewFrame title={`HTML preview: ${file.name}`} src={getFilePreviewUrl(file.path)} />
|
||||
</div>
|
||||
)
|
||||
return htmlPreviewFrame
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -301,11 +303,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
}
|
||||
|
||||
if (isHtmlFile && htmlPreview) {
|
||||
return (
|
||||
<div className="h-[calc(100vh-12rem)] min-h-[480px] rounded border border-border overflow-hidden bg-white">
|
||||
<HtmlPreviewFrame title={`HTML preview: ${file.name}`} src={getFilePreviewUrl(file.path)} />
|
||||
</div>
|
||||
)
|
||||
return htmlPreviewFrame
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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 (
|
||||
<iframe
|
||||
title={title}
|
||||
src={src}
|
||||
srcDoc={srcDoc}
|
||||
sandbox="allow-scripts"
|
||||
sandbox={sandbox}
|
||||
referrerPolicy="no-referrer"
|
||||
className={cn('h-full w-full border-0 bg-white', className)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface PreviewHtmlButtonProps {
|
||||
onClick: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function PreviewHtmlButton({ onClick, className }: PreviewHtmlButtonProps) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground text-xs',
|
||||
className,
|
||||
)}
|
||||
title="Preview HTML artifact"
|
||||
>
|
||||
Preview HTML
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useMobile } from '@/hooks/useMobile'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { isHtmlPath } from '@/lib/htmlArtifacts'
|
||||
import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
import { PreviewHtmlButton } from '@/components/html-preview/PreviewHtmlButton'
|
||||
|
||||
interface CodePreviewProps {
|
||||
fileName: string
|
||||
@@ -92,13 +93,7 @@ export function CodePreview({ fileName, content, onHtmlArtifactOpen }: CodePrevi
|
||||
<span className="font-medium truncate flex-1">{extractFileFromPath(fileName)}</span>
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
{isHtmlFile && onHtmlArtifactOpen && (
|
||||
<button
|
||||
onClick={handleHtmlArtifact}
|
||||
className="px-2 py-1 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground text-xs"
|
||||
title="Preview HTML artifact"
|
||||
>
|
||||
Preview HTML
|
||||
</button>
|
||||
<PreviewHtmlButton onClick={handleHtmlArtifact} className="px-2 py-1" />
|
||||
)}
|
||||
<CopyButton content={content} title="Copy" iconSize="sm" variant="ghost" />
|
||||
</div>
|
||||
|
||||
@@ -6,6 +6,7 @@ import rehypeRaw from 'rehype-raw'
|
||||
import mermaid from 'mermaid'
|
||||
import { Maximize2, X, AlertCircle } from 'lucide-react'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { PreviewHtmlButton } from '@/components/html-preview/PreviewHtmlButton'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
import { useTheme } from '@/hooks/useTheme'
|
||||
@@ -181,13 +182,10 @@ function CodeBlock({ children, className, onHtmlArtifactOpen, ...props }: CodeBl
|
||||
</pre>
|
||||
<div className="absolute top-2 right-2 flex gap-1">
|
||||
{isHtmlCode && onHtmlArtifactOpen && (
|
||||
<button
|
||||
<PreviewHtmlButton
|
||||
onClick={() => onHtmlArtifactOpen({ source: 'inline', html: codeContent, title: 'HTML artifact' })}
|
||||
className="p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground text-xs"
|
||||
title="Preview HTML artifact"
|
||||
>
|
||||
Preview HTML
|
||||
</button>
|
||||
className="p-1.5"
|
||||
/>
|
||||
)}
|
||||
<CopyButton content={rawCodeContent} title="Copy code" />
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user