mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
fix(artifacts): render artifacts from the checked path and serve raw files once
- show_artifact returns the validated path as tool metadata; the chat card renders from it and maps repo paths with getWorkspaceFilePath, so local repos and moved sessions load the right file - serve .htm as text/html - raw file route stats and reads once and adds ETag/Last-Modified with 304 - reuse isPathWithinRoot from utils/fs-safe - move readShowArtifactCall to frontend/src/lib/artifactTool
This commit is contained in:
1 parent
f7b2ffb865
commit
5e2452172c
26 files changed
+489
-58
No files matched your search
@@ -23,6 +23,19 @@ function getSpecialRoutePathFromRequest(c: Context, routeName: string): string |
|
||||
return match?.[1] ? decodeFilePath(match[1]) : undefined
|
||||
}
|
||||
|
||||
function buildWeakEtag(size: number, lastModified: Date): string {
|
||||
return `W/"${size}-${lastModified.getTime()}"`
|
||||
}
|
||||
|
||||
function matchesIfNoneMatch(ifNoneMatch: string | undefined, etag: string): boolean {
|
||||
if (!ifNoneMatch) {
|
||||
return false
|
||||
}
|
||||
|
||||
const values = ifNoneMatch.split(',').map((value) => value.trim())
|
||||
return values.includes('*') || values.includes(etag)
|
||||
}
|
||||
|
||||
export function createFileRoutes() {
|
||||
const app = new Hono()
|
||||
|
||||
@@ -112,21 +125,46 @@ export function createFileRoutes() {
|
||||
return c.json(result)
|
||||
}
|
||||
|
||||
const result = await fileService.getFile(userPath)
|
||||
|
||||
if (raw && !result.isDirectory) {
|
||||
if (raw) {
|
||||
const metadata = await fileService.getRawFileMetadata(userPath)
|
||||
|
||||
if (!metadata) {
|
||||
const result = await fileService.getFile(userPath)
|
||||
return c.json(result)
|
||||
}
|
||||
|
||||
const etag = buildWeakEtag(metadata.size, metadata.lastModified)
|
||||
const lastModified = metadata.lastModified.toUTCString()
|
||||
|
||||
if (matchesIfNoneMatch(c.req.header('if-none-match'), etag)) {
|
||||
return new Response(null, {
|
||||
status: 304,
|
||||
headers: {
|
||||
'ETag': etag,
|
||||
'Last-Modified': lastModified,
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Security-Policy': 'sandbox allow-scripts',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const content = await fileService.getRawFileContent(userPath)
|
||||
return new Response(content, {
|
||||
headers: {
|
||||
'Content-Type': result.mimeType || 'application/octet-stream',
|
||||
'Content-Length': result.size.toString(),
|
||||
'Content-Type': metadata.mimeType,
|
||||
'Content-Length': content.byteLength.toString(),
|
||||
'Content-Security-Policy': 'sandbox allow-scripts',
|
||||
'Cache-Control': 'no-cache',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'ETag': etag,
|
||||
'Last-Modified': lastModified,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
const result = await fileService.getFile(userPath)
|
||||
|
||||
if (download && !result.isDirectory) {
|
||||
const content = result.content ? Buffer.from(result.content, 'base64') : Buffer.alloc(0)
|
||||
return new Response(content, {
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
} from '../services/opencode/upstream'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import { getTrustedOrigins, getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
import { isPathWithinRoot } from '../services/sandbox/command'
|
||||
import { isPathWithinRoot } from '../utils/fs-safe'
|
||||
import { buildProxyResponseHeaders, filterProxyHeaders } from '../utils/proxy-headers'
|
||||
import {
|
||||
connectUpstreamWebSocket,
|
||||
|
||||
@@ -40,6 +40,12 @@ interface FileUploadResult {
|
||||
mimeType: string
|
||||
}
|
||||
|
||||
export interface RawFileMetadata {
|
||||
size: number
|
||||
mimeType: AllowedMimeType
|
||||
lastModified: Date
|
||||
}
|
||||
|
||||
export async function getRawFileContent(userPath: string): Promise<Buffer> {
|
||||
const validatedPath = validatePath(userPath)
|
||||
logger.info(`Getting raw file content for path: ${userPath} -> ${validatedPath}`)
|
||||
@@ -62,6 +68,32 @@ export async function getRawFileContent(userPath: string): Promise<Buffer> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getRawFileMetadata(userPath: string): Promise<RawFileMetadata | null> {
|
||||
const validatedPath = validatePath(userPath)
|
||||
logger.info(`Getting raw file metadata for path: ${userPath} -> ${validatedPath}`)
|
||||
|
||||
try {
|
||||
const exists = await fileExists(validatedPath)
|
||||
if (!exists) {
|
||||
throw new Error('Path does not exist')
|
||||
}
|
||||
|
||||
const stats = await getFileStats(validatedPath)
|
||||
if (stats.isDirectory) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
size: stats.size,
|
||||
mimeType: getMimeType(validatedPath),
|
||||
lastModified: stats.lastModified,
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to read raw file metadata ${validatedPath}:`, error)
|
||||
throw { message: 'File or directory not found', statusCode: 404 }
|
||||
}
|
||||
}
|
||||
|
||||
export async function getFile(userPath: string): Promise<FileInfo> {
|
||||
const validatedPath = validatePath(userPath)
|
||||
const responsePath = path.isAbsolute(userPath.trim()) ? path.relative(SHARED_WORKSPACE_BASE, validatedPath) : userPath
|
||||
@@ -262,6 +294,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',
|
||||
|
||||
@@ -255,7 +255,10 @@ var ACTIONS = {
|
||||
{ path: params.path },
|
||||
context.signal,
|
||||
)
|
||||
return 'Showing the artifact "' + params.title + '" from ' + result.path + ' in the Manager chat. It renders the current file contents, so after editing the file the user can reload the view; call show_artifact again only to show a different file.'
|
||||
return {
|
||||
content: 'Showing the artifact "' + params.title + '" from ' + result.path + ' in the Manager chat. It renders the current file contents, so after editing the file the user can reload the view; call show_artifact again only to show a different file.',
|
||||
metadata: { path: result.path },
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -294,7 +297,11 @@ export default {
|
||||
input: INPUT_SCHEMA,
|
||||
options: { codemode: false },
|
||||
execute: async function (input, context) {
|
||||
return { content: await runAction(input, context) }
|
||||
var result = await runAction(input, context)
|
||||
if (result !== null && typeof result === 'object') {
|
||||
return result
|
||||
}
|
||||
return { content: result }
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
getReposPath,
|
||||
getScheduleWorktreesPath,
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import { isPathWithinRoot } from '../../utils/fs-safe'
|
||||
|
||||
export const WORKSPACE_SANDBOX_NAME = 'ocm-workspace'
|
||||
|
||||
@@ -36,11 +37,6 @@ export function overrideSandboxExecutableTrustValidator(validator: ((candidate:
|
||||
resetSandboxExecutableCache()
|
||||
}
|
||||
|
||||
export function isPathWithinRoot(root: string, target: string): boolean {
|
||||
const relative = path.relative(path.resolve(root), path.resolve(target))
|
||||
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
function isWritableByManager(stat: { uid: number; gid: number; mode: number }): boolean {
|
||||
if (typeof process.getuid === 'function' && typeof process.getgid === 'function') {
|
||||
if (stat.uid === process.getuid() && (stat.mode & 0o200) !== 0) return true
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import path from 'path'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { writeFileAtomic } from '../../utils/fs-safe'
|
||||
import { isPathWithinRoot, writeFileAtomic } from '../../utils/fs-safe'
|
||||
import {
|
||||
isPathWithinRoot,
|
||||
quoteForShell,
|
||||
resolveSandboxExecUser,
|
||||
sandboxExecutablePath,
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path'
|
||||
import { ARTIFACT_LIMITS } from '@opencode-manager/shared/schemas'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
import { isPathWithinRoot } from '../utils/fs-safe'
|
||||
|
||||
const ARTIFACT_EXTENSIONS = new Set(['.html', '.htm'])
|
||||
|
||||
@@ -13,14 +14,11 @@ export class SessionArtifactError extends ServiceError {
|
||||
}
|
||||
}
|
||||
|
||||
function isInsideDirectory(directory: string, candidate: string): boolean {
|
||||
const relative = path.relative(directory, candidate)
|
||||
return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an `ocm` `show_artifact` path to the real, absolute path of a self-contained HTML file inside the
|
||||
* session directory, rejecting paths that escape it (including through symlinks), non-HTML files and oversized files.
|
||||
* Resolves an `ocm` `show_artifact` path to the absolute path of a self-contained HTML file inside the session
|
||||
* directory, rejecting paths that escape it (including through symlinks), non-HTML files and oversized files.
|
||||
* Symlinks are resolved for validation only; the returned path stays lexical so callers can map it by the
|
||||
* session directory or repo prefix they were given.
|
||||
*/
|
||||
export async function resolveSessionArtifactFile(
|
||||
openCodeClient: OpenCodeClient,
|
||||
@@ -46,7 +44,7 @@ export async function resolveSessionArtifactFile(
|
||||
throw new SessionArtifactError(`Artifact file not found: ${artifactPath}`, 404)
|
||||
}
|
||||
|
||||
if (!isInsideDirectory(realSessionDirectory, realFile)) {
|
||||
if (!isPathWithinRoot(realSessionDirectory, realFile)) {
|
||||
throw new SessionArtifactError(`Artifact path must be inside the session directory ${sessionDirectory}`, 400)
|
||||
}
|
||||
|
||||
@@ -65,5 +63,5 @@ export async function resolveSessionArtifactFile(
|
||||
throw new SessionArtifactError('Artifact file exceeds 5 MB', 413)
|
||||
}
|
||||
|
||||
return realFile
|
||||
return resolved
|
||||
}
|
||||
@@ -26,6 +26,11 @@ export function canonicalPathSync(target: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function isPathWithinRoot(root: string, target: string): boolean {
|
||||
const relative = path.relative(path.resolve(root), path.resolve(target))
|
||||
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
||||
}
|
||||
|
||||
export async function writeFileAtomic(filePath: string, content: string | Buffer, options: { mode?: number } = {}): Promise<void> {
|
||||
const dir = path.dirname(filePath)
|
||||
await mkdirSafe(dir)
|
||||
|
||||
Reference in new issue
Block a user