fix: sandbox file previews and reserve archive capacity [skip ci]

This commit is contained in:
evgyur committed 2026-11-05 06:45:54 +03:00
1 parent 11e6c8e63a
commit 9df954a231
4 files changed
+90 -35

No files matched your search

+47 -34
View File
@@ -215,6 +215,8 @@ export function createArchiveTasks(options: ArchiveTaskOptions = {}): ArchiveTas
const tasks = new Map<string, ArchiveTask>()
/** Running children, by task id (teardown kills them). */
const children = new Map<string, { kill(): void }>()
let resolvingArchives = 0
let disposed = false
const spawner = options.spawn ?? undefined
const tempPathOf = (id: string, ext: string): string =>
@@ -245,40 +247,45 @@ export function createArchiveTasks(options: ArchiveTaskOptions = {}): ArchiveTas
sweep(Date.now())
let building = 0
for (const task of tasks.values()) if (task.state === 'building') building += 1
if (building >= ARCHIVE_MAX_BUILDING) {
if (disposed) throw new SidebarError('unavailable', 'archive service disposed', 503)
if (building + resolvingArchives >= ARCHIVE_MAX_BUILDING) {
throw new SidebarError('bad-request', `too many archives are being built (max ${ARCHIVE_MAX_BUILDING})`, 409)
}
const resolve = options.resolveTool ?? resolveArchiveTool
// One call either way: `spawn` has a default, so passing `undefined`
// selects the real implementation without a second code path.
const spec = await resolve(spawner)
if (spec === undefined) {
// A NEW wire code, and deliberately its own: "this machine has no zip
// and no tar" is not a failure of the selection, and the client shows
// it as an actionable sentence rather than a raw English message.
throw new SidebarError(
'unavailable',
'no archive tool is available: neither zip nor tar could be run',
501,
)
}
const plan = planArchive(paths, spec)
const id = `ar-${randomUUID()}`
const finalName = archiveFileName(name, spec.ext)
const tempPath = tempPathOf(id, spec.ext)
const task: ArchiveTask = {
id,
sessionId,
name: finalName,
state: 'building',
bytes: 0,
expiresAt: Number.POSITIVE_INFINITY,
}
tasks.set(id, task)
// Detached on purpose: the POST answers as soon as the id exists, and the
// task table (not the request) owns the error from here on.
void pack(id, task, plan, tempPath, spawner)
return { id, name: finalName, entries: paths.length }
resolvingArchives += 1
try {
const resolve = options.resolveTool ?? resolveArchiveTool
// One call either way: `spawn` has a default, so passing `undefined`
// selects the real implementation without a second code path.
const spec = await resolve(spawner)
if (disposed) throw new SidebarError('unavailable', 'archive service disposed', 503)
if (spec === undefined) {
// A NEW wire code, and deliberately its own: "this machine has no zip
// and no tar" is not a failure of the selection, and the client shows
// it as an actionable sentence rather than a raw English message.
throw new SidebarError(
'unavailable',
'no archive tool is available: neither zip nor tar could be run',
501,
)
}
const plan = planArchive(paths, spec)
const id = `ar-${randomUUID()}`
const finalName = archiveFileName(name, spec.ext)
const tempPath = tempPathOf(id, spec.ext)
const task: ArchiveTask = {
id,
sessionId,
name: finalName,
state: 'building',
bytes: 0,
expiresAt: Number.POSITIVE_INFINITY,
}
tasks.set(id, task)
// Detached on purpose: the POST answers as soon as the id exists, and the
// task table (not the request) owns the error from here on.
void pack(id, task, plan, tempPath, spawner)
return { id, name: finalName, entries: paths.length }
} finally { resolvingArchives -= 1 }
},
status(id, sessionId) {
sweep(Date.now())
@@ -302,6 +309,7 @@ export function createArchiveTasks(options: ArchiveTaskOptions = {}): ArchiveTas
return tasks.size
},
dispose() {
disposed = true
for (const child of children.values()) {
try {
child.kill()
@@ -338,17 +346,22 @@ export function createArchiveTasks(options: ArchiveTaskOptions = {}): ArchiveTas
children.delete(id)
}
let handle: Awaited<ReturnType<typeof open>> | undefined
let ownsTemp = false
try {
handle = await open(tempPath, 'w')
handle = await open(tempPath, 'wx')
ownsTemp = true
if (disposed) throw new Error('archive service disposed')
const result = await runArchiveTool(plan, handle.fd, spawner, child => { children.set(id, child) })
await handle.close()
handle = undefined
if (disposed) throw new Error('archive service disposed')
if (result.code !== 0) {
settle(result.stderr === '' ? `${plan.spec.bin} exited with code ${result.code}` : result.stderr)
await rm(tempPath, { force: true }).catch(() => {})
return
}
const info = await stat(tempPath).catch(() => undefined)
if (disposed) throw new Error('archive service disposed')
if (info === undefined) {
settle(`${plan.spec.bin} produced no archive`)
return
@@ -362,7 +375,7 @@ export function createArchiveTasks(options: ArchiveTaskOptions = {}): ArchiveTas
await handle?.close().catch(() => {})
task.bytes = await stat(tempPath).then(info => info.size).catch(() => 0)
settle(error instanceof Error ? error.message : String(error))
await rm(tempPath, { force: true }).catch(() => {})
if (ownsTemp) await rm(tempPath, { force: true }).catch(() => {})
}
}
}
+7 -1
View File
@@ -1846,7 +1846,13 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
const type = mediaTypeForPath(path)
// Raw bytes either way (binary-safe); ?download=1 switches the
// disposition so the browser saves the file instead of showing it.
const headers: Record<string, string> = { 'content-type': type, 'cache-control': 'no-cache' }
const headers: Record<string, string> = {
'content-type': type,
'cache-control': 'no-cache',
'content-security-policy': "sandbox allow-scripts allow-popups allow-downloads allow-modals; object-src 'none'",
'x-content-type-options': 'nosniff',
'referrer-policy': 'no-referrer',
}
// An SVG is a scriptable DOCUMENT, not an inert image: navigating to
// this URL directly would run its <script> in the GUI's origin, with
// same-origin access to /sidebar/api/*. The sibling html route already
+21
View File
@@ -495,6 +495,27 @@ describe('archive task table (injected spawn)', () => {
expect(tasks.size()).toBe(ARCHIVE_MAX_BUILDING)
})
it('reserves concurrency slots before asynchronous tool resolution', async () => {
const { tasks } = makeTable({ behavior: { run: { hang: true } } })
const paths = sampleSelection()
const outcomes = await Promise.allSettled(Array.from({ length: 10 }, (_, index) =>
tasks.start({ sessionId: 's-1', name: `parallel-${index}`, paths })))
expect(outcomes.filter(item => item.status === 'fulfilled')).toHaveLength(ARCHIVE_MAX_BUILDING)
expect(outcomes.filter(item => item.status === 'rejected')).toHaveLength(10 - ARCHIVE_MAX_BUILDING)
expect(tasks.size()).toBe(ARCHIVE_MAX_BUILDING)
})
it('rejects a tool lookup that completes after disposal without spawning', async () => {
let release!: () => void
const gate = new Promise<void>(resolve => { release = resolve })
const tasks = createArchiveTasks({ resolveTool: async () => { await gate; return { tool: 'zip', bin: 'zip', flags: [], ext: '.zip' } } })
const pending = tasks.start({ sessionId: 's-1', name: 'late', paths: sampleSelection() })
tasks.dispose()
release()
await expect(pending).rejects.toMatchObject({ status: 503 })
expect(tasks.size()).toBe(0)
})
it('expires a settled task after ARCHIVE_TTL_MS and deletes its file', async () => {
const { tasks, tempDir: archives } = makeTable({ behavior: { run: { bytes: Buffer.from('x') } } })
const { id } = await tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() })
+15
View File
@@ -167,6 +167,21 @@ describe('/sidebar/file streams without a size cap', () => {
expect(response.headers.get('referrer-policy')).toBe('no-referrer')
})
it.each(['html', 'htm', 'HTML', 'bin'])('keeps arbitrary file previews in an opaque origin (%s)', async extension => {
const ws = workspace('opaque-preview')
const target = join(ws, `preview.${extension}`)
writeFileSync(target, '<script>window.fixture = true</script>')
const { origin } = await serve(ws)
const response = await fetch(fileUrl(origin, ws, target))
expect(response.status).toBe(200)
const policy = response.headers.get('content-security-policy') ?? ''
expect(policy).toContain('sandbox')
expect(policy).not.toContain('allow-same-origin')
expect(response.headers.get('x-content-type-options')).toBe('nosniff')
expect(response.headers.get('referrer-policy')).toBe('no-referrer')
expect(await response.text()).toContain('window.fixture')
})
it('answers the JSON error envelope when the file cannot be opened', async () => {
const ws = workspace('missing')
const { origin } = await serve(ws)