mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat: add HTML artifact preview for inline and file-based HTML outputs
This commit is contained in:
1 parent
5b85abd627
commit
7f9403ce5e
21 files changed
+1323
-62
No files matched your search
@@ -23,12 +23,103 @@ function getSpecialRoutePathFromRequest(c: Context, routeName: string): string |
|
||||
return match?.[1] ? decodeFilePath(match[1]) : undefined
|
||||
}
|
||||
|
||||
function getPreviewPathFromRequest(c: Context): string | undefined {
|
||||
const path = c.req.path
|
||||
const prefix = '/api/files/preview'
|
||||
|
||||
const queryPath = c.req.query('path')
|
||||
if (queryPath !== undefined) {
|
||||
return queryPath
|
||||
}
|
||||
|
||||
if (path.startsWith(prefix + '/')) {
|
||||
const previewPath = path.slice(prefix.length + 1)
|
||||
return decodeURIComponent(previewPath)
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
const PREVIEWABLE_MIME_TYPES = new Set([
|
||||
'text/html',
|
||||
'text/css',
|
||||
'text/javascript',
|
||||
'application/javascript',
|
||||
'application/json',
|
||||
'application/xml',
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/gif',
|
||||
'image/svg+xml',
|
||||
])
|
||||
|
||||
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> {
|
||||
const isHtmlSvg = result.mimeType === 'text/html' || result.mimeType === 'image/svg+xml'
|
||||
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',
|
||||
}
|
||||
|
||||
if (isHtmlSvg) {
|
||||
headers['Content-Security-Policy'] = [
|
||||
'sandbox allow-scripts;',
|
||||
"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';",
|
||||
"img-src 'self' http: https: data: blob:;",
|
||||
"font-src 'self' http: https: data:;",
|
||||
"connect-src 'self' http: https:;",
|
||||
"media-src 'self' http: https: data: blob:;",
|
||||
"object-src 'none';",
|
||||
"base-uri 'none';",
|
||||
"frame-ancestors 'self'",
|
||||
].join(' ')
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
export function createFileRoutes() {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('*', async (c) => {
|
||||
const path = c.req.path
|
||||
|
||||
if (path === '/api/files/preview' || path.startsWith('/api/files/preview/')) {
|
||||
const userPath = getPreviewPathFromRequest(c)
|
||||
|
||||
if (!userPath) {
|
||||
return c.json({ error: 'No path provided' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await fileService.getFile(userPath)
|
||||
|
||||
if (result.isDirectory) {
|
||||
return c.json({ error: 'Cannot preview directories' }, 400)
|
||||
}
|
||||
|
||||
if (!isPreviewableMimeType(result.mimeType)) {
|
||||
return c.json({ error: 'File type cannot be previewed' }, 415)
|
||||
}
|
||||
|
||||
const content = await fileService.getRawFileContent(userPath)
|
||||
const headers = getPreviewHeaders(result)
|
||||
|
||||
return new Response(content, { headers })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to preview file:', error)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to preview file' }, getStatusCode(error) as ContentfulStatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
if (path.endsWith('/download-zip')) {
|
||||
const userPath = getSpecialRoutePathFromRequest(c, 'download-zip')
|
||||
|
||||
|
||||
@@ -253,6 +253,7 @@ function getMimeType(filePath: string): AllowedMimeType {
|
||||
const mimeTypes: Record<string, AllowedMimeType> = {
|
||||
'.txt': 'text/plain',
|
||||
'.html': 'text/html',
|
||||
'.htm': 'text/html',
|
||||
'.css': 'text/css',
|
||||
'.js': 'text/javascript',
|
||||
'.ts': 'text/typescript',
|
||||
|
||||
@@ -47,6 +47,7 @@ vi.mock('../../src/services/archive', () => ({
|
||||
}))
|
||||
|
||||
const getFile = fileService.getFile as MockedFunction<typeof fileService.getFile>
|
||||
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>
|
||||
const createFileOrFolder = fileService.createFileOrFolder as MockedFunction<typeof fileService.createFileOrFolder>
|
||||
@@ -69,6 +70,125 @@ describe('File Routes', () => {
|
||||
app.route('/api/files', filesApp)
|
||||
})
|
||||
|
||||
describe('GET /preview/* - HTML Preview Assets', () => {
|
||||
const htmlFileInfo: FileInfo = {
|
||||
name: 'index.html',
|
||||
path: 'test-repo/index.html',
|
||||
isDirectory: false,
|
||||
size: 31,
|
||||
mimeType: 'text/html',
|
||||
content: '',
|
||||
lastModified: new Date(),
|
||||
}
|
||||
|
||||
it('should serve HTML files with sandbox CSP headers', async () => {
|
||||
getFile.mockResolvedValue(htmlFileInfo)
|
||||
getRawFileContent.mockResolvedValue(Buffer.from('<html><body>Hello</body></html>'))
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo/index.html')
|
||||
const body = await response.text()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toBe('<html><body>Hello</body></html>')
|
||||
expect(response.headers.get('Content-Type')).toContain('text/html')
|
||||
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('https:')
|
||||
expect(getFile).toHaveBeenCalledWith('test-repo/index.html')
|
||||
expect(getRawFileContent).toHaveBeenCalledWith('test-repo/index.html')
|
||||
})
|
||||
|
||||
it('should serve CSS files with text/css Content-Type', async () => {
|
||||
const cssFileInfo: FileInfo = {
|
||||
name: 'styles.css',
|
||||
path: 'test-repo/styles/app.css',
|
||||
isDirectory: false,
|
||||
size: 50,
|
||||
mimeType: 'text/css',
|
||||
content: '',
|
||||
lastModified: new Date(),
|
||||
}
|
||||
getFile.mockResolvedValue(cssFileInfo)
|
||||
getRawFileContent.mockResolvedValue(Buffer.from('body { color: red }'))
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo/styles/app.css')
|
||||
|
||||
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')
|
||||
})
|
||||
|
||||
it('should support query-based path parameter', async () => {
|
||||
getFile.mockResolvedValue(htmlFileInfo)
|
||||
getRawFileContent.mockResolvedValue(Buffer.from('<html><body>Hello</body></html>'))
|
||||
|
||||
const response = await app.request('/api/files/preview?path=test-repo/index.html')
|
||||
const body = await response.text()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toBe('<html><body>Hello</body></html>')
|
||||
expect(getFile).toHaveBeenCalledWith('test-repo/index.html')
|
||||
})
|
||||
|
||||
it('should return 400 for directory results', async () => {
|
||||
const dirInfo: FileInfo = {
|
||||
name: 'test-repo',
|
||||
path: 'test-repo',
|
||||
isDirectory: true,
|
||||
size: 0,
|
||||
lastModified: new Date(),
|
||||
}
|
||||
getFile.mockResolvedValue(dirInfo)
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo')
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json() as { error: string }
|
||||
expect(body.error).toContain('Cannot preview directories')
|
||||
})
|
||||
|
||||
it('should return 415 for non-previewable MIME types', async () => {
|
||||
const pdfFileInfo: FileInfo = {
|
||||
name: 'doc.pdf',
|
||||
path: 'test-repo/doc.pdf',
|
||||
isDirectory: false,
|
||||
size: 100,
|
||||
mimeType: 'application/pdf',
|
||||
content: '',
|
||||
lastModified: new Date(),
|
||||
}
|
||||
getFile.mockResolvedValue(pdfFileInfo)
|
||||
|
||||
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')
|
||||
})
|
||||
|
||||
it('should return 400 when no path is provided', async () => {
|
||||
const response = await app.request('/api/files/preview')
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json() as { error: string }
|
||||
expect(body.error).toContain('No path provided')
|
||||
})
|
||||
|
||||
it('should return 403 for path traversal attempts', async () => {
|
||||
const error = { message: 'Path traversal detected', statusCode: 403 }
|
||||
getFile.mockRejectedValue(error)
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo/../outside')
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
const body = await response.json() as { error: string }
|
||||
expect(body.error).toContain('Path traversal detected')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /*/download-zip - Route Order Regression Test', () => {
|
||||
it('should route to archive service for directory download, not file service', async () => {
|
||||
const mockStream = {
|
||||
@@ -175,6 +295,17 @@ describe('File Routes', () => {
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should route paths starting with "preview" but not matching /preview/ to generic handler', async () => {
|
||||
getFile.mockResolvedValue(mockFileInfo)
|
||||
|
||||
const response = await app.request('/api/files/previewer')
|
||||
const body = await response.json() as FileInfo
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('isDirectory', false)
|
||||
expect(getFile).toHaveBeenCalledWith('previewer')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /* with ?startLine&endLine - File Range', () => {
|
||||
|
||||
Reference in new issue
Block a user