mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat: SSH Authentication Keys v2 (#113)
* feat: add SSH authentication keys v2 for Git operations Add comprehensive SSH key authentication support for Git operations including: - SSH host key verification with user approval flow - Encrypted SSH key storage with passphrase support - SSH connection testing endpoint - Real-time host key change warnings Backend changes: - New SSHHostKeyHandler for managing host key verification via IPC - Add passphrase handler for locked SSH keys - Add SSH key manager utilities (key writing, validation, cleanup) - Add crypto utilities for secure key/secret encryption - Add SSH validation utilities for key format checking - Add SSH routes for host key response handling - Enhance GitAuthService with SSH setup and environment methods - Update GitService to handle SSH authentication for push/fetch/pull - Update OpenCode server to support SSH keys with SSH config generation - Add database migration for trusted_ssh_hosts table - Add settings endpoint for SSH connection testing Frontend changes: - Add SSHHostKeyDialog for host key verification UI - Add PassphraseModal for SSH key passphrase input - Update GitCredentialDialog with SSH key type and testing - Update GitSettings to manage SSH keys - Add SSH API client and hooks (useSSH, usePassphraseHandler) Shared changes: - Add SSH schemas and types Test coverage: - Integration tests for SSH flow - IPC handler tests for host key and passphrase - SSH route tests - SSH utility validation tests - Updated existing tests for SSH-aware changes
This commit is contained in:
1 parent
3d5ee463d7
commit
414f39b809
54 files changed
+4051
-214
No files matched your search
@@ -1,12 +1,138 @@
|
||||
import type { IPCServer } from '../ipc/ipcServer'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { AskpassHandler } from '../ipc/askpassHandler'
|
||||
import { SSHHostKeyHandler } from '../ipc/sshHostKeyHandler'
|
||||
import { writeTemporarySSHKey, buildSSHCommand, buildSSHCommandWithKnownHosts, cleanupSSHKey, parseSSHHost } from '../utils/ssh-key-manager'
|
||||
import { decryptSecret } from '../utils/crypto'
|
||||
import { isSSHUrl, extractHostFromSSHUrl, getSSHCredentialsForHost, type GitCredential } from '../utils/git-auth'
|
||||
import { logger } from '../utils/logger'
|
||||
import { SettingsService } from './settings'
|
||||
|
||||
export class GitAuthService {
|
||||
private askpassHandler: AskpassHandler | null = null
|
||||
public sshHostKeyHandler: SSHHostKeyHandler | null = null
|
||||
private sshKeyPath: string | null = null
|
||||
private sshPassphrase: string | null = null
|
||||
private sshPort: string | null = null
|
||||
|
||||
initialize(ipcServer: IPCServer | undefined, database: Database): void {
|
||||
this.askpassHandler = new AskpassHandler(ipcServer, database)
|
||||
this.sshHostKeyHandler = new SSHHostKeyHandler(database, 120_000)
|
||||
this.sshHostKeyHandler.initialize()
|
||||
|
||||
if (ipcServer) {
|
||||
const handlerPath = 'ssh-host-key'
|
||||
ipcServer.registerHandler(handlerPath, this.sshHostKeyHandler)
|
||||
logger.info(`SSH host key handler registered with IPC server at /${handlerPath}`)
|
||||
}
|
||||
}
|
||||
|
||||
async setupSSHKey(credential: GitCredential): Promise<void> {
|
||||
if (credential.type !== 'ssh' || !credential.sshPrivateKeyEncrypted) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const privateKey = decryptSecret(credential.sshPrivateKeyEncrypted)
|
||||
this.sshKeyPath = await writeTemporarySSHKey(privateKey, credential.name)
|
||||
|
||||
if (credential.passphrase) {
|
||||
this.sshPassphrase = decryptSecret(credential.passphrase)
|
||||
logger.info(`SSH key with passphrase created for ${credential.name}: ${this.sshKeyPath}`)
|
||||
} else {
|
||||
this.sshPassphrase = null
|
||||
logger.info(`SSH key created for ${credential.name}: ${this.sshKeyPath}`)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Failed to setup SSH key for ${credential.name}:`, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
setSSHPort(port: string | null): void {
|
||||
this.sshPort = port
|
||||
}
|
||||
|
||||
getSSHEnvironment(): Record<string, string> {
|
||||
const knownHostsPath = this.sshHostKeyHandler?.getKnownHostsPath()
|
||||
const port = this.sshPort || undefined
|
||||
|
||||
if (!this.sshKeyPath) {
|
||||
if (knownHostsPath) {
|
||||
const sshCommand = buildSSHCommandWithKnownHosts(knownHostsPath, port)
|
||||
logger.info(`SSH environment: Using known_hosts=${knownHostsPath}, SSH_COMMAND=${sshCommand}`)
|
||||
return {
|
||||
GIT_SSH_COMMAND: sshCommand,
|
||||
...(this.sshHostKeyHandler?.getEnv() || {}),
|
||||
}
|
||||
}
|
||||
logger.info(`SSH environment: No SSH key and no known_hosts path, returning host key handler env only`)
|
||||
return {
|
||||
...(this.sshHostKeyHandler?.getEnv() || {}),
|
||||
}
|
||||
}
|
||||
|
||||
const sshResult = buildSSHCommand(this.sshKeyPath, this.sshPassphrase || undefined, knownHostsPath, port)
|
||||
logger.info(`SSH environment: Using SSH key=${this.sshKeyPath}, known_hosts=${knownHostsPath}, SSH_COMMAND=${sshResult.command}`)
|
||||
return {
|
||||
GIT_SSH_COMMAND: sshResult.command,
|
||||
...(sshResult.env || {}),
|
||||
...(this.sshHostKeyHandler?.getEnv() || {}),
|
||||
}
|
||||
}
|
||||
|
||||
async setupSSHForRepoUrl(repoUrl: string | undefined, database: Database): Promise<boolean> {
|
||||
if (!repoUrl || !isSSHUrl(repoUrl)) {
|
||||
return false
|
||||
}
|
||||
|
||||
const sshHost = extractHostFromSSHUrl(repoUrl)
|
||||
if (!sshHost) {
|
||||
logger.warn(`Could not extract SSH host from URL: ${repoUrl}`)
|
||||
return false
|
||||
}
|
||||
|
||||
const { port } = parseSSHHost(repoUrl)
|
||||
this.setSSHPort(port && port !== '22' ? port : null)
|
||||
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings('default')
|
||||
const gitCredentials = (settings.preferences.gitCredentials || []) as GitCredential[]
|
||||
const sshCredentials = getSSHCredentialsForHost(gitCredentials, sshHost)
|
||||
|
||||
if (sshCredentials.length > 0 && sshCredentials[0]) {
|
||||
try {
|
||||
await this.setupSSHKey(sshCredentials[0])
|
||||
} catch (error) {
|
||||
logger.error(`Failed to setup SSH key for ${sshHost}:`, error)
|
||||
throw new Error(`Failed to setup SSH authentication: ${error}`)
|
||||
}
|
||||
}
|
||||
|
||||
const verified = await this.verifyHostKeyBeforeOperation(repoUrl)
|
||||
if (!verified) {
|
||||
await this.cleanupSSHKey()
|
||||
throw new Error('SSH host key verification failed or was rejected by user')
|
||||
}
|
||||
|
||||
return sshCredentials.length > 0
|
||||
}
|
||||
|
||||
async verifyHostKeyBeforeOperation(repoUrl: string): Promise<boolean> {
|
||||
if (!this.sshHostKeyHandler) {
|
||||
return true
|
||||
}
|
||||
return this.sshHostKeyHandler.verifyHostKeyBeforeOperation(repoUrl)
|
||||
}
|
||||
|
||||
async cleanupSSHKey(): Promise<void> {
|
||||
if (this.sshKeyPath) {
|
||||
await cleanupSSHKey(this.sshKeyPath)
|
||||
this.sshKeyPath = null
|
||||
this.sshPassphrase = null
|
||||
this.sshPort = null
|
||||
logger.info('SSH key cleaned up')
|
||||
}
|
||||
}
|
||||
|
||||
getGitEnvironment(silent: boolean = false): Record<string, string> {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { executeCommand } from '../../utils/process'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { getErrorMessage } from '../../utils/error-utils'
|
||||
import { getRepoById } from '../../db/queries'
|
||||
import { resolveGitIdentity, createGitIdentityEnv } from '../../utils/git-auth'
|
||||
import { resolveGitIdentity, createGitIdentityEnv, isSSHUrl } from '../../utils/git-auth'
|
||||
import { isNoUpstreamError, parseBranchNameFromError } from '../../utils/git-errors'
|
||||
import { SettingsService } from '../settings'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
@@ -64,6 +64,17 @@ export class GitService {
|
||||
return this.getUntrackedFileDiff(repoPath, filePath, env)
|
||||
}
|
||||
|
||||
if (status.status === 'clean') {
|
||||
return {
|
||||
path: filePath,
|
||||
status: 'modified',
|
||||
diff: '',
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
isBinary: false
|
||||
}
|
||||
}
|
||||
|
||||
return this.getTrackedFileDiff(repoPath, filePath, env, includeStaged, options)
|
||||
}
|
||||
|
||||
@@ -187,7 +198,7 @@ export class GitService {
|
||||
const authEnv = this.gitAuthService.getGitEnvironment()
|
||||
|
||||
const settings = this.settingsService.getSettings('default')
|
||||
const gitCredentials = settings.preferences.gitCredentials || []
|
||||
const gitCredentials = (settings.preferences.gitCredentials || []) as import('../../utils/git-auth').GitCredential[]
|
||||
const identity = await resolveGitIdentity(settings.preferences.gitIdentity, gitCredentials)
|
||||
const identityEnv = identity ? createGitIdentityEnv(identity) : {}
|
||||
|
||||
@@ -257,6 +268,30 @@ export class GitService {
|
||||
}
|
||||
}
|
||||
|
||||
private async setupSSHIfNeeded(repoUrl: string | undefined, database: Database): Promise<void> {
|
||||
await this.gitAuthService.setupSSHForRepoUrl(repoUrl, database)
|
||||
}
|
||||
|
||||
private async cleanupSSHForRepo(): Promise<void> {
|
||||
await this.gitAuthService.cleanupSSHKey()
|
||||
}
|
||||
|
||||
private getEnvironmentForRepo(repo: { repoUrl?: string; fullPath: string }, silent: boolean = false): Record<string, string> {
|
||||
if (!repo.repoUrl) {
|
||||
return this.gitAuthService.getGitEnvironment(silent)
|
||||
}
|
||||
|
||||
const isSSH = isSSHUrl(repo.repoUrl)
|
||||
const baseEnv = this.gitAuthService.getGitEnvironment(silent)
|
||||
|
||||
if (!isSSH) {
|
||||
return baseEnv
|
||||
}
|
||||
|
||||
const sshEnv = this.gitAuthService.getSSHEnvironment()
|
||||
return { ...baseEnv, ...sshEnv }
|
||||
}
|
||||
|
||||
async resetToCommit(repoId: number, commitHash: string, database: Database): Promise<string> {
|
||||
try {
|
||||
const repo = getRepoById(database, repoId)
|
||||
@@ -284,20 +319,26 @@ export class GitService {
|
||||
}
|
||||
|
||||
const fullPath = path.resolve(repo.fullPath)
|
||||
const env = this.gitAuthService.getGitEnvironment()
|
||||
|
||||
if (options.setUpstream) {
|
||||
return await this.pushWithUpstream(repoId, fullPath, env)
|
||||
}
|
||||
await this.setupSSHIfNeeded(repo.repoUrl, database)
|
||||
|
||||
try {
|
||||
const args = ['git', '-C', fullPath, 'push']
|
||||
return await executeCommand(args, { env })
|
||||
} catch (error) {
|
||||
if (isNoUpstreamError(error as Error)) {
|
||||
const env = this.getEnvironmentForRepo(repo)
|
||||
if (options.setUpstream) {
|
||||
return await this.pushWithUpstream(repoId, fullPath, env)
|
||||
}
|
||||
throw error
|
||||
|
||||
try {
|
||||
const args = ['git', '-C', fullPath, 'push']
|
||||
return await executeCommand(args, { env })
|
||||
} catch (error) {
|
||||
if (isNoUpstreamError(error as Error)) {
|
||||
return await this.pushWithUpstream(repoId, fullPath, env)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} finally {
|
||||
await this.cleanupSSHForRepo()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,9 +349,15 @@ export class GitService {
|
||||
}
|
||||
|
||||
const fullPath = path.resolve(repo.fullPath)
|
||||
const env = this.gitAuthService.getGitEnvironment(true)
|
||||
|
||||
return executeCommand(['git', '-C', fullPath, 'fetch', '--all', '--prune'], { env })
|
||||
await this.setupSSHIfNeeded(repo.repoUrl, database)
|
||||
|
||||
try {
|
||||
const env = this.getEnvironmentForRepo(repo, true)
|
||||
return await executeCommand(['git', '-C', fullPath, 'fetch', '--all', '--prune'], { env })
|
||||
} finally {
|
||||
await this.cleanupSSHForRepo()
|
||||
}
|
||||
}
|
||||
|
||||
async pull(repoId: number, database: Database): Promise<string> {
|
||||
@@ -320,9 +367,15 @@ export class GitService {
|
||||
}
|
||||
|
||||
const fullPath = path.resolve(repo.fullPath)
|
||||
const env = this.gitAuthService.getGitEnvironment(false)
|
||||
|
||||
return executeCommand(['git', '-C', fullPath, 'pull'], { env })
|
||||
await this.setupSSHIfNeeded(repo.repoUrl, database)
|
||||
|
||||
try {
|
||||
const env = this.getEnvironmentForRepo(repo, false)
|
||||
return await executeCommand(['git', '-C', fullPath, 'pull'], { env })
|
||||
} finally {
|
||||
await this.cleanupSSHForRepo()
|
||||
}
|
||||
}
|
||||
|
||||
async getBranches(repoId: number, database: Database): Promise<GitBranch[]> {
|
||||
@@ -383,7 +436,7 @@ export class GitService {
|
||||
|
||||
if (branch.current && (!branch.ahead || !branch.behind)) {
|
||||
try {
|
||||
const status = await this.getBranchStatusFromDb(repoId, database)
|
||||
const status = await this.getBranchStatus(repoId, database)
|
||||
branch.ahead = status.ahead
|
||||
branch.behind = status.behind
|
||||
} catch {
|
||||
@@ -470,7 +523,7 @@ export class GitService {
|
||||
}
|
||||
|
||||
private parsePorcelainOutput(output: string): GitFileStatus[] {
|
||||
const fileMap = new Map<string, GitFileStatus>()
|
||||
const files: GitFileStatus[] = []
|
||||
const lines = output.split('\n').filter(line => line.length > 0)
|
||||
|
||||
for (const line of lines) {
|
||||
@@ -487,41 +540,32 @@ export class GitService {
|
||||
filePath = filePath.substring(arrowIndex + 4)
|
||||
}
|
||||
|
||||
const existing = fileMap.get(filePath)
|
||||
|
||||
if (stagedStatus !== ' ' && stagedStatus !== '?') {
|
||||
const fileStatus: GitFileStatus = {
|
||||
files.push({
|
||||
path: filePath,
|
||||
status: this.parseStatusCode(stagedStatus),
|
||||
staged: true,
|
||||
...(oldPath && { oldPath })
|
||||
}
|
||||
fileMap.set(filePath, fileStatus)
|
||||
continue
|
||||
})
|
||||
}
|
||||
|
||||
if (unstagedStatus !== ' ' && unstagedStatus !== '?' && !existing) {
|
||||
const fileStatus: GitFileStatus = {
|
||||
if (unstagedStatus === '?' && stagedStatus === '?') {
|
||||
files.push({
|
||||
path: filePath,
|
||||
status: 'untracked',
|
||||
staged: false
|
||||
})
|
||||
} else if (unstagedStatus !== ' ') {
|
||||
files.push({
|
||||
path: filePath,
|
||||
status: this.parseStatusCode(unstagedStatus),
|
||||
staged: false,
|
||||
...(oldPath && { oldPath })
|
||||
}
|
||||
fileMap.set(filePath, fileStatus)
|
||||
continue
|
||||
}
|
||||
|
||||
if ((stagedStatus === '?' || unstagedStatus === '?') && !existing) {
|
||||
const fileStatus: GitFileStatus = {
|
||||
path: filePath,
|
||||
status: 'untracked',
|
||||
staged: false
|
||||
}
|
||||
fileMap.set(filePath, fileStatus)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(fileMap.values())
|
||||
return files
|
||||
}
|
||||
|
||||
private parseStatusCode(code: string): GitFileStatusType {
|
||||
@@ -543,20 +587,26 @@ export class GitService {
|
||||
}
|
||||
}
|
||||
|
||||
private async getFileStatus(repoPath: string, filePath: string, env: Record<string, string>): Promise<{ status: string }> {
|
||||
private async getFileStatus(repoPath: string, filePath: string, env: Record<string, string>): Promise<{ status: GitFileStatusType | 'clean' }> {
|
||||
try {
|
||||
const output = await executeCommand([
|
||||
'git', '-C', repoPath, 'status', '--porcelain', '--', filePath
|
||||
], { env, silent: true })
|
||||
|
||||
if (!output.trim()) {
|
||||
return { status: 'untracked' }
|
||||
return { status: 'clean' }
|
||||
}
|
||||
|
||||
const statusCode = output.trim().split(' ')[0]
|
||||
return { status: statusCode || 'untracked' }
|
||||
const parsed = this.parsePorcelainOutput(output)
|
||||
const firstFile = parsed[0]
|
||||
|
||||
if (!firstFile) {
|
||||
return { status: 'clean' }
|
||||
}
|
||||
|
||||
return { status: firstFile.status }
|
||||
} catch {
|
||||
return { status: 'untracked' }
|
||||
return { status: 'clean' }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -686,8 +736,4 @@ export class GitService {
|
||||
const args = ['git', '-C', fullPath, 'push', '--set-upstream', 'origin', branchName]
|
||||
return executeCommand(args, { env })
|
||||
}
|
||||
|
||||
private async getBranchStatusFromDb(repoId: number, database: Database): Promise<{ ahead: number; behind: number }> {
|
||||
return this.getBranchStatus(repoId, database)
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import { spawn, execSync } from 'child_process'
|
||||
import path from 'path'
|
||||
import { logger } from '../utils/logger'
|
||||
import { createGitEnv, createGitIdentityEnv, resolveGitIdentity } from '../utils/git-auth'
|
||||
import { createGitEnv, createGitIdentityEnv, resolveGitIdentity, type GitCredential } from '../utils/git-auth'
|
||||
import {
|
||||
buildSSHCommandWithKnownHosts,
|
||||
buildSSHCommandWithConfig,
|
||||
writePersistentSSHKey,
|
||||
stripKeyPassphrase,
|
||||
writeSSHConfig,
|
||||
generateSSHConfig,
|
||||
cleanupPersistentSSHKeys,
|
||||
parseSSHHost
|
||||
} from '../utils/ssh-key-manager'
|
||||
import { decryptSecret } from '../utils/crypto'
|
||||
import { SettingsService } from './settings'
|
||||
import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { GitCredential } from '../utils/git-auth'
|
||||
|
||||
const OPENCODE_SERVER_PORT = ENV.OPENCODE.PORT
|
||||
const OPENCODE_SERVER_HOST = ENV.OPENCODE.HOST
|
||||
@@ -115,6 +125,51 @@ class OpenCodeServerManager {
|
||||
logger.info(`OpenCode will use ?directory= parameter for session isolation`)
|
||||
|
||||
const gitEnv = createGitEnv(gitCredentials)
|
||||
const knownHostsPath = path.join(getWorkspacePath(), 'config', 'known_hosts')
|
||||
let gitSshCommand: string
|
||||
let sshConfigPath: string | null = null
|
||||
|
||||
const sshCredentials = gitCredentials.filter(cred => cred.type === 'ssh' && cred.sshPrivateKeyEncrypted)
|
||||
if (sshCredentials.length > 0) {
|
||||
logger.info(`Setting up ${sshCredentials.length} SSH credential(s) for OpenCode server`)
|
||||
|
||||
const sshConfigEntries: Array<{ hostname: string, port: string, keyPath: string }> = []
|
||||
|
||||
for (const cred of sshCredentials) {
|
||||
try {
|
||||
const { host, port } = parseSSHHost(cred.host)
|
||||
const privateKey = decryptSecret(cred.sshPrivateKeyEncrypted!)
|
||||
const keyPath = await writePersistentSSHKey(privateKey, cred.name)
|
||||
|
||||
if (cred.passphrase) {
|
||||
const passphrase = decryptSecret(cred.passphrase)
|
||||
stripKeyPassphrase(keyPath, passphrase)
|
||||
logger.info(`Stripped passphrase from SSH key for ${cred.name} (${host}:${port})`)
|
||||
} else {
|
||||
logger.info(`Setup SSH key for ${cred.name} (${host}:${port}): ${keyPath}`)
|
||||
}
|
||||
|
||||
sshConfigEntries.push({ hostname: host, port, keyPath })
|
||||
} catch (error) {
|
||||
logger.error(`Failed to setup SSH key for ${cred.name}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
if (sshConfigEntries.length > 0) {
|
||||
const sshConfigContent = generateSSHConfig(sshConfigEntries)
|
||||
sshConfigPath = path.join(getWorkspacePath(), 'config', 'ssh_config')
|
||||
await writeSSHConfig(sshConfigPath, sshConfigContent)
|
||||
gitSshCommand = buildSSHCommandWithConfig(sshConfigPath, knownHostsPath)
|
||||
logger.info(`OpenCode server SSH config written to ${sshConfigPath} with ${sshConfigEntries.length} host(s)`)
|
||||
} else {
|
||||
gitSshCommand = buildSSHCommandWithKnownHosts(knownHostsPath)
|
||||
logger.warn(`No SSH credentials could be set up, using default known_hosts only`)
|
||||
}
|
||||
} else {
|
||||
gitSshCommand = buildSSHCommandWithKnownHosts(knownHostsPath)
|
||||
}
|
||||
|
||||
logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`)
|
||||
|
||||
let stderrOutput = ''
|
||||
|
||||
@@ -129,6 +184,7 @@ class OpenCodeServerManager {
|
||||
...process.env,
|
||||
...gitEnv,
|
||||
...gitIdentityEnv,
|
||||
GIT_SSH_COMMAND: gitSshCommand,
|
||||
XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state'),
|
||||
XDG_CONFIG_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.config'),
|
||||
OPENCODE_CONFIG: OPENCODE_CONFIG_PATH,
|
||||
@@ -180,7 +236,7 @@ class OpenCodeServerManager {
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (!this.serverPid) return
|
||||
|
||||
|
||||
logger.info('Stopping OpenCode server')
|
||||
try {
|
||||
process.kill(this.serverPid, 'SIGTERM')
|
||||
@@ -192,9 +248,9 @@ class OpenCodeServerManager {
|
||||
logger.warn(`Failed to send SIGTERM to ${this.serverPid}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
|
||||
|
||||
try {
|
||||
process.kill(this.serverPid, 'SIGKILL')
|
||||
} catch (error) {
|
||||
@@ -205,9 +261,15 @@ class OpenCodeServerManager {
|
||||
logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this.serverPid = null
|
||||
this.isHealthy = false
|
||||
|
||||
try {
|
||||
await cleanupPersistentSSHKeys()
|
||||
} catch (error) {
|
||||
logger.warn('Failed to cleanup persistent SSH keys:', error)
|
||||
}
|
||||
}
|
||||
|
||||
async restart(): Promise<void> {
|
||||
|
||||
@@ -6,8 +6,9 @@ import type { Repo, CreateRepoInput } from '../types/repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import { isGitHubHttpsUrl } from '../utils/git-auth'
|
||||
import { isGitHubHttpsUrl, isSSHUrl } from '../utils/git-auth'
|
||||
import path from 'path'
|
||||
import { parseSSHHost } from '../utils/ssh-key-manager'
|
||||
|
||||
const GIT_CLONE_TIMEOUT = 300000
|
||||
|
||||
@@ -22,7 +23,11 @@ function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: str
|
||||
return new Error(`Repository not found: ${repoUrl}. Check the URL and ensure you have access to it.`)
|
||||
}
|
||||
|
||||
if (message.includes('permission denied') || (isGitHubHttpsUrl(repoUrl) && message.includes('fatal'))) {
|
||||
if (isSSHUrl(repoUrl) && message.includes('permission denied')) {
|
||||
return new Error(`Access denied to ${repoUrl}. Please add your SSH credentials in Settings > Git Credentials and ensure your SSH key has access to this repository.`)
|
||||
}
|
||||
|
||||
if (isGitHubHttpsUrl(repoUrl) && (message.includes('permission denied') || message.includes('fatal'))) {
|
||||
return new Error(`Access denied to ${repoUrl}. Please add your credentials in Settings > Git Credentials and ensure you have proper access.`)
|
||||
}
|
||||
|
||||
@@ -299,23 +304,30 @@ export async function cloneRepo(
|
||||
branch?: string,
|
||||
useWorktree: boolean = false
|
||||
): Promise<Repo> {
|
||||
const { url: normalizedRepoUrl, name: repoName } = normalizeRepoUrl(repoUrl)
|
||||
const isSSH = isSSHUrl(repoUrl)
|
||||
const preserveSSH = isSSH
|
||||
const hasSSHCredential = await gitAuthService.setupSSHForRepoUrl(repoUrl, database)
|
||||
|
||||
const { url: normalizedRepoUrl, name: repoName } = normalizeRepoUrl(repoUrl, preserveSSH)
|
||||
const baseRepoDirName = repoName
|
||||
const worktreeDirName = branch && useWorktree ? `${repoName}-${branch.replace(/[\\/]/g, '-')}` : repoName
|
||||
const localPath = worktreeDirName
|
||||
|
||||
|
||||
const existing = db.getRepoByUrlAndBranch(database, normalizedRepoUrl, branch)
|
||||
|
||||
|
||||
if (existing) {
|
||||
logger.info(`Repo branch already exists: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}`)
|
||||
if (hasSSHCredential) {
|
||||
await gitAuthService.cleanupSSHKey()
|
||||
}
|
||||
return existing
|
||||
}
|
||||
|
||||
|
||||
await ensureDirectoryExists(getReposPath())
|
||||
const baseRepoExists = await executeCommand(['bash', '-c', `test -d ${baseRepoDirName} && echo exists || echo missing`], path.resolve(getReposPath()))
|
||||
|
||||
|
||||
const shouldUseWorktree = useWorktree && branch && baseRepoExists.trim() === 'exists'
|
||||
|
||||
|
||||
const createRepoInput: CreateRepoInput = {
|
||||
repoUrl: normalizedRepoUrl,
|
||||
localPath,
|
||||
@@ -332,7 +344,10 @@ export async function cloneRepo(
|
||||
const repo = db.createRepo(database, createRepoInput)
|
||||
|
||||
try {
|
||||
const env = gitAuthService.getGitEnvironment()
|
||||
const env = {
|
||||
...gitAuthService.getGitEnvironment(),
|
||||
...(isSSH ? gitAuthService.getSSHEnvironment() : {})
|
||||
}
|
||||
|
||||
if (shouldUseWorktree) {
|
||||
logger.info(`Creating worktree for branch: ${branch}`)
|
||||
@@ -518,6 +533,8 @@ export async function cloneRepo(
|
||||
logger.error(`Failed to create repo: ${normalizedRepoUrl}${branch ? `#${branch}` : ''}`, error)
|
||||
db.deleteRepo(database, repo.id)
|
||||
throw error
|
||||
} finally {
|
||||
await gitAuthService.cleanupSSHKey()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -643,14 +660,26 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
|
||||
db.deleteRepo(database, repoId)
|
||||
}
|
||||
|
||||
function normalizeRepoUrl(url: string): { url: string; name: string } {
|
||||
function normalizeRepoUrl(url: string, preserveSSH: boolean = false): { url: string; name: string } {
|
||||
const sshMatch = url.match(/^git@([^:]+):(.+?)(?:\.git)?$/)
|
||||
if (sshMatch) {
|
||||
const [, host, pathPart] = sshMatch
|
||||
const path = pathPart ?? ''
|
||||
const repoName = path.split('/').pop() || `repo-${Date.now()}`
|
||||
return {
|
||||
url: `https://${host}/${path.replace(/\.git$/, '')}`,
|
||||
url: preserveSSH ? url : `https://${host}/${path.replace(/\.git$/, '')}`,
|
||||
name: repoName
|
||||
}
|
||||
}
|
||||
|
||||
if (url.startsWith('ssh://')) {
|
||||
const { host } = parseSSHHost(url)
|
||||
const pathParts = url.split(`${host}/`)
|
||||
const pathPart = pathParts[1] || ''
|
||||
const repoName = pathPart.replace(/\.git$/, '').split('/').pop() || `repo-${Date.now()}`
|
||||
|
||||
return {
|
||||
url: preserveSSH ? url : `https://${host}/${pathPart.replace(/\.git$/, '')}`,
|
||||
name: repoName
|
||||
}
|
||||
}
|
||||
|
||||
@@ -403,6 +403,22 @@ class SSEAggregator {
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
broadcastToAll(event: string, data: string): void {
|
||||
this.clients.forEach((client) => {
|
||||
try {
|
||||
client.callback(event, data)
|
||||
} catch { /* ignore broadcast errors */ }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const sseAggregator = SSEAggregator.getInstance()
|
||||
|
||||
export function broadcastSSHHostKeyRequest(data: Record<string, unknown>): void {
|
||||
const event = JSON.stringify({
|
||||
type: 'ssh.host-key-request',
|
||||
properties: data,
|
||||
})
|
||||
sseAggregator.broadcastToAll('message', event)
|
||||
}
|
||||
Reference in new issue
Block a user