fix(fs): tolerate EACCES on existing mkdir targets (#319)

Add mkdirSafe/mkdirSyncSafe helpers that swallow EACCES/EPERM when the
target directory already exists with execute permission, and route all
recursive mkdir call sites through them so pre-existing directories
owned by another user do not break backend startup, file ops, or repo
mirroring.
This commit is contained in:
Chris Scott authored and GitHub committed 2026-07-23 22:51:17 -04:00
1 parent 8a8bdc18b0
commit 87f3d7f230
22 files changed
+210 -46

No files matched your search

+2 -2
View File
@@ -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)
+2 -1
View File
@@ -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<void> {
try {
const configDir = path.join(getWorkspacePath(), 'config')
await fs.mkdir(configDir, { recursive: true })
await mkdirSafe(configDir)
try {
await fs.access(this.knownHostsPath)
} catch {
@@ -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<UploadMeta, 'uploadId' | 'startedAt'>): Promise<UploadMeta> {
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<SwapResult> {
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(() => {})
}
}
+5 -4
View File
@@ -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<string> {
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'))
+3 -2
View File
@@ -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<Record<string, unknown>> {
async function writeMcpAuth(data: Record<string, unknown>): Promise<void> {
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 })
}
+3 -2
View File
@@ -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<void> {
await mkdir(TTS_CACHE_DIR, { recursive: true })
await mkdirSafe(TTS_CACHE_DIR)
}
async function getCachedAudio(cacheKey: string): Promise<Buffer | null> {
+2 -1
View File
@@ -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<typeof AuthCredentialsSchema>
@@ -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}`)
+3 -2
View File
@@ -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<string> {
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<void> {
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}`)
}
+4 -3
View File
@@ -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)
@@ -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)
}),
)
@@ -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<void> {
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)
@@ -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) {
+2 -1
View File
@@ -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<v
return
}
await fs.mkdir(path.dirname(aliasPath), { recursive: true })
await mkdirSafe(path.dirname(aliasPath))
await fs.symlink(sourcePath, aliasPath, process.platform === 'win32' ? 'junction' : 'dir')
}
+3 -2
View File
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync } from 'node:fs'
import { existsSync } from 'node:fs'
import path from 'path'
import type { Database } from 'bun:sqlite'
import { getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
@@ -12,6 +12,7 @@ import { resolveGitIdentity, createGitIdentityEnv, isSSHUrl } from '../utils/git
import { executeCommand } from '../utils/process'
import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo'
import { logger } from '../utils/logger'
import { mkdirSyncSafe } from '../utils/fs-safe'
export interface ScheduleWorktreeContext {
directory: string
@@ -115,7 +116,7 @@ export class ScheduleWorktreeManager {
// Fallback: raw git worktree
const worktreePath = path.join(getScheduleWorktreesPath(), `job-${job.id}-run-${runId}`)
mkdirSync(path.dirname(worktreePath), { recursive: true })
mkdirSyncSafe(path.dirname(worktreePath))
await createWorktreeSafely(repo.fullPath, worktreePath, runBranch, env, baseRef)
if (!existsSync(worktreePath)) {
+3 -2
View File
@@ -11,6 +11,7 @@ import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, d
import type { OpenCodeClient } from './opencode/client'
import { logger } from '../utils/logger'
import { githubFetchJson, githubFetchBinary, type GithubFetchFn } from '../utils/github'
import { mkdirSafe } from '../utils/fs-safe'
interface OpenCodeSkillInfo {
name: string
@@ -135,13 +136,13 @@ async function installSkillFiles(
throw new Error(`Skill "${prepared.skillName}" already exists in ${input.scope} scope`)
}
await fs.mkdir(targetRoot, { recursive: true })
await mkdirSafe(targetRoot)
const stagingDir = await fs.mkdtemp(path.join(targetRoot, `.${prepared.skillName}-install-`))
try {
for (const file of prepared.files) {
const targetFilePath = resolveWithinDirectory(stagingDir, file.relativePath, 'staging directory')
await fs.mkdir(path.dirname(targetFilePath), { recursive: true })
await mkdirSafe(path.dirname(targetFilePath))
await fs.writeFile(targetFilePath, file.content)
}
+2 -1
View File
@@ -1,6 +1,7 @@
import { promises as fs } from 'node:fs'
import { randomBytes } from 'node:crypto'
import { logger } from './logger'
import { mkdirSafe } from './fs-safe'
const fileLockPromises = new Map<string, Promise<unknown>>()
@@ -20,7 +21,7 @@ export async function readJsonSafe<T>(filePath: string, fallback: T): Promise<T>
export async function writeJsonAtomic(filePath: string, data: unknown): Promise<void> {
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) {
+3 -2
View File
@@ -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<void> {
await mkdir(DISCOVERY_CACHE_DIR, { recursive: true })
await mkdirSafe(DISCOVERY_CACHE_DIR)
}
async function getCachedDiscovery<T>(cacheKey: string): Promise<T | null> {
+109
View File
@@ -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' })
})
})
})
+36
View File
@@ -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<void> {
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
}
}
}
+3 -2
View File
@@ -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<void> {
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 })
+5
View File
@@ -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(),
}))
+6 -9
View File
@@ -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()
})
})