diff --git a/backend/src/db/schema.ts b/backend/src/db/schema.ts index 39b5749f..9e53ef7b 100644 --- a/backend/src/db/schema.ts +++ b/backend/src/db/schema.ts @@ -1,14 +1,14 @@ import { Database } from 'bun:sqlite' import { logger } from '../utils/logger' -import { mkdirSync } from 'fs' import { dirname } from 'path' import { migrate } from './migration-runner' import { allMigrations } from './migrations' import { ensureOpenCodeModelStateTable } from './model-state' import { ensureAssistantRepo } from './queries' +import { mkdirSyncSafe } from '../utils/fs-safe' export function initializeDatabase(dbPath: string = './data/opencode.db'): Database { - mkdirSync(dirname(dbPath), { recursive: true }) + mkdirSyncSafe(dirname(dbPath)) const db = new Database(dbPath) migrate(db, allMigrations) diff --git a/backend/src/ipc/sshHostKeyHandler.ts b/backend/src/ipc/sshHostKeyHandler.ts index 3a0caa3b..77ae5dfc 100644 --- a/backend/src/ipc/sshHostKeyHandler.ts +++ b/backend/src/ipc/sshHostKeyHandler.ts @@ -8,6 +8,7 @@ import { getWorkspacePath } from '@opencode-manager/shared/config/env' import { broadcastSSHHostKeyRequest } from '../services/sse-aggregator' import { executeCommand } from '../utils/process' import { parseSSHHost, normalizeHostPort } from '../utils/ssh-key-manager' +import { mkdirSafe } from '../utils/fs-safe' interface SSHHostKeyRequest { id: string @@ -40,7 +41,7 @@ export class SSHHostKeyHandler implements IPCHandler { private async ensureKnownHostsFile(): Promise { try { const configDir = path.join(getWorkspacePath(), 'config') - await fs.mkdir(configDir, { recursive: true }) + await mkdirSafe(configDir) try { await fs.access(this.knownHostsPath) } catch { diff --git a/backend/src/routes/internal/repo-mirror-helpers.ts b/backend/src/routes/internal/repo-mirror-helpers.ts index d8874385..0e7202f9 100644 --- a/backend/src/routes/internal/repo-mirror-helpers.ts +++ b/backend/src/routes/internal/repo-mirror-helpers.ts @@ -1,11 +1,12 @@ import { spawn, spawnSync } from 'child_process' -import { existsSync, mkdirSync, mkdtempSync, readdirSync, statSync } from 'fs' +import { existsSync, mkdtempSync, readdirSync, statSync } from 'fs' import * as fsp from 'fs/promises' import { createReadStream } from 'fs' import { dirname, join } from 'path' import { pipeline } from 'stream/promises' import { randomUUID } from 'crypto' import { getReposPath } from '@opencode-manager/shared/config/env' +import { mkdirSafe, mkdirSyncSafe } from '../../utils/fs-safe' export const MIRROR_CHUNK_SIZE = 8 * 1024 * 1024 const STALE_UPLOAD_MS = 24 * 60 * 60 * 1000 @@ -52,7 +53,7 @@ export function getPartPath(uploadId: string, index: number): string { export async function createUploadSession(meta: Omit): Promise { const uploadId = randomUUID() - mkdirSync(getPartsDir(uploadId), { recursive: true }) + mkdirSyncSafe(getPartsDir(uploadId)) const full: UploadMeta = { ...meta, uploadId, startedAt: Date.now() } await fsp.writeFile(getMetaPath(uploadId), JSON.stringify(full), 'utf-8') return full @@ -99,7 +100,7 @@ export async function extractPartsToStaging(uploadId: string, totalParts: number } const stagingParent = getStagingRoot() - mkdirSync(stagingParent, { recursive: true }) + mkdirSyncSafe(stagingParent) const staging = mkdtempSync(join(stagingParent, 'recv-')) const tarArgs = ['-x', '-f', '-', '-C', staging] @@ -154,7 +155,7 @@ export interface SwapResult { } export async function atomicSwapIntoPlace(extractedRoot: string, fullPath: string): Promise { - await fsp.mkdir(dirname(fullPath), { recursive: true }) + await mkdirSafe(dirname(fullPath)) let backupDir: string | undefined if (existsSync(fullPath)) { @@ -191,7 +192,7 @@ export async function carryOverIgnoredFiles(backupDir: string | undefined, fullP const src = join(backupDir, clean) const dest = join(fullPath, clean) if (!existsSync(src) || existsSync(dest)) continue - await fsp.mkdir(dirname(dest), { recursive: true }) + await mkdirSafe(dirname(dest)) await fsp.rename(src, dest).catch(() => {}) } } diff --git a/backend/src/routes/internal/repo-mirror.ts b/backend/src/routes/internal/repo-mirror.ts index 30349a13..d0182cc4 100644 --- a/backend/src/routes/internal/repo-mirror.ts +++ b/backend/src/routes/internal/repo-mirror.ts @@ -2,7 +2,7 @@ import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import { spawn } from 'child_process' import { copyFileSync, createReadStream, createWriteStream, existsSync } from 'fs' -import { mkdirSync, mkdtempSync, writeFileSync } from 'fs' +import { mkdtempSync, writeFileSync } from 'fs' import { Readable } from 'stream' import { pipeline } from 'stream/promises' import { join } from 'path' @@ -12,6 +12,7 @@ import { getRepoById, updateLastPulled, updateRepoBranch, deleteRepo } from '../ import { ensureMirrorTargetPath, createRepoRow, isRepoInUse } from '../../services/repo' import { logger } from '../../utils/logger' import { getErrorMessage } from '../../utils/error-utils' +import { mkdirSyncSafe } from '../../utils/fs-safe' import { safeGitOut, gitOut } from './repo-sync-helpers' import { MIRROR_CHUNK_SIZE, @@ -129,7 +130,7 @@ async function importBundle(fullPath: string, bundlePath: string, branch: string async function createBundle(fullPath: string): Promise { const stagingRoot = getStagingRoot() - mkdirSync(stagingRoot, { recursive: true }) + mkdirSyncSafe(stagingRoot) const bundleDir = mkdtempSync(join(stagingRoot, 'bundle-')) const bundlePath = join(bundleDir, 'repo.bundle') await gitRaw(fullPath, ['bundle', 'create', bundlePath, '--all']) @@ -344,7 +345,7 @@ export function createInternalRepoMirrorRoutes(db: Database) { if (!rawBody) return c.json({ error: 'no body provided' }, 400) const stagingRoot = getStagingRoot() - mkdirSync(stagingRoot, { recursive: true }) + mkdirSyncSafe(stagingRoot) const bundleDir = mkdtempSync(join(stagingRoot, 'bundle-upload-')) const bundlePath = join(bundleDir, 'repo.bundle') const branch = c.req.header('x-ocm-branch')?.trim() || null @@ -497,7 +498,7 @@ export function createInternalRepoMirrorRoutes(db: Database) { const ignored = await gitOut(fullPath, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory']) if (ignored.trim()) { const excludeParent = getStagingRoot() - mkdirSync(excludeParent, { recursive: true }) + mkdirSyncSafe(excludeParent) ignoreFile = mkdtempSync(join(excludeParent, 'exclude-')) writeFileSync(join(ignoreFile, '.gitignore'), ignored) excludeArgs.push('--exclude-from', join(ignoreFile, '.gitignore')) diff --git a/backend/src/routes/mcp-oauth-proxy.ts b/backend/src/routes/mcp-oauth-proxy.ts index 6b84d0b2..ded95253 100644 --- a/backend/src/routes/mcp-oauth-proxy.ts +++ b/backend/src/routes/mcp-oauth-proxy.ts @@ -3,9 +3,10 @@ import type { OpenCodeClient } from '../services/opencode/client' import { z } from 'zod' import crypto from 'crypto' import path from 'path' -import { readFile, writeFile, mkdir } from 'fs/promises' +import { readFile, writeFile } from 'fs/promises' import { storeMcpOAuthFlow, consumeMcpOAuthFlow, deleteMcpOAuthFlow, markMcpOAuthFlowCompleted, markMcpOAuthFlowFailed, getMcpOAuthFlowResult } from '../services/mcp-oauth-state' import { logger } from '../utils/logger' +import { mkdirSafe } from '../utils/fs-safe' import { getWorkspacePath } from '@opencode-manager/shared/config/env' const StartSchema = z.object({ @@ -32,7 +33,7 @@ async function readMcpAuth(): Promise> { async function writeMcpAuth(data: Record): Promise { const filePath = getMcpAuthPath() - await mkdir(path.dirname(filePath), { recursive: true }) + await mkdirSafe(path.dirname(filePath)) await writeFile(filePath, JSON.stringify(data, null, 2), { mode: 0o600 }) } diff --git a/backend/src/routes/tts.ts b/backend/src/routes/tts.ts index 244c96fb..5f463ca9 100644 --- a/backend/src/routes/tts.ts +++ b/backend/src/routes/tts.ts @@ -2,10 +2,11 @@ import { Hono } from 'hono' import { z } from 'zod' import { Database } from 'bun:sqlite' import { createHash } from 'crypto' -import { mkdir, readFile, writeFile, readdir, stat, unlink } from 'fs/promises' +import { readFile, writeFile, readdir, stat, unlink } from 'fs/promises' import { join } from 'path' import { SettingsService } from '../services/settings' import { logger } from '../utils/logger' +import { mkdirSafe } from '../utils/fs-safe' import { getWorkspacePath } from '@opencode-manager/shared/config/env' import { normalizeToBaseUrl, @@ -29,7 +30,7 @@ function generateCacheKey(text: string, voice: string, model: string, speed: num } async function ensureCacheDir(): Promise { - await mkdir(TTS_CACHE_DIR, { recursive: true }) + await mkdirSafe(TTS_CACHE_DIR) } async function getCachedAudio(cacheKey: string): Promise { diff --git a/backend/src/services/auth.ts b/backend/src/services/auth.ts index c842e526..539d21c7 100644 --- a/backend/src/services/auth.ts +++ b/backend/src/services/auth.ts @@ -4,6 +4,7 @@ import { getAuthPath } from '@opencode-manager/shared/config/env' import { logger } from '../utils/logger' import { AuthCredentialsSchema } from '../../../shared/src/schemas/auth' import type { z } from 'zod' +import { mkdirSafe } from '../utils/fs-safe' type AuthCredentials = z.infer @@ -58,7 +59,7 @@ export class AuthService { key: apiKey, } - await fs.mkdir(path.dirname(this.authPath), { recursive: true }) + await mkdirSafe(path.dirname(this.authPath)) await fs.writeFile(this.authPath, JSON.stringify(auth, null, 2), { mode: 0o600 }) logger.info(`Set credentials for provider: ${providerId}`) diff --git a/backend/src/services/file-operations.ts b/backend/src/services/file-operations.ts index a1cccd21..2be0c07b 100644 --- a/backend/src/services/file-operations.ts +++ b/backend/src/services/file-operations.ts @@ -2,6 +2,7 @@ import { promises as fs } from 'fs' import path from 'path' import { logger } from '../utils/logger' import { getReposPath } from '@opencode-manager/shared/config/env' +import { mkdirSafe } from '../utils/fs-safe' export async function readFileContent(filePath: string): Promise { try { @@ -29,7 +30,7 @@ export async function writeFileContent( try { const fullPath = path.isAbsolute(filePath) ? filePath : path.join(getReposPath(), filePath) - await fs.mkdir(path.dirname(fullPath), { recursive: true }) + await mkdirSafe(path.dirname(fullPath)) await fs.writeFile(fullPath, Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf8')) logger.info(`Wrote file to: ${fullPath}`) @@ -41,7 +42,7 @@ export async function writeFileContent( export async function ensureDirectoryExists(dirPath: string): Promise { try { const fullPath = path.isAbsolute(dirPath) ? dirPath : path.resolve(dirPath) - await fs.mkdir(fullPath, { recursive: true }) + await mkdirSafe(fullPath) } catch (error) { throw new Error(`Failed to create directory ${dirPath}: ${error}`) } diff --git a/backend/src/services/files.ts b/backend/src/services/files.ts index 4dfc77f1..8979ed73 100644 --- a/backend/src/services/files.ts +++ b/backend/src/services/files.ts @@ -3,6 +3,7 @@ import path from 'path' import { createReadStream } from 'fs' import { createInterface } from 'readline' import { logger } from '../utils/logger' +import { mkdirSafe } from '../utils/fs-safe' import { readFileContent, @@ -160,7 +161,7 @@ export async function uploadFile(userPath: string, file: File, relativePath?: st } const parentDir = path.dirname(fullPath) - await fs.mkdir(parentDir, { recursive: true }) + await mkdirSafe(parentDir) const buffer = await file.arrayBuffer() @@ -178,7 +179,7 @@ export async function createFileOrFolder(userPath: string, body: { type: 'file' const validatedPath = validatePath(userPath) if (body.type === 'folder') { - await fs.mkdir(validatedPath, { recursive: true }) + await mkdirSafe(validatedPath) return { name: path.basename(validatedPath), path: userPath, @@ -216,7 +217,7 @@ export async function renameOrMoveFile(userPath: string, body: { newPath: string const newValidatedPath = validatePath(body.newPath) // Create parent directory if needed - await fs.mkdir(path.dirname(newValidatedPath), { recursive: true }) + await mkdirSafe(path.dirname(newValidatedPath)) // Move/rename file await fs.rename(oldValidatedPath, newValidatedPath) diff --git a/backend/src/services/opencode-directory-files.ts b/backend/src/services/opencode-directory-files.ts index 32e64cad..eb6f8e51 100644 --- a/backend/src/services/opencode-directory-files.ts +++ b/backend/src/services/opencode-directory-files.ts @@ -2,6 +2,7 @@ import path from 'path' import { promises as fs } from 'fs' import { getWorkspacePath } from '@opencode-manager/shared/config/env' import { normalizeUploadRelativePath, resolveWithinDirectory } from './file-operations' +import { mkdirSafe } from '../utils/fs-safe' export type OpenCodeDirectoryFileKind = 'agents' | 'commands' @@ -82,11 +83,11 @@ export async function installOpenCodeDirectoryFiles( targetFilePath: resolveWithinDirectory(targetRoot, file.relativePath, `${kind} directory`), })) - await fs.mkdir(targetRoot, { recursive: true }) + await mkdirSafe(targetRoot) await Promise.all( targets.map(async target => { - await fs.mkdir(path.dirname(target.targetFilePath), { recursive: true }) + await mkdirSafe(path.dirname(target.targetFilePath)) await fs.writeFile(target.targetFilePath, target.content) }), ) diff --git a/backend/src/services/opencode-gh-env-plugin.ts b/backend/src/services/opencode-gh-env-plugin.ts index 81e908d0..67758f1e 100644 --- a/backend/src/services/opencode-gh-env-plugin.ts +++ b/backend/src/services/opencode-gh-env-plugin.ts @@ -1,6 +1,7 @@ import { promises as fs } from 'fs' import path from 'path' import { logger } from '../utils/logger' +import { mkdirSafe } from '../utils/fs-safe' const PLUGIN_FILENAME = 'ocm-gh-env.js' @@ -48,7 +49,7 @@ export function getGhEnvPluginDir(configHome: string): string { export async function installGhEnvPlugin(configHome: string): Promise { try { const dir = getGhEnvPluginDir(configHome) - await fs.mkdir(dir, { recursive: true }) + await mkdirSafe(dir) await fs.writeFile(path.join(dir, PLUGIN_FILENAME), PLUGIN_SOURCE, 'utf-8') } catch (error) { logger.warn('Failed to install gh-env OpenCode plugin:', error) diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index b73bacdd..964269b5 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -26,6 +26,7 @@ import { writeFileContent } from './file-operations' import { getOrCreateInternalToken } from './internal-token' import { installGhEnvPlugin } from './opencode-gh-env-plugin' import { CredentialProvider } from './credential-provider' +import { mkdirSafe } from '../utils/fs-safe' const MIN_OPENCODE_VERSION = '1.0.137' @@ -495,7 +496,7 @@ class OpenCodeServerManager { const packageJsonPath = path.join(binDir, 'package.json') try { - await fs.mkdir(binDir, { recursive: true }) + await mkdirSafe(binDir) const packageJsonExists = await fs.access(packageJsonPath) .then(() => true) @@ -600,7 +601,7 @@ class OpenCodeServerManager { } } - await fs.mkdir(installDir, { recursive: true }) + await mkdirSafe(installDir) if (!await fs.access(path.join(installDir, 'package.json')).then(() => true).catch(() => false)) { const init = spawnSync('bun', ['init', '-y'], { cwd: installDir, encoding: 'utf8', timeout: 30000 }) if (init.status !== 0) { diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 50606dc7..55fc2b56 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -19,6 +19,7 @@ import { listRepos } from '../db/queries' import { listActiveScheduleRunWorkspaces } from '../db/schedules' import { SettingsService } from './settings' import type { OpenCodeClient } from './opencode/client' +import { mkdirSafe } from '../utils/fs-safe' const GIT_CLONE_TIMEOUT = 300000 const DEFAULT_DISCOVERY_MAX_DEPTH = 4 @@ -186,7 +187,7 @@ async function createWorkspaceLink(alias: string, sourcePath: string): Promise>() @@ -20,7 +21,7 @@ export async function readJsonSafe(filePath: string, fallback: T): Promise export async function writeJsonAtomic(filePath: string, data: unknown): Promise { const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}.${randomBytes(4).toString('hex')}` try { - await fs.mkdir(filePath.substring(0, filePath.lastIndexOf('/')), { recursive: true }) + await mkdirSafe(filePath.substring(0, filePath.lastIndexOf('/'))) await fs.writeFile(tmpPath, JSON.stringify(data, null, 2), 'utf8') await fs.rename(tmpPath, filePath) } catch (error) { diff --git a/backend/src/utils/discovery-cache.ts b/backend/src/utils/discovery-cache.ts index 689b2a79..ecf47bfd 100644 --- a/backend/src/utils/discovery-cache.ts +++ b/backend/src/utils/discovery-cache.ts @@ -1,7 +1,8 @@ import { createHash } from 'crypto' -import { mkdir, readFile, writeFile, stat, unlink } from 'fs/promises' +import { readFile, writeFile, stat, unlink } from 'fs/promises' import { join } from 'path' import { logger } from './logger' +import { mkdirSafe } from './fs-safe' import { getWorkspacePath } from '@opencode-manager/shared/config/env' const DISCOVERY_CACHE_DIR = join(getWorkspacePath(), 'cache', 'discovery') @@ -17,7 +18,7 @@ export function normalizeToBaseUrl(endpoint: string): string { } async function ensureDiscoveryCacheDir(): Promise { - await mkdir(DISCOVERY_CACHE_DIR, { recursive: true }) + await mkdirSafe(DISCOVERY_CACHE_DIR) } async function getCachedDiscovery(cacheKey: string): Promise { diff --git a/backend/src/utils/fs-safe.test.ts b/backend/src/utils/fs-safe.test.ts new file mode 100644 index 00000000..80952fc0 --- /dev/null +++ b/backend/src/utils/fs-safe.test.ts @@ -0,0 +1,109 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { mkdirSafe, mkdirSyncSafe } from './fs-safe' +import { join } from 'node:path' +import { mkdtemp, rm, mkdir, stat, chmod } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import * as nodeFs from 'node:fs' +import { statSync, mkdirSync, chmodSync } from 'node:fs' + +describe('fs-safe', () => { + let tmpDir: string + + beforeEach(async () => { + tmpDir = await mkdtemp(join(tmpdir(), 'fs-safe-test-')) + }) + + afterEach(async () => { + await rm(tmpDir, { recursive: true, force: true }) + vi.restoreAllMocks() + }) + + describe('mkdirSafe', () => { + it('creates nested directories that do not exist', async () => { + const dir = join(tmpDir, 'a', 'b', 'c') + await mkdirSafe(dir) + const stats = await stat(dir) + expect(stats.isDirectory()).toBe(true) + }) + + it('resolves without error when the directory already exists', async () => { + const dir = join(tmpDir, 'existing') + await mkdir(dir, { recursive: true }) + await expect(mkdirSafe(dir)).resolves.toBeUndefined() + }) + + it('honors mode option', async () => { + const previousUmask = process.umask(0) + try { + const dir = join(tmpDir, 'mode700') + await mkdirSafe(dir, { mode: 0o700 }) + const stats = await stat(dir) + expect(stats.mode & 0o777).toBe(0o700) + } finally { + process.umask(previousUmask) + } + }) + + it('rethrows EACCES when the target directory truly does not exist', async () => { + const parent = join(tmpDir, 'readonly-parent') + await mkdir(parent, { recursive: true }) + await chmod(parent, 0o555) + try { + await expect(mkdirSafe(join(parent, 'child'))).rejects.toMatchObject({ + code: 'EACCES', + }) + } finally { + await chmod(parent, 0o755) + } + }) + + it('swallows EACCES when the target directory already exists', async () => { + const dir = join(tmpDir, 'exists-eacces') + await mkdir(dir, { recursive: true }) + const spy = vi.spyOn(nodeFs.promises, 'mkdir').mockRejectedValueOnce( + Object.assign(new Error('EACCES'), { code: 'EACCES' }), + ) + await expect(mkdirSafe(dir)).resolves.toBeUndefined() + expect(spy).toHaveBeenCalled() + }) + + it('rethrows non-permission errors unchanged', async () => { + const dir = join(tmpDir, 'enospc') + await mkdir(dir, { recursive: true }) + const spy = vi.spyOn(nodeFs.promises, 'mkdir').mockRejectedValueOnce( + Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' }), + ) + await expect(mkdirSafe(dir)).rejects.toMatchObject({ code: 'ENOSPC' }) + expect(spy).toHaveBeenCalled() + }) + }) + + describe('mkdirSyncSafe', () => { + it('creates nested directories that do not exist', () => { + const dir = join(tmpDir, 'sync', 'a', 'b') + mkdirSyncSafe(dir) + expect(statSync(dir).isDirectory()).toBe(true) + }) + + it('resolves without error when the directory already exists', () => { + const dir = join(tmpDir, 'sync-existing') + mkdirSync(dir, { recursive: true }) + expect(() => mkdirSyncSafe(dir)).not.toThrow() + }) + + it('rethrows EACCES when the target directory truly does not exist', () => { + const parent = join(tmpDir, 'sync-readonly-parent') + mkdirSync(parent, { recursive: true }) + chmodSync(parent, 0o555) + let threw: unknown + try { + mkdirSyncSafe(join(parent, 'child')) + } catch (error) { + threw = error + } finally { + chmodSync(parent, 0o755) + } + expect(threw).toMatchObject({ code: 'EACCES' }) + }) + }) +}) diff --git a/backend/src/utils/fs-safe.ts b/backend/src/utils/fs-safe.ts new file mode 100644 index 00000000..9b8db24d --- /dev/null +++ b/backend/src/utils/fs-safe.ts @@ -0,0 +1,36 @@ +import { promises as fs, mkdirSync, accessSync, constants } from 'node:fs' + +interface MkdirSafeOptions { + mode?: number +} + +function isPermissionError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException).code + return code === 'EACCES' || code === 'EPERM' +} + +export async function mkdirSafe(dirPath: string, options: MkdirSafeOptions = {}): Promise { + try { + await fs.mkdir(dirPath, { ...options, recursive: true }) + } catch (error) { + if (!isPermissionError(error)) throw error + try { + await fs.access(dirPath, constants.X_OK) + } catch { + throw error + } + } +} + +export function mkdirSyncSafe(dirPath: string, options: MkdirSafeOptions = {}): void { + try { + mkdirSync(dirPath, { ...options, recursive: true }) + } catch (error) { + if (!isPermissionError(error)) throw error + try { + accessSync(dirPath, constants.X_OK) + } catch { + throw error + } + } +} diff --git a/backend/src/utils/ssh-key-manager.ts b/backend/src/utils/ssh-key-manager.ts index 7707bcbb..845d60a2 100644 --- a/backend/src/utils/ssh-key-manager.ts +++ b/backend/src/utils/ssh-key-manager.ts @@ -4,6 +4,7 @@ import { execFile } from 'node:child_process' import { randomBytes } from 'node:crypto' import { join } from 'node:path' import { getWorkspacePath } from '@opencode-manager/shared/config/env' +import { mkdirSafe } from './fs-safe' const SSH_KEYS_DIR = join(getWorkspacePath(), '.ssh-keys') @@ -11,7 +12,7 @@ async function ensureSSHKeysDir(): Promise { try { await fs.access(SSH_KEYS_DIR) } catch { - await fs.mkdir(SSH_KEYS_DIR, { mode: 0o700, recursive: true }) + await mkdirSafe(SSH_KEYS_DIR, { mode: 0o700 }) } } @@ -169,7 +170,7 @@ export async function writeSSHConfig(configPath: string, configContent: string): try { await fs.access(dir) } catch { - await fs.mkdir(dir, { mode: 0o700, recursive: true }) + await mkdirSafe(dir, { mode: 0o700 }) } await fs.writeFile(configPath, configContent, { mode: 0o600 }) diff --git a/backend/test/routes/stt.test.ts b/backend/test/routes/stt.test.ts index f970d441..7fc07d9d 100644 --- a/backend/test/routes/stt.test.ts +++ b/backend/test/routes/stt.test.ts @@ -9,6 +9,11 @@ vi.mock('fs/promises', () => ({ unlink: vi.fn(), })) +vi.mock('../../src/utils/fs-safe', () => ({ + mkdirSafe: vi.fn().mockResolvedValue(undefined), + mkdirSyncSafe: vi.fn(), +})) + vi.mock('bun:sqlite', () => ({ Database: vi.fn(), })) diff --git a/backend/test/routes/tts.test.ts b/backend/test/routes/tts.test.ts index d882bcb1..f02b9669 100644 --- a/backend/test/routes/tts.test.ts +++ b/backend/test/routes/tts.test.ts @@ -10,6 +10,11 @@ vi.mock('fs/promises', () => ({ unlink: vi.fn(), })) +vi.mock('../../src/utils/fs-safe', () => ({ + mkdirSafe: vi.fn().mockResolvedValue(undefined), + mkdirSyncSafe: vi.fn(), +})) + vi.mock('bun:sqlite', () => ({ Database: vi.fn(), })) @@ -24,7 +29,6 @@ vi.mock('../../src/utils/logger', () => ({ }, })) -const mockMkdir = fs.mkdir as any const mockReadFile = fs.readFile as any const mockReaddir = fs.readdir as any const mockStat = fs.stat as any @@ -66,14 +70,7 @@ describe('TTS Routes', () => { describe('ensureCacheDir', () => { it('should create cache directory when it does not exist', async () => { - mockMkdir.mockResolvedValue(undefined) - - await ensureCacheDir() - - expect(mockMkdir).toHaveBeenCalledWith( - expect.stringContaining('cache/tts'), - { recursive: true } - ) + await expect(ensureCacheDir()).resolves.toBeUndefined() }) })