Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach } from 'bun:test'
import { mkdirSync, writeFileSync, rmSync, existsSync, readFileSync } from 'fs'
import { join } from 'path'
import { join, sep } from 'path'
import { tmpdir } from 'os'
import {
collectDirectoryFiles,
Expand Down Expand Up @@ -226,6 +226,21 @@ describe('bundle-files', () => {
expect(readFileSync(join(target, 'test.txt'), 'utf-8')).toBe('restored content')
})

it('restores files when target directory has a trailing separator', () => {
const content = Buffer.from('restored content')
const files: BundleFile[] = [{
relativePath: 'test.txt',
contentBase64: content.toString('base64'),
size: content.length,
}]

const target = join(tmpDir, 'target')
mkdirSync(target)
restoreFiles(`${target}${sep}`, files)

expect(readFileSync(join(target, 'test.txt'), 'utf-8')).toBe('restored content')
})

it('creates subdirectories as needed', () => {
const content = Buffer.from('nested')
const files: BundleFile[] = [{
Expand Down
13 changes: 10 additions & 3 deletions packages/desktop/packages/shared/src/utils/bundle-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
*/

import { existsSync, readdirSync, readFileSync, statSync, mkdirSync, writeFileSync } from 'fs'
import { join, relative, dirname, sep } from 'path'
import { join, relative, dirname, sep, resolve, isAbsolute } from 'path'
import { debug } from './debug.ts'

/**
Expand Down Expand Up @@ -175,17 +175,24 @@ export function collectDirectoryFiles(dir: string, options?: CollectOptions): Bu
* @throws Error if any file fails path validation (path traversal, absolute path, etc.)
*/
export function restoreFiles(targetDir: string, files: BundleFile[]): void {
const resolvedTargetDir = resolve(targetDir)

for (const file of files) {
const error = validateBundleFile(file)
if (error) {
throw new Error(`Invalid bundle file: ${error}`)
}

const nativePath = fromPortableRelPath(file.relativePath)
const fullPath = join(targetDir, nativePath)
const fullPath = resolve(resolvedTargetDir, nativePath)

// Safety: ensure resolved path is inside target dir
if (!fullPath.startsWith(targetDir + sep) && fullPath !== targetDir) {
const relativeFromTarget = relative(resolvedTargetDir, fullPath)
if (
relativeFromTarget === '..' ||
relativeFromTarget.startsWith(`..${sep}`) ||
isAbsolute(relativeFromTarget)
) {
throw new Error(`Path escapes target directory: ${file.relativePath}`)
}

Expand Down
Loading