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:
Chris Scott authored and GitHub committed 2026-02-08 00:06:44 -05:00
1 parent 3d5ee463d7
commit 414f39b809
54 files changed
+4051 -214

No files matched your search

+2 -2
View File
@@ -163,8 +163,8 @@ function migrateGitTokenToCredentials(db: Database): void {
continue
}
const { gitToken: _gitToken, ...rest } = parsed
void _gitToken
const { gitToken: _, ...rest } = parsed
void _
const migrated = {
...rest,
gitCredentials: [{
+11
View File
@@ -121,6 +121,17 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
CREATE INDEX IF NOT EXISTS idx_passkey_userId ON "passkey"(userId);
CREATE INDEX IF NOT EXISTS idx_passkey_credentialID ON "passkey"(credentialID);
CREATE TABLE IF NOT EXISTS trusted_ssh_hosts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
host TEXT NOT NULL UNIQUE,
key_type TEXT NOT NULL,
public_key TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_trusted_ssh_hosts_host ON trusted_ssh_hosts(host);
`)
runMigrations(db)
+2
View File
@@ -17,6 +17,7 @@ import { createProvidersRoutes } from './routes/providers'
import { createOAuthRoutes } from './routes/oauth'
import { createTitleRoutes } from './routes/title'
import { createSSERoutes } from './routes/sse'
import { createSSHRoutes } from './routes/ssh'
import { createNotificationRoutes } from './routes/notifications'
import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './routes/auth'
import { createAuth } from './auth'
@@ -241,6 +242,7 @@ protectedApi.route('/tts', createTTSRoutes(db))
protectedApi.route('/stt', createSTTRoutes(db))
protectedApi.route('/generate-title', createTitleRoutes())
protectedApi.route('/sse', createSSERoutes())
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
app.route('/api', protectedApi)
+5 -4
View File
@@ -111,18 +111,19 @@ export class AskpassHandler implements IPCHandler {
const settingsService = new SettingsService(this.database)
const settings = settingsService.getSettings('default')
const gitCredentials: GitCredential[] = settings.preferences.gitCredentials || []
logger.info(`Found ${gitCredentials.length} configured git credentials`)
const allCredentials = (settings.preferences.gitCredentials || []) as GitCredential[]
const gitCredentials = allCredentials.filter(cred => !cred.type || cred.type === 'pat')
logger.info(`Found ${gitCredentials.length} configured PAT credentials (${allCredentials.length} total)`)
for (const cred of gitCredentials) {
const normalizedCred = this.normalizeHostname(cred.host)
logger.debug(`Comparing: request='${normalizedRequest}' vs stored='${normalizedCred}' (raw: ${cred.host})`)
if (normalizedCred === normalizedRequest) {
logger.info(`Found matching credential '${cred.name}' for ${hostname}`)
logger.info(`Found matching PAT credential '${cred.name}' for ${hostname}`)
return {
username: cred.username || this.getDefaultUsername(cred.host),
password: cred.token,
password: cred.token || '',
}
}
}
+4
View File
@@ -33,6 +33,10 @@ export class IPCServer {
this.handlers.set(`/${name}`, handler)
}
getHandler(name: string): IPCHandler | undefined {
return this.handlers.get(`/${name}`)
}
getEnv(): Record<string, string> {
return { VSCODE_GIT_IPC_HANDLE: this.ipcHandlePath }
}
+54
View File
@@ -0,0 +1,54 @@
import type { IPCServer, IPCHandler } from './ipcServer'
import { logger } from '../utils/logger'
interface PassphraseResponse {
type: 'passphrase-response'
passphrase: string
}
export class PassphraseHandler implements IPCHandler {
private resolveMap = new Map<string, { resolve: (passphrase: string) => void; reject: (error: Error) => void }>()
constructor(ipcServer: IPCServer | undefined) {
if (ipcServer) {
ipcServer.registerHandler('passphrase', this)
logger.info('PassphraseHandler registered with IPC server')
} else {
logger.warn('PassphraseHandler: No IPC server provided, passphrase prompts will fail')
}
}
async handle(request: PassphraseResponse): Promise<string> {
if (request.type === 'passphrase-response') {
const pending = this.resolveMap.get('default')
if (pending) {
pending.resolve(request.passphrase)
this.resolveMap.delete('default')
}
return 'ack'
}
return ''
}
requestPassphrase(credentialName: string, host: string): Promise<string> {
return new Promise((resolve, reject) => {
const requestId = `default`
this.resolveMap.set(requestId, { resolve, reject })
logger.info(`Requesting passphrase for ${credentialName} (${host})`)
setTimeout(() => {
if (this.resolveMap.has(requestId)) {
this.resolveMap.delete(requestId)
reject(new Error('Passphrase request timed out'))
}
}, 120000)
})
}
cleanup(): void {
this.resolveMap.forEach(({ reject }) => reject(new Error('Passphrase handler closed')))
this.resolveMap.clear()
}
}
+226
View File
@@ -0,0 +1,226 @@
import * as path from 'path'
import * as fs from 'fs/promises'
import * as crypto from 'crypto'
import type { IPCHandler } from './ipcServer'
import type { Database } from 'bun:sqlite'
import { logger } from '../utils/logger'
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'
interface SSHHostKeyRequest {
id: string
host: string
ip: string
keyType: string
fingerprint: string
timestamp: number
isKeyChanged: boolean
}
export class SSHHostKeyHandler implements IPCHandler {
private pendingRequests = new Map<string, {
request: SSHHostKeyRequest
resolve: (value: boolean) => void
timeout: ReturnType<typeof setTimeout>
}>()
private readonly timeoutMs: number
private knownHostsPath: string
private database: Database
constructor(database: Database, timeoutMs: number = 120_000) {
this.database = database
this.timeoutMs = timeoutMs
const configDir = path.join(getWorkspacePath(), 'config')
this.knownHostsPath = path.join(configDir, 'known_hosts')
this.ensureKnownHostsFile()
logger.info(`SSHHostKeyHandler initialized with timeout=${timeoutMs}ms, known_hosts=${this.knownHostsPath}`)
}
private async ensureKnownHostsFile(): Promise<void> {
try {
const configDir = path.join(getWorkspacePath(), 'config')
await fs.mkdir(configDir, { recursive: true })
try {
await fs.access(this.knownHostsPath)
} catch {
await fs.writeFile(this.knownHostsPath, '', { mode: 0o600 })
logger.info(`Created known_hosts file at ${this.knownHostsPath}`)
}
} catch (error) {
logger.error('Failed to ensure known_hosts file:', error)
}
}
async verifyHostKeyBeforeOperation(repoUrl: string): Promise<boolean> {
const { host, port } = parseSSHHost(repoUrl)
const hostPort = normalizeHostPort(host, port)
const trustedHost = this.getTrustedHost(hostPort)
if (trustedHost) {
logger.info(`Host ${hostPort} already trusted, skipping verification`)
return true
}
try {
const publicKey = await this.fetchHostPublicKey(host, port)
logger.info(`Fetched public key for ${hostPort}`)
const parts = publicKey.split(' ')
const keyType = parts[1] || 'UNKNOWN'
const requestId = crypto.randomBytes(16).toString('hex')
const hostKeyRequest: SSHHostKeyRequest = {
id: requestId,
host: hostPort,
ip: '',
keyType,
fingerprint: publicKey,
timestamp: Date.now(),
isKeyChanged: false
}
logger.info(`Broadcasting SSH host key request: ${requestId} for host=${hostPort}`)
broadcastSSHHostKeyRequest({ ...hostKeyRequest, requestId, action: 'verify' })
return new Promise<boolean>((resolve) => {
const timeout = setTimeout(() => {
logger.info(`SSH host key request timed out: ${requestId}, rejecting connection`)
this.pendingRequests.delete(requestId)
resolve(false)
}, this.timeoutMs)
this.pendingRequests.set(requestId, { request: hostKeyRequest, resolve, timeout })
})
} catch (error) {
logger.warn(`Failed to fetch host key for ${hostPort}, rejecting connection:`, (error as Error).message)
return false
}
}
private async fetchHostPublicKey(host: string, port?: string): Promise<string> {
const portArgs = port ? ['-p', port] : []
const output = await executeCommand(['ssh-keyscan', '-t', 'ed25519,rsa,ecdsa', ...portArgs, host], { silent: true })
const bracketedHost = port && port !== '22' ? `[${host}]:${port}` : host
const lines = output.trim().split('\n')
for (const line of lines) {
if (line.startsWith(host) || line.startsWith(bracketedHost)) {
return line
}
}
throw new Error('No valid host keys found')
}
async handle(request: unknown): Promise<unknown> {
const response = request as { requestId: string; response: 'accept' | 'reject' }
return await this.respond(response)
}
async respond(response: { requestId: string; response: 'accept' | 'reject' }): Promise<{ success: boolean; error?: string }> {
const pending = this.pendingRequests.get(response.requestId)
if (!pending) {
return { success: false, error: 'Request not found or expired' }
}
clearTimeout(pending.timeout)
this.pendingRequests.delete(response.requestId)
if (response.response === 'accept') {
await this.addToKnownHosts(pending.request.host, pending.request.fingerprint)
this.saveTrustedHost(pending.request.host, pending.request.fingerprint)
logger.info(`Accepted SSH host key for ${pending.request.host}`)
} else {
logger.info(`Rejected SSH host key for ${pending.request.host}`)
}
pending.resolve(response.response === 'accept')
return { success: true }
}
private async addToKnownHosts(host: string, publicKey: string): Promise<void> {
try {
await fs.appendFile(this.knownHostsPath, publicKey + '\n')
logger.info(`Added host to known_hosts: ${host}`)
} catch (error) {
logger.error(`Failed to add host to known_hosts: ${error}`)
}
}
private async loadFromDatabaseToKnownHosts(): Promise<void> {
try {
const hosts = this.database.prepare('SELECT * FROM trusted_ssh_hosts').all() as Array<{
id: number
host: string
key_type: string
public_key: string
created_at: number
updated_at: number
}>
const entries = hosts.map(h => h.public_key).join('\n')
await fs.writeFile(this.knownHostsPath, entries + '\n', { mode: 0o600 })
logger.info(`Loaded ${hosts.length} trusted hosts from database to known_hosts`)
} catch (error) {
logger.error('Failed to load trusted hosts from database:', error)
}
}
private getTrustedHost(host: string): { key_type: string; public_key: string } | null {
try {
const result = this.database.prepare('SELECT key_type, public_key FROM trusted_ssh_hosts WHERE host = ?').get(host) as {
key_type: string
public_key: string
} | undefined
return result || null
} catch (error) {
logger.error(`Failed to get trusted host ${host}:`, error)
return null
}
}
private saveTrustedHost(host: string, publicKey: string): void {
try {
const parts = publicKey.split(' ')
const keyType = parts[1] || 'UNKNOWN'
const now = Date.now()
const existing = this.getTrustedHost(host)
if (existing) {
this.database.prepare('UPDATE trusted_ssh_hosts SET key_type = ?, public_key = ?, updated_at = ? WHERE host = ?')
.run(keyType, publicKey, now, host)
logger.info(`Updated trusted host in database: ${host}`)
} else {
this.database.prepare('INSERT INTO trusted_ssh_hosts (host, key_type, public_key, created_at, updated_at) VALUES (?, ?, ?, ?, ?)')
.run(host, keyType, publicKey, now, now)
logger.info(`Saved new trusted host to database: ${host}`)
}
} catch (error) {
logger.error(`Failed to save trusted host ${host}:`, error)
}
}
async initialize(): Promise<void> {
await this.ensureKnownHostsFile()
await this.loadFromDatabaseToKnownHosts()
logger.info('SSHHostKeyHandler initialized with known_hosts from database')
}
getKnownHostsPath(): string {
return this.knownHostsPath
}
getEnv(): Record<string, string> {
return {
KNOWN_HOSTS_PATH: this.knownHostsPath
}
}
getPendingCount(): number {
return this.pendingRequests.size
}
}
export function createSSHHostKeyHandler(database: Database, timeoutMs?: number): SSHHostKeyHandler {
return new SSHHostKeyHandler(database, timeoutMs)
}
+1 -1
View File
@@ -43,7 +43,7 @@ export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthS
const statuses = await Promise.all(
repoIds.map(async (id) => {
try {
const status = await git.getStatus(id, database)
const status = await git.getStatus(id, database)
return [id, status]
} catch (error: unknown) {
logger.error(`Failed to get git status for repo ${id}:`, error)
+179 -8
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono'
import { z } from 'zod'
import { execSync } from 'child_process'
import { execSync, spawnSync } from 'child_process'
import { existsSync } from 'fs'
import { resolve, dirname } from 'path'
import type { Database } from 'bun:sqlite'
@@ -15,6 +15,8 @@ import {
import { logger } from '../utils/logger'
import { opencodeServerManager } from '../services/opencode-single-server'
import { DEFAULT_AGENTS_MD } from '../constants'
import { validateSSHPrivateKey } from '../utils/ssh-validation'
import { encryptSecret } from '../utils/crypto'
function compareVersions(v1: string, v2: string): number {
const parts1 = v1.split('.').map(s => Number(s))
@@ -50,22 +52,44 @@ function getOpenCodeInstallMethod(): string {
return 'curl'
}
function execWithTimeout(command: string, timeoutMs: number): { output: string; timedOut: boolean } {
function execWithTimeout(command: string, timeoutMs: number, env?: Record<string, string>): { output: string; timedOut: boolean } {
try {
const output = execSync(command, {
encoding: 'utf8',
timeout: timeoutMs,
killSignal: 'SIGKILL'
killSignal: 'SIGKILL',
env: env ? { ...process.env, ...env } : undefined
})
return { output, timedOut: false }
} catch (error) {
if (error && typeof error === 'object' && 'status' in error && (error as { status: number }).status === null) {
return { output: '', timedOut: true }
}
if (error && typeof error === 'object' && ('stdout' in error || 'stderr' in error)) {
const stdout = (error as { stdout?: string }).stdout || ''
const stderr = (error as { stderr?: string }).stderr || ''
return { output: stdout + stderr, timedOut: false }
}
throw error
}
}
function spawnWithTimeout(args: string[], timeoutMs: number, env?: Record<string, string>): { output: string; timedOut: boolean } {
const result = spawnSync(args[0]!, args.slice(1), {
encoding: 'utf8',
timeout: timeoutMs,
killSignal: 'SIGKILL',
env: env ? { ...process.env, ...env } : undefined
})
if (result.signal === 'SIGKILL' || result.error?.message?.includes('TIMEOUT')) {
return { output: '', timedOut: true }
}
const output = (result.stdout || '') + (result.stderr || '')
return { output, timedOut: false }
}
const UpdateSettingsSchema = z.object({
preferences: UserPreferencesSchema.partial(),
})
@@ -100,6 +124,12 @@ const ConnectMcpDirectorySchema = z.object({
directory: z.string().min(1),
})
const TestSSHConnectionSchema = z.object({
host: z.string().min(1),
sshPrivateKey: z.string().min(1),
passphrase: z.string().optional(),
})
async function extractOpenCodeError(response: Response, defaultError: string): Promise<string> {
const errorObj = await response.json().catch(() => null)
@@ -128,18 +158,42 @@ export function createSettingsRoutes(db: Database) {
const userId = c.req.query('userId') || 'default'
const body = await c.req.json()
const validated = UpdateSettingsSchema.parse(body)
if (validated.preferences.gitCredentials) {
const validations = await Promise.all(
validated.preferences.gitCredentials.map(async (cred: Record<string, unknown>) => {
if (cred.type === 'ssh' && cred.sshPrivateKey) {
const validation = await validateSSHPrivateKey(cred.sshPrivateKey as string)
if (!validation.valid) {
throw new Error(`Invalid SSH key for credential '${cred.name}': ${validation.error}`)
}
const result: Record<string, unknown> = {
...cred,
sshPrivateKeyEncrypted: encryptSecret(cred.sshPrivateKey as string),
hasPassphrase: validation.hasPassphrase,
passphrase: cred.passphrase ? encryptSecret(cred.passphrase as string) : undefined,
}
delete result.sshPrivateKey
return result
}
return cred
})
)
validated.preferences.gitCredentials = validations
}
const currentSettings = settingsService.getSettings(userId)
const settings = settingsService.updateSettings(validated.preferences, userId)
let serverRestarted = false
const credentialsChanged = validated.preferences.gitCredentials !== undefined &&
JSON.stringify(currentSettings.preferences.gitCredentials || []) !== JSON.stringify(validated.preferences.gitCredentials)
const identityChanged = validated.preferences.gitIdentity !== undefined &&
JSON.stringify(currentSettings.preferences.gitIdentity || {}) !== JSON.stringify(validated.preferences.gitIdentity)
let reloadError: string | undefined
if (credentialsChanged || identityChanged) {
const changeType = [credentialsChanged && 'credentials', identityChanged && 'identity'].filter(Boolean).join(' and ')
@@ -156,6 +210,9 @@ export function createSettingsRoutes(db: Database) {
return c.json({ ...settings, serverRestarted, reloadError })
} catch (error) {
logger.error('Failed to update settings:', error)
if (error instanceof Error && error.message.startsWith('Invalid SSH key')) {
return c.json({ error: error.message }, 400)
}
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid settings data', details: error.issues }, 400)
}
@@ -775,6 +832,120 @@ export function createSettingsRoutes(db: Database) {
}
})
app.post('/test-ssh', async (c) => {
try {
const body = await c.req.json()
const { host, sshPrivateKey, passphrase } = TestSSHConnectionSchema.parse(body)
logger.info(`Testing SSH connection to ${host}`)
const validation = await validateSSHPrivateKey(sshPrivateKey)
if (!validation.valid) {
return c.json({
success: false,
message: validation.error || 'Invalid SSH key'
}, 400)
}
const { writeTemporarySSHKey, cleanupSSHKey, parseSSHHost } = await import('../utils/ssh-key-manager')
let keyPath: string | null = null
try {
keyPath = await writeTemporarySSHKey(sshPrivateKey, 'test')
const { user, host: sshHost, port } = parseSSHHost(host)
const sshArgs = [
'-T',
'-i', keyPath,
'-o', 'IdentitiesOnly=yes',
'-o', 'PasswordAuthentication=no',
'-o', 'StrictHostKeyChecking=accept-new',
'-o', 'UserKnownHostsFile=/dev/null',
]
if (port && port !== '22') {
sshArgs.push('-p', port)
}
sshArgs.push(`${user}@${sshHost}`)
let executable = 'ssh'
const env: Record<string, string> = {}
if (passphrase) {
executable = 'sshpass'
sshArgs.unshift('-e', 'ssh')
env.SSHPASS = passphrase
}
const { output, timedOut } = spawnWithTimeout([executable, ...sshArgs], 30000, env)
if (timedOut) {
logger.warn(`SSH connection test to ${host} timed out`)
return c.json({
success: false,
message: 'Connection timed out. This may indicate a network issue or an incorrect host.'
})
}
const outputStr = String(output)
if (outputStr.includes('Permission denied') || outputStr.includes('Access denied')) {
return c.json({
success: false,
message: 'Permission denied. The SSH key may not be authorized on this host, or the passphrase is incorrect.'
})
}
if (outputStr.includes('Could not resolve hostname') || outputStr.includes('Name or service not known')) {
return c.json({
success: false,
message: 'Could not resolve hostname. Please check that the host is correct and accessible.'
})
}
if (outputStr.includes('Connection refused') || outputStr.includes('Connection timed out')) {
return c.json({
success: false,
message: 'Connection refused or timed out. The host may be down or not accepting SSH connections.'
})
}
const authenticated = outputStr.includes('successfully authenticated') ||
outputStr.includes('You\'ve successfully authenticated') ||
outputStr.includes('Welcome to')
if (authenticated) {
logger.info(`SSH connection test to ${host} succeeded`)
return c.json({
success: true,
message: `Successfully connected to ${host}`
})
}
logger.warn(`SSH connection test to ${host} returned ambiguous output: ${outputStr}`)
return c.json({
success: false,
message: `Authentication failed. The key may not be authorized on this host. Details: ${outputStr.trim().substring(0, 200)}`
})
} finally {
if (keyPath) {
await cleanupSSHKey(keyPath)
}
}
} catch (error) {
logger.error('Failed to test SSH connection:', error)
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
}
return c.json({
success: false,
message: error instanceof Error ? error.message : 'Failed to test SSH connection'
}, 500)
}
})
// MCP directory-aware endpoints
app.post('/mcp/:name/connectdirectory', async (c) => {
try {
+56
View File
@@ -0,0 +1,56 @@
import { Hono } from 'hono'
import { z } from 'zod'
import { logger } from '../utils/logger'
import { GitAuthService } from '../services/git-auth'
const SSHHostKeyResponseSchema = z.object({
requestId: z.string(),
response: z.enum(['accept', 'reject'])
})
interface SSHHostKeyResponse {
success: boolean
error?: string
}
export function createSSHRoutes(gitAuthService: GitAuthService) {
const app = new Hono()
app.post('/host-key/respond', async (c) => {
try {
const body = await c.req.json()
const validated = SSHHostKeyResponseSchema.parse(body)
const handler = gitAuthService.sshHostKeyHandler
if (!handler) {
return c.json<SSHHostKeyResponse>({ success: false, error: 'SSH host key handler not found' }, 404)
}
const result = await handler.respond(validated)
return c.json<SSHHostKeyResponse>(result)
} catch (error) {
logger.error('Error responding to SSH host key request:', error)
if (error instanceof z.ZodError) {
return c.json<SSHHostKeyResponse>({ success: false, error: 'Invalid request body' }, 400)
}
return c.json<SSHHostKeyResponse>({ success: false, error: 'Internal server error' }, 500)
}
})
app.get('/host-key/status', (c) => {
try {
const handler = gitAuthService.sshHostKeyHandler
if (!handler) {
return c.json({ success: false, error: 'SSH host key handler not found' }, 404)
}
const pendingCount = handler.getPendingCount()
return c.json({ success: true, pendingCount })
} catch (error) {
logger.error('Error getting SSH host key status:', error)
return c.json({ success: false, error: 'Internal server error' }, 500)
}
})
return app
}
+126
View File
@@ -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> {
+93 -47
View File
@@ -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)
}
}
+68 -6
View File
@@ -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> {
+40 -11
View File
@@ -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
}
}
+16
View File
@@ -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)
}
+1 -1
View File
@@ -36,7 +36,7 @@ export interface FileDiffResponse {
export interface GitDiffOptions {
showContext?: number
ignoreWhitespace?: boolean
unified?: boolean
unified?: number
}
export interface GitBranch {
+46
View File
@@ -0,0 +1,46 @@
import { scryptSync, createCipheriv, createDecipheriv, randomBytes } from 'crypto'
import { ENV } from '@opencode-manager/shared/config/env'
const ENCRYPTION_KEY_SALT = Buffer.from('opencode-ssh-key-salt-v1', 'utf8')
const IV_LENGTH = 16
const KEY_LENGTH = 32
function deriveKey(): Buffer {
const secret = ENV.AUTH.SECRET || 'default-secret-do-not-use-in-production'
return scryptSync(secret, ENCRYPTION_KEY_SALT, KEY_LENGTH)
}
export function encryptSecret(plaintext: string): string {
const key = deriveKey()
const iv = randomBytes(IV_LENGTH)
const cipher = createCipheriv('aes-256-gcm', key, iv)
const updateResult = cipher.update(plaintext, 'utf8')
const encrypted = Buffer.concat([updateResult, cipher.final()])
const authTag = cipher.getAuthTag()
const combined = Buffer.concat([iv, authTag, encrypted])
return combined.toString('base64')
}
export function decryptSecret(encrypted: string): string {
const combined = Buffer.from(encrypted, 'base64')
if (combined.length < IV_LENGTH + 16) {
throw new Error('Invalid encrypted data format')
}
const iv = combined.slice(0, IV_LENGTH)
const authTag = combined.slice(IV_LENGTH, IV_LENGTH + 16)
const ciphertext = combined.slice(IV_LENGTH + 16)
const key = deriveKey()
const decipher = createDecipheriv('aes-256-gcm', key, iv)
decipher.setAuthTag(authTag)
const updateResult = decipher.update(ciphertext)
const decrypted = Buffer.concat([updateResult, decipher.final()])
return decrypted.toString('utf8')
}
+68 -3
View File
@@ -1,8 +1,13 @@
export interface GitCredential {
name: string
host: string
token: string
type: 'pat' | 'ssh'
token?: string
sshPrivateKey?: string
sshPrivateKeyEncrypted?: string
hasPassphrase?: boolean
username?: string
passphrase?: string
}
export function isGitHubHttpsUrl(repoUrl: string): boolean {
@@ -31,6 +36,29 @@ export function getDefaultUsername(host: string): string {
}
}
export function isSSHUrl(url: string): boolean {
return url.startsWith('git@') || url.startsWith('ssh://')
}
export function extractHostFromSSHUrl(url: string): string | null {
if (url.startsWith('git@')) {
const match = url.match(/^git@([^:]+):/)
const host = match?.[1]
return host || null
}
if (url.startsWith('ssh://')) {
try {
const parsed = new URL(url)
const hostname = parsed.hostname ?? ''
const port = parsed.port ?? ''
return port ? `${hostname}:${port}` : parsed.hostname || null
} catch {
return null
}
}
return null
}
export function normalizeHost(host: string): string {
if (!host.endsWith('/')) {
return `${host}/`
@@ -70,7 +98,7 @@ export function createGitEnv(credentials: GitCredential[]): Record<string, strin
}
export function createGitHubGitEnv(gitToken: string): Record<string, string> {
return createGitEnv([{ name: 'GitHub', host: 'https://github.com/', token: gitToken }])
return createGitEnv([{ name: 'GitHub', host: 'https://github.com/', token: gitToken, type: 'pat' }])
}
export function findGitHubCredential(credentials: GitCredential[]): GitCredential | null {
@@ -97,6 +125,43 @@ export function getCredentialForHost(credentials: GitCredential[], host: string)
})
}
export function getSSHCredentialsForHost(credentials: GitCredential[], host: string): GitCredential[] {
return credentials.filter(cred => {
if (cred.type !== 'ssh') return false
const credHost = cred.host.toLowerCase()
const targetHost = host.toLowerCase()
if (credHost === targetHost) {
return true
}
try {
const parsedCredHost = new URL(credHost)
const credHostname = parsedCredHost.hostname.toLowerCase()
const credPort = parsedCredHost.port || (parsedCredHost.protocol.includes('ssh') ? 22 : null)
const normalizedCredHost = credPort ? `${credHostname}:${credPort}` : credHostname
const parsedTargetHost = new URL(`ssh://dummy@${targetHost}`)
const targetHostname = parsedTargetHost.hostname.toLowerCase()
const targetPort = parsedTargetHost.port || 22
const normalizedTargetHost = targetPort !== '' ? `${targetHostname}:${targetPort}` : targetHostname
return normalizedCredHost === normalizedTargetHost
} catch {
if (credHost.includes(':')) {
const [credHostname, credPort] = credHost.split(':')
if (targetHost.includes(':')) {
const [targetHostname, targetPort] = targetHost.split(':')
return credHostname === targetHostname && credPort === targetPort
}
return credHostname === targetHost
}
return credHost === targetHost
}
})
}
export interface GitHubUserInfo {
name: string | null
email: string
@@ -117,7 +182,7 @@ export async function resolveGitIdentity(
}
const githubCred = findGitHubCredential(credentials)
if (githubCred) {
if (githubCred && githubCred.token) {
const githubUser = await fetchGitHubUserInfo(githubCred.token)
if (githubUser) {
return {
+2
View File
@@ -36,6 +36,8 @@ export async function executeCommand(
logger.info(` GIT_ASKPASS: ${effectiveEnv.GIT_ASKPASS || '(not set)'}`)
logger.info(` VSCODE_GIT_IPC_HANDLE: ${effectiveEnv.VSCODE_GIT_IPC_HANDLE || '(not set)'}`)
logger.info(` GIT_TERMINAL_PROMPT: ${effectiveEnv.GIT_TERMINAL_PROMPT || '(not set)'}`)
logger.info(` GIT_SSH_COMMAND: ${effectiveEnv.GIT_SSH_COMMAND || '(not set)'}`)
logger.info(` VSCODE_GIT_SSH_HOST_KEY: ${effectiveEnv.VSCODE_GIT_SSH_HOST_KEY || '(not set)'}`)
}
const proc: ChildProcess = spawn(command || '', cmdArgs, {
+270
View File
@@ -0,0 +1,270 @@
/* eslint-disable no-empty */
import { promises as fs } from 'fs'
import { execFileSync } from 'child_process'
import { randomBytes } from 'crypto'
import { join } from 'path'
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
const SSH_KEYS_DIR = join(getWorkspacePath(), '.ssh-keys')
async function ensureSSHKeysDir(): Promise<void> {
try {
await fs.access(SSH_KEYS_DIR)
} catch {
await fs.mkdir(SSH_KEYS_DIR, { mode: 0o700, recursive: true })
}
}
async function validateSSHKey(keyPath: string): Promise<boolean> {
try {
const stats = await fs.stat(keyPath)
const mode = stats.mode & 0o777
if (mode !== 0o600) {
await fs.chmod(keyPath, 0o600)
}
const keyContent = await fs.readFile(keyPath, 'utf-8')
const trimmedKey = keyContent.trim()
if (!trimmedKey) {
return false
}
const keyLines = trimmedKey.split('\n')
const firstLine = keyLines[0]
if (!firstLine) {
return false
}
if (firstLine.startsWith('-----BEGIN')) {
return true
}
if (firstLine.match(/^(ssh-rsa|ssh-ed25519|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521|ssh-dss)\s+/)) {
return true
}
return false
} catch {
return false
}
}
export async function writeTemporarySSHKey(keyContent: string, identifier: string): Promise<string> {
await ensureSSHKeysDir()
const randomSuffix = randomBytes(8).toString('hex')
const fileName = `key-${identifier}-${randomSuffix}`
const keyPath = join(SSH_KEYS_DIR, fileName)
await fs.writeFile(keyPath, keyContent.trim() + '\n', { mode: 0o600 })
const isValid = await validateSSHKey(keyPath)
if (!isValid) {
await fs.unlink(keyPath).catch(() => {})
throw new Error('Invalid SSH key format')
}
return keyPath
}
export async function cleanupSSHKey(keyPath: string): Promise<void> {
try {
await fs.unlink(keyPath).catch(() => {})
} catch {
}
}
export interface SSHCommandResult {
command: string
env?: Record<string, string>
}
export function buildSSHCommand(keyPath: string, passphrase?: string, knownHostsPath?: string, port?: string): SSHCommandResult {
const knownHostsOption = knownHostsPath ? `-o UserKnownHostsFile="${knownHostsPath}" -o StrictHostKeyChecking=accept-new` : '-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/dev/null'
const portOption = port && port !== '22' ? ` -p ${port}` : ''
const baseCommand = `ssh -T -i "${keyPath}" -o IdentitiesOnly=yes -o PasswordAuthentication=no ${knownHostsOption}${portOption}`
if (passphrase) {
return {
command: `sshpass -e ${baseCommand}`,
env: { SSHPASS: passphrase }
}
}
return { command: baseCommand }
}
export function buildSSHCommandWithKnownHosts(knownHostsPath: string, port?: string): string {
const portOption = port && port !== '22' ? ` -p ${port}` : ''
return `ssh -T -o UserKnownHostsFile="${knownHostsPath}" -o StrictHostKeyChecking=accept-new -o PasswordAuthentication=no${portOption}`
}
export async function writePersistentSSHKey(keyContent: string, identifier: string): Promise<string> {
await ensureSSHKeysDir()
const fileName = `persistent-${identifier}`
const keyPath = join(SSH_KEYS_DIR, fileName)
await fs.writeFile(keyPath, keyContent.trim() + '\n', { mode: 0o600 })
const isValid = await validateSSHKey(keyPath)
if (!isValid) {
await fs.unlink(keyPath).catch(() => {})
throw new Error('Invalid SSH key format')
}
return keyPath
}
export function buildSSHCommandWithConfig(configPath: string, knownHostsPath: string): string {
return `ssh -T -F "${configPath}" -o UserKnownHostsFile="${knownHostsPath}" -o StrictHostKeyChecking=accept-new -o PasswordAuthentication=no`
}
export function stripKeyPassphrase(keyPath: string, passphrase: string): void {
execFileSync('ssh-keygen', ['-p', '-P', passphrase, '-N', '', '-f', keyPath], { stdio: 'ignore' })
}
export interface SSHConfigEntry {
hostname: string
port: string
keyPath: string
}
export function generateSSHConfig(entries: SSHConfigEntry[]): string {
const lines: string[] = []
for (const entry of entries) {
lines.push(`Host ${entry.hostname}`)
lines.push(` IdentityFile "${entry.keyPath}"`)
lines.push(' IdentitiesOnly yes')
if (entry.port !== '22') {
lines.push(` Port ${entry.port}`)
}
lines.push('')
}
return lines.join('\n')
}
export async function writeSSHConfig(configPath: string, configContent: string): Promise<void> {
const dir = join(getWorkspacePath(), 'config')
try {
await fs.access(dir)
} catch {
await fs.mkdir(dir, { mode: 0o700, recursive: true })
}
await fs.writeFile(configPath, configContent, { mode: 0o600 })
}
export async function cleanupAllSSHKeys(): Promise<void> {
try {
await fs.rm(SSH_KEYS_DIR, { recursive: true, force: true })
} catch {
}
}
export async function cleanupPersistentSSHKeys(): Promise<void> {
await ensureSSHKeysDir()
try {
const files = await fs.readdir(SSH_KEYS_DIR)
const persistentFiles = files.filter(f => f.startsWith('persistent-'))
await Promise.all(
persistentFiles.map(f => fs.unlink(join(SSH_KEYS_DIR, f)).catch(() => {}))
)
} catch {
}
try {
const configPath = join(getWorkspacePath(), 'config', 'ssh_config')
await fs.unlink(configPath)
} catch {
}
}
export interface SSHConnectionInfo {
user: string
host: string
port: string
}
export function parseSSHHost(input: string): SSHConnectionInfo {
const defaultUser = 'git'
const defaultPort = '22'
if (input.startsWith('ssh://')) {
try {
const parsed = new URL(input)
return {
user: parsed.username || defaultUser,
host: parsed.hostname || '',
port: parsed.port || defaultPort
}
} catch {
}
}
const cleaned = input.replace(/^[a-z]+:\/\//i, '')
let user = defaultUser
let host = cleaned
let port = defaultPort
if (cleaned.includes('@')) {
const atIndex = cleaned.indexOf('@')
user = cleaned.substring(0, atIndex)
host = cleaned.substring(atIndex + 1)
}
if (host.includes(':')) {
const colonIndex = host.lastIndexOf(':')
const afterColon = host.substring(colonIndex + 1)
if (afterColon.includes('/')) {
const hostPart = host.split(':')[0]
if (hostPart) {
host = hostPart
}
} else {
const portNum = parseInt(afterColon, 10)
if (!isNaN(portNum) && portNum > 0 && portNum <= 65535) {
port = afterColon
const hostPart = host.substring(0, colonIndex)
if (hostPart) {
host = hostPart
}
} else {
const hostPart = host.split(':')[0]
if (hostPart) {
host = hostPart
}
}
}
}
return { user, host, port }
}
export function normalizeHostPort(host: string, port?: string): string {
if (port && port !== '22') {
return `${host}:${port}`
}
return host
}
export function parseHostPort(hostPort: string): { host: string; port: string } {
if (hostPort.includes(':')) {
const colonIndex = hostPort.lastIndexOf(':')
const host = hostPort.substring(0, colonIndex)
const port = hostPort.substring(colonIndex + 1)
return { host, port }
}
return { host: hostPort, port: '22' }
}
+48
View File
@@ -0,0 +1,48 @@
import { promises as fs } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { executeCommand } from './process'
async function removeFile(filePath: string): Promise<void> {
await fs.unlink(filePath).catch(() => {})
}
export async function validateSSHPrivateKey(key: string): Promise<{ valid: boolean; hasPassphrase: boolean; error?: string }> {
if (!key || typeof key !== 'string') {
return { valid: false, hasPassphrase: false, error: 'SSH key is required' }
}
const trimmedKey = key.trim()
if (!trimmedKey) {
return { valid: false, hasPassphrase: false, error: 'SSH key cannot be empty' }
}
let tempKeyPath: string | null = null
try {
tempKeyPath = join(tmpdir(), `temp-ssh-key-${Date.now()}-${Math.random().toString(36).slice(2)}`)
await fs.writeFile(tempKeyPath, trimmedKey + '\n', { mode: 0o600 })
try {
await executeCommand(['ssh-keygen', '-y', '-P', '', '-f', tempKeyPath], { silent: true })
return { valid: true, hasPassphrase: false }
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
const passphrasePatterns = ['incorrect passphrase', 'bad passphrase', 'passphrase failed']
const isPassphraseError = passphrasePatterns.some(pattern => errorMessage.toLowerCase().includes(pattern))
if (isPassphraseError) {
return { valid: true, hasPassphrase: true }
}
throw error
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
return { valid: false, hasPassphrase: false, error: `Invalid SSH key: ${errorMessage}` }
} finally {
if (tempKeyPath) {
await removeFile(tempKeyPath)
}
}
}