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
@@ -0,0 +1,4 @@
|
||||
NODE_ENV=test
|
||||
PORT=3001
|
||||
DATABASE_PATH=:memory:
|
||||
AUTH_SECRET=test-secret-for-encryption
|
||||
@@ -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: [{
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 || '',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -36,7 +36,7 @@ export interface FileDiffResponse {
|
||||
export interface GitDiffOptions {
|
||||
showContext?: number
|
||||
ignoreWhitespace?: boolean
|
||||
unified?: boolean
|
||||
unified?: number
|
||||
}
|
||||
|
||||
export interface GitBranch {
|
||||
|
||||
@@ -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')
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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, {
|
||||
|
||||
@@ -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' }
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import * as crypto from 'crypto'
|
||||
import * as fs from 'fs/promises'
|
||||
import * as path from 'path'
|
||||
|
||||
const { setupWorkspacePath, getWorkspacePathMock } = vi.hoisted(() => {
|
||||
let workspacePath: string = '/tmp/test-workspace'
|
||||
return {
|
||||
setupWorkspacePath: (newPath: string) => {
|
||||
workspacePath = newPath
|
||||
},
|
||||
getWorkspacePathMock: () => workspacePath
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV: {
|
||||
AUTH: {
|
||||
SECRET: 'test-secret-for-encryption-key-32c'
|
||||
},
|
||||
OPENCODE: {
|
||||
PORT: 5551
|
||||
},
|
||||
SERVER: {
|
||||
PORT: 5003
|
||||
}
|
||||
},
|
||||
getWorkspacePath: getWorkspacePathMock,
|
||||
getReposPath: vi.fn(() => '/tmp/test-repos')
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
let testWorkspacePath: string = '/tmp/test-workspace'
|
||||
|
||||
const mockPrepare = vi.fn()
|
||||
const mockExec = vi.fn()
|
||||
const mockDatabase = {
|
||||
prepare: mockPrepare,
|
||||
exec: mockExec
|
||||
} as unknown as Database
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(() => mockDatabase)
|
||||
}))
|
||||
|
||||
import { GitAuthService } from '../../src/services/git-auth'
|
||||
import { writeTemporarySSHKey, cleanupSSHKey, cleanupAllSSHKeys, buildSSHCommand } from '../../src/utils/ssh-key-manager'
|
||||
import { encryptSecret, decryptSecret } from '../../src/utils/crypto'
|
||||
|
||||
describe('SSH Integration Tests', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
const uniqueId = crypto.randomUUID()
|
||||
testWorkspacePath = `/tmp/test-workspace-${uniqueId}`
|
||||
setupWorkspacePath(testWorkspacePath)
|
||||
|
||||
mockPrepare.mockReturnValue({
|
||||
run: vi.fn(),
|
||||
get: vi.fn().mockReturnValue(null),
|
||||
all: vi.fn().mockReturnValue([])
|
||||
})
|
||||
|
||||
const configDir = path.join(testWorkspacePath, 'config')
|
||||
const sshKeysDir = path.join(testWorkspacePath, '.ssh-keys')
|
||||
await fs.mkdir(configDir, { recursive: true })
|
||||
await fs.mkdir(sshKeysDir, { recursive: true })
|
||||
const knownHostsFile = path.join(configDir, 'known_hosts')
|
||||
await fs.writeFile(knownHostsFile, '', { mode: 0o600 })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
await fs.rm(testWorkspacePath, { recursive: true, force: true }).catch(() => {})
|
||||
})
|
||||
|
||||
describe('Full SSH Authentication Flow', () => {
|
||||
it('should setup SSH key, get environment, and cleanup', async () => {
|
||||
const validKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
|
||||
const keyPath = await writeTemporarySSHKey(validKey, 'integration-test')
|
||||
expect(keyPath).toBeTruthy()
|
||||
|
||||
const stats = await fs.stat(keyPath)
|
||||
expect(stats.mode & 0o777).toBe(0o600)
|
||||
|
||||
const sshResult = buildSSHCommand(keyPath)
|
||||
expect(sshResult.command).toContain(`ssh -T -i "${keyPath}"`)
|
||||
expect(sshResult.command).toContain('-o IdentitiesOnly=yes')
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
await expect(fs.access(keyPath)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('should setup SSH key with passphrase', async () => {
|
||||
const validKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
const passphrase = 'my-secret-passphrase'
|
||||
|
||||
const keyPath = await writeTemporarySSHKey(validKey, 'integration-pass-test')
|
||||
|
||||
const sshResult = buildSSHCommand(keyPath, passphrase)
|
||||
expect(sshResult.command).toContain('sshpass -e')
|
||||
expect(sshResult.env?.SSHPASS).toBe(passphrase)
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Key Lifecycle', () => {
|
||||
it('should handle create -> use -> cleanup cycle', async () => {
|
||||
const key1 = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== key1@host'
|
||||
const key2 = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/key2@host'
|
||||
|
||||
const keyPath1 = await writeTemporarySSHKey(key1, 'lifecycle-1')
|
||||
expect(keyPath1).toBeTruthy()
|
||||
|
||||
const keyPath2 = await writeTemporarySSHKey(key2, 'lifecycle-2')
|
||||
expect(keyPath2).toBeTruthy()
|
||||
|
||||
const cmd1 = buildSSHCommand(keyPath1)
|
||||
expect(cmd1.command).toContain(keyPath1)
|
||||
|
||||
const cmd2 = buildSSHCommand(keyPath2)
|
||||
expect(cmd2.command).toContain(keyPath2)
|
||||
|
||||
await cleanupSSHKey(keyPath1)
|
||||
await cleanupSSHKey(keyPath2)
|
||||
|
||||
await expect(fs.access(keyPath1)).rejects.toThrow()
|
||||
await expect(fs.access(keyPath2)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('should handle bulk cleanup after multiple key creations', async () => {
|
||||
const keys = [
|
||||
'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== bulk1@host',
|
||||
'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/bulk2@host',
|
||||
'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEM/bulk3@host'
|
||||
]
|
||||
|
||||
const keyPaths: string[] = []
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const keyPath = await writeTemporarySSHKey(keys[i]!, `bulk-test-${i}`)
|
||||
keyPaths.push(keyPath)
|
||||
}
|
||||
|
||||
await cleanupAllSSHKeys()
|
||||
|
||||
for (const keyPath of keyPaths) {
|
||||
await expect(fs.access(keyPath)).rejects.toThrow()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('Environment Variable Propagation', () => {
|
||||
it('should include all required SSH environment variables', async () => {
|
||||
const validKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
const keyPath = await writeTemporarySSHKey(validKey, 'env-test')
|
||||
|
||||
const sshResult = buildSSHCommand(keyPath)
|
||||
|
||||
expect(sshResult.command).toContain('-o IdentitiesOnly=yes')
|
||||
expect(sshResult.command).toContain('-o PasswordAuthentication=no')
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
|
||||
it('should include known_hosts path when provided', async () => {
|
||||
const validKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
const keyPath = await writeTemporarySSHKey(validKey, 'known-hosts-test')
|
||||
const knownHostsPath = path.join(testWorkspacePath, 'config', 'known_hosts')
|
||||
|
||||
const sshResult = buildSSHCommand(keyPath, undefined, knownHostsPath)
|
||||
|
||||
expect(sshResult.command).toContain(`-o UserKnownHostsFile="${knownHostsPath}"`)
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Switching Between SSH and PAT Credentials', () => {
|
||||
it('should properly switch between SSH credential types', async () => {
|
||||
const sshKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== ssh@host'
|
||||
|
||||
const keyPath = await writeTemporarySSHKey(sshKey, 'switch-test')
|
||||
const sshCmd = buildSSHCommand(keyPath)
|
||||
expect(sshCmd.command).toContain('ssh -T -i')
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
await expect(fs.access(keyPath)).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Encryption and Decryption Integration', () => {
|
||||
it('should properly encrypt and decrypt SSH private key', () => {
|
||||
const privateKey = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const encrypted = encryptSecret(privateKey)
|
||||
expect(encrypted).not.toBe(privateKey)
|
||||
|
||||
const decrypted = decryptSecret(encrypted)
|
||||
expect(decrypted).toBe(privateKey)
|
||||
})
|
||||
|
||||
it('should properly encrypt and decrypt passphrase', () => {
|
||||
const passphrase = 'my-super-secret-passphrase-123!'
|
||||
|
||||
const encrypted = encryptSecret(passphrase)
|
||||
expect(encrypted).not.toBe(passphrase)
|
||||
|
||||
const decrypted = decryptSecret(encrypted)
|
||||
expect(decrypted).toBe(passphrase)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GitAuthService Integration', () => {
|
||||
it('should initialize SSH host key handler', () => {
|
||||
const gitAuthService = new GitAuthService()
|
||||
const mockIpcServer = {
|
||||
registerHandler: vi.fn()
|
||||
}
|
||||
|
||||
gitAuthService.initialize(mockIpcServer as never, mockDatabase)
|
||||
|
||||
expect(gitAuthService.sshHostKeyHandler).toBeTruthy()
|
||||
})
|
||||
|
||||
it('should return true for verifyHostKeyBeforeOperation when handler is null', async () => {
|
||||
const gitAuthService = new GitAuthService()
|
||||
|
||||
const result = await gitAuthService.verifyHostKeyBeforeOperation('git@github.com:user/repo.git')
|
||||
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should get git environment with terminal prompt disabled', () => {
|
||||
const gitAuthService = new GitAuthService()
|
||||
|
||||
const env = gitAuthService.getGitEnvironment()
|
||||
|
||||
expect(env.GIT_TERMINAL_PROMPT).toBe('0')
|
||||
expect(env.LANG).toBe('en_US.UTF-8')
|
||||
expect(env.LC_ALL).toBe('en_US.UTF-8')
|
||||
})
|
||||
|
||||
it('should include silent flag when requested', () => {
|
||||
const gitAuthService = new GitAuthService()
|
||||
|
||||
const env = gitAuthService.getGitEnvironment(true)
|
||||
|
||||
expect(env.VSCODE_GIT_FETCH_SILENT).toBe('true')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Database Persistence', () => {
|
||||
it('should save trusted host to database', async () => {
|
||||
const mockRun = vi.fn()
|
||||
mockPrepare.mockReturnValue({
|
||||
run: mockRun,
|
||||
get: vi.fn().mockReturnValue(null),
|
||||
all: vi.fn().mockReturnValue([])
|
||||
})
|
||||
|
||||
const gitAuthService = new GitAuthService()
|
||||
const mockIpcServer = {
|
||||
registerHandler: vi.fn()
|
||||
}
|
||||
gitAuthService.initialize(mockIpcServer as never, mockDatabase)
|
||||
|
||||
const handler = gitAuthService.sshHostKeyHandler
|
||||
if (handler) {
|
||||
handler['saveTrustedHost']('github.com', 'github.com ssh-rsa AAAAB...')
|
||||
}
|
||||
|
||||
expect(mockPrepare).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should load trusted hosts from database on initialization', async () => {
|
||||
const mockAll = vi.fn().mockReturnValue([
|
||||
{ host: 'github.com', public_key: 'github.com ssh-rsa AAAAB...' },
|
||||
{ host: 'gitlab.com', public_key: 'gitlab.com ssh-ed25519 AAAAC...' }
|
||||
])
|
||||
mockPrepare.mockReturnValue({
|
||||
run: vi.fn(),
|
||||
get: vi.fn().mockReturnValue(null),
|
||||
all: mockAll
|
||||
})
|
||||
|
||||
const gitAuthService = new GitAuthService()
|
||||
const mockIpcServer = {
|
||||
registerHandler: vi.fn()
|
||||
}
|
||||
gitAuthService.initialize(mockIpcServer as never, mockDatabase)
|
||||
|
||||
await gitAuthService.sshHostKeyHandler?.initialize()
|
||||
|
||||
expect(mockPrepare).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,311 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import * as crypto from 'crypto'
|
||||
import * as fs from 'fs/promises'
|
||||
import * as path from 'path'
|
||||
|
||||
const { setupWorkspacePath, getWorkspacePathMock } = vi.hoisted(() => {
|
||||
let path: string = '/tmp/test-workspace'
|
||||
return {
|
||||
setupWorkspacePath: (newPath: string) => {
|
||||
path = newPath
|
||||
},
|
||||
getWorkspacePathMock: () => path
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV: {
|
||||
AUTH: {
|
||||
SECRET: 'test-secret-for-encryption'
|
||||
},
|
||||
OPENCODE: {
|
||||
PORT: 5551
|
||||
},
|
||||
SERVER: {
|
||||
PORT: 5003
|
||||
}
|
||||
},
|
||||
getWorkspacePath: getWorkspacePathMock,
|
||||
getReposPath: vi.fn(() => '/tmp/test-repos'),
|
||||
}))
|
||||
|
||||
let testWorkspacePath: string = '/tmp/test-workspace'
|
||||
|
||||
const mockPrepare = vi.fn()
|
||||
const mockExec = vi.fn()
|
||||
const mockDatabase = {
|
||||
prepare: mockPrepare,
|
||||
exec: mockExec,
|
||||
} as unknown as Database
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(() => mockDatabase),
|
||||
}))
|
||||
|
||||
import { SSHHostKeyHandler, createSSHHostKeyHandler } from '../../src/ipc/sshHostKeyHandler'
|
||||
|
||||
describe('SSHHostKeyHandler', () => {
|
||||
let handler: SSHHostKeyHandler
|
||||
let knownHostsPath: string
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
const uniqueId = crypto.randomUUID()
|
||||
testWorkspacePath = `/tmp/test-workspace-${uniqueId}`
|
||||
setupWorkspacePath(testWorkspacePath)
|
||||
|
||||
mockPrepare.mockReturnValue({
|
||||
run: vi.fn(),
|
||||
get: vi.fn().mockReturnValue(null),
|
||||
all: vi.fn().mockReturnValue([]),
|
||||
})
|
||||
|
||||
const configDir = `${testWorkspacePath}/config`
|
||||
await fs.mkdir(configDir, { recursive: true })
|
||||
const knownHostsFile = path.join(configDir, 'known_hosts')
|
||||
await fs.writeFile(knownHostsFile, '', { mode: 0o600 })
|
||||
|
||||
handler = createSSHHostKeyHandler(mockDatabase, 5000)
|
||||
await handler.initialize()
|
||||
knownHostsPath = handler.getKnownHostsPath()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
await fs.rm(testWorkspacePath, { recursive: true, force: true }).catch(() => {})
|
||||
})
|
||||
|
||||
describe('Public Key Retrieval', () => {
|
||||
it('should store public key instead of fingerprint', async () => {
|
||||
const host = 'test.example.com'
|
||||
const publicKey = `${host} ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com`
|
||||
|
||||
await handler['addToKnownHosts'](host, publicKey)
|
||||
|
||||
const content = await fs.readFile(knownHostsPath, 'utf-8')
|
||||
expect(content).toContain(publicKey)
|
||||
expect(content).not.toContain('SHA256:')
|
||||
})
|
||||
|
||||
it('should store public key in database', () => {
|
||||
const host = 'test.example.com'
|
||||
const publicKey = `${host} ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com`
|
||||
|
||||
const mockRun = vi.fn()
|
||||
mockPrepare.mockReturnValue({ run: mockRun })
|
||||
|
||||
handler['saveTrustedHost'](host, publicKey)
|
||||
|
||||
expect(mockPrepare).toHaveBeenCalled()
|
||||
expect(mockRun).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Host:Port Handling', () => {
|
||||
it('should handle hosts with non-standard ports', async () => {
|
||||
const host = 'github.com:2222'
|
||||
const publicKey = `[github.com]:2222 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host`
|
||||
|
||||
await handler['addToKnownHosts'](host, publicKey)
|
||||
|
||||
const content = await fs.readFile(knownHostsPath, 'utf-8')
|
||||
expect(content).toContain('[github.com]:2222')
|
||||
})
|
||||
|
||||
it('should handle hosts with standard port 22', async () => {
|
||||
const host = 'github.com'
|
||||
const publicKey = `${host} ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host`
|
||||
|
||||
await handler['addToKnownHosts'](host, publicKey)
|
||||
|
||||
const content = await fs.readFile(knownHostsPath, 'utf-8')
|
||||
expect(content).toContain(`${host} ssh-rsa`)
|
||||
expect(content).not.toContain(':22')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Load from Database', () => {
|
||||
it('should load public keys from database to known_hosts', async () => {
|
||||
const host1 = 'github.com'
|
||||
const host2 = 'gitlab.com:2222'
|
||||
const publicKey1 = `${host1} ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host`
|
||||
const publicKey2 = `[gitlab.com]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com`
|
||||
|
||||
mockPrepare.mockReturnValue({
|
||||
all: vi.fn().mockReturnValue([
|
||||
{ host: host1, public_key: publicKey1 },
|
||||
{ host: host2, public_key: publicKey2 },
|
||||
]),
|
||||
})
|
||||
|
||||
await handler['loadFromDatabaseToKnownHosts']()
|
||||
|
||||
const content = await fs.readFile(knownHostsPath, 'utf-8')
|
||||
expect(content).toContain(publicKey1)
|
||||
expect(content).toContain(publicKey2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SSH Key Format Support', () => {
|
||||
const keyFormats = [
|
||||
{
|
||||
type: 'RSA public',
|
||||
key: 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
},
|
||||
{
|
||||
type: 'ED25519 public',
|
||||
key: 'github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@example.com'
|
||||
},
|
||||
{
|
||||
type: 'ECDSA public',
|
||||
key: 'github.com ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEM/test@test.com'
|
||||
}
|
||||
]
|
||||
|
||||
keyFormats.forEach(({ type, key }) => {
|
||||
it(`should support ${type}`, async () => {
|
||||
await handler['addToKnownHosts']('testhost', key)
|
||||
|
||||
const content = await fs.readFile(knownHostsPath, 'utf-8')
|
||||
const keyType = key.split(' ')[1]
|
||||
if (keyType) {
|
||||
expect(content).toContain(keyType)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('Known Hosts File Format', () => {
|
||||
it('should write proper known_hosts format', async () => {
|
||||
const host = 'github.com'
|
||||
const keyType = 'ssh-rsa'
|
||||
const keyData = 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw=='
|
||||
const publicKey = `${host} ${keyType} ${keyData}`
|
||||
|
||||
await handler['addToKnownHosts'](host, publicKey)
|
||||
|
||||
const content = await fs.readFile(knownHostsPath, 'utf-8')
|
||||
const lines = content.trim().split('\n')
|
||||
|
||||
expect(lines.length).toBe(1)
|
||||
const firstLine = lines[0]
|
||||
if (firstLine) {
|
||||
const parts = firstLine.split(' ')
|
||||
expect(parts.length).toBeGreaterThanOrEqual(3)
|
||||
expect(parts[0]).toBe(host)
|
||||
expect(parts[1]).toBe(keyType)
|
||||
expect(parts[2]).toBe(keyData)
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle bracketed host notation for non-standard ports', async () => {
|
||||
const host = 'github.com:2222'
|
||||
const publicKey = '[github.com]:2222 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
|
||||
await handler['addToKnownHosts'](host, publicKey)
|
||||
|
||||
const content = await fs.readFile(knownHostsPath, 'utf-8')
|
||||
expect(content).toContain('[github.com]:2222')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getEnv', () => {
|
||||
it('should return known hosts path in environment', () => {
|
||||
const env = handler.getEnv()
|
||||
expect(env.KNOWN_HOSTS_PATH).toBe(knownHostsPath)
|
||||
})
|
||||
})
|
||||
|
||||
describe('verifyHostKeyBeforeOperation', () => {
|
||||
it('should return true immediately for trusted host in DB', async () => {
|
||||
mockPrepare.mockReturnValue({
|
||||
run: vi.fn(),
|
||||
get: vi.fn().mockReturnValue({ key_type: 'ssh-rsa', public_key: 'github.com ssh-rsa AAAAB...' }),
|
||||
all: vi.fn().mockReturnValue([])
|
||||
})
|
||||
|
||||
const result = await handler.verifyHostKeyBeforeOperation('git@github.com:user/repo.git')
|
||||
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false on ssh-keyscan command failure', async () => {
|
||||
mockPrepare.mockReturnValue({
|
||||
run: vi.fn(),
|
||||
get: vi.fn().mockReturnValue(null),
|
||||
all: vi.fn().mockReturnValue([])
|
||||
})
|
||||
|
||||
const result = await handler.verifyHostKeyBeforeOperation('git@invalid-host.example:user/repo.git')
|
||||
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('respond', () => {
|
||||
it('should return error for non-existent request', async () => {
|
||||
const result = await handler.respond({
|
||||
requestId: 'non-existent-id',
|
||||
response: 'accept'
|
||||
})
|
||||
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toBe('Request not found or expired')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getPendingCount', () => {
|
||||
it('should return 0 when no pending requests', () => {
|
||||
const count = handler.getPendingCount()
|
||||
expect(count).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Error Scenarios', () => {
|
||||
it('should handle database query failures gracefully in getTrustedHost', () => {
|
||||
mockPrepare.mockImplementation(() => {
|
||||
throw new Error('Database connection failed')
|
||||
})
|
||||
|
||||
const result = handler['getTrustedHost']('github.com')
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('should handle database save failures gracefully', () => {
|
||||
const mockRun = vi.fn().mockImplementation(() => {
|
||||
throw new Error('Database write failed')
|
||||
})
|
||||
mockPrepare.mockReturnValue({
|
||||
run: mockRun,
|
||||
get: vi.fn().mockReturnValue(null),
|
||||
all: vi.fn().mockReturnValue([])
|
||||
})
|
||||
|
||||
expect(() => {
|
||||
handler['saveTrustedHost']('github.com', 'github.com ssh-rsa AAAAB...')
|
||||
}).not.toThrow()
|
||||
})
|
||||
|
||||
it('should handle known_hosts file write failures gracefully', async () => {
|
||||
const originalPath = handler['knownHostsPath']
|
||||
handler['knownHostsPath'] = '/nonexistent/path/known_hosts'
|
||||
|
||||
await expect(handler['addToKnownHosts']('github.com', 'github.com ssh-rsa AAAAB...')).resolves.not.toThrow()
|
||||
|
||||
handler['knownHostsPath'] = originalPath
|
||||
})
|
||||
|
||||
it('should handle database load failures gracefully', async () => {
|
||||
mockPrepare.mockReturnValue({
|
||||
all: vi.fn().mockImplementation(() => {
|
||||
throw new Error('Database read failed')
|
||||
})
|
||||
})
|
||||
|
||||
await expect(handler['loadFromDatabaseToKnownHosts']()).resolves.not.toThrow()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -27,6 +27,26 @@ vi.mock('../../src/utils/process', () => ({
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
getReposPath: vi.fn(() => '/repos'),
|
||||
getWorkspacePath: vi.fn(() => '/tmp/test-workspace'),
|
||||
ENV: {
|
||||
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
|
||||
SERVER: { PORT: 5001, HOST: '0.0.0.0', CORS_ORIGIN: '*', NODE_ENV: 'test' },
|
||||
AUTH: { SECRET: 'test-secret' },
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config', () => ({
|
||||
DEFAULTS: {
|
||||
SSE: {
|
||||
RECONNECT_DELAY_MS: 1000,
|
||||
MAX_RECONNECT_DELAY_MS: 30000,
|
||||
IDLE_GRACE_PERIOD_MS: 120000,
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('eventsource', () => ({
|
||||
EventSource: vi.fn(),
|
||||
}))
|
||||
|
||||
const getRepoByIdMock = db.getRepoById as MockedFunction<typeof db.getRepoById>
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { Hono } from 'hono'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV: {
|
||||
AUTH: {
|
||||
SECRET: 'test-secret-for-encryption'
|
||||
},
|
||||
OPENCODE: {
|
||||
PORT: 5551
|
||||
},
|
||||
SERVER: {
|
||||
PORT: 5003
|
||||
}
|
||||
},
|
||||
getReposPath: vi.fn(() => '/tmp/test-repos'),
|
||||
getWorkspacePath: vi.fn(() => '/tmp/test-workspace')
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config', () => ({
|
||||
DEFAULTS: {
|
||||
SSE: {
|
||||
RECONNECT_DELAY_MS: 1000,
|
||||
MAX_RECONNECT_DELAY_MS: 30000,
|
||||
IDLE_GRACE_PERIOD_MS: 120000,
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('eventsource', () => ({
|
||||
EventSource: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
import { createSSHRoutes } from '../../src/routes/ssh'
|
||||
|
||||
interface MockSSHHostKeyHandler {
|
||||
respond: ReturnType<typeof vi.fn>
|
||||
getPendingCount?: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
interface MockGitAuthService {
|
||||
sshHostKeyHandler: MockSSHHostKeyHandler | null
|
||||
}
|
||||
|
||||
describe('SSH Routes', () => {
|
||||
let app: Hono
|
||||
let mockGitAuthService: MockGitAuthService
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGitAuthService = {
|
||||
sshHostKeyHandler: {
|
||||
respond: vi.fn().mockReturnValue({ success: true }),
|
||||
getPendingCount: vi.fn().mockReturnValue(0)
|
||||
}
|
||||
}
|
||||
app = createSSHRoutes(mockGitAuthService as unknown as GitAuthService)
|
||||
})
|
||||
|
||||
describe('POST /host-key/respond', () => {
|
||||
it('should accept valid response with accept', async () => {
|
||||
const response = await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId: 'test-123', response: 'accept' })
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
expect(mockGitAuthService.sshHostKeyHandler?.respond).toHaveBeenCalledWith({
|
||||
requestId: 'test-123',
|
||||
response: 'accept'
|
||||
})
|
||||
})
|
||||
|
||||
it('should accept valid response with reject', async () => {
|
||||
const response = await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId: 'test-456', response: 'reject' })
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
expect(mockGitAuthService.sshHostKeyHandler?.respond).toHaveBeenCalledWith({
|
||||
requestId: 'test-456',
|
||||
response: 'reject'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return 400 for invalid request body missing requestId', async () => {
|
||||
const response = await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ response: 'accept' })
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('success', false)
|
||||
expect(body).toHaveProperty('error', 'Invalid request body')
|
||||
})
|
||||
|
||||
it('should return 400 for invalid request body missing response', async () => {
|
||||
const response = await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId: 'test-123' })
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('success', false)
|
||||
expect(body).toHaveProperty('error', 'Invalid request body')
|
||||
})
|
||||
|
||||
it('should return 400 for invalid response value', async () => {
|
||||
const response = await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId: 'test-123', response: 'invalid' })
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(body).toHaveProperty('success', false)
|
||||
expect(body).toHaveProperty('error', 'Invalid request body')
|
||||
})
|
||||
|
||||
it('should return 404 when handler not found', async () => {
|
||||
mockGitAuthService.sshHostKeyHandler = null
|
||||
app = createSSHRoutes(mockGitAuthService as unknown as GitAuthService)
|
||||
|
||||
const response = await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId: 'test-123', response: 'accept' })
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('success', false)
|
||||
expect(body).toHaveProperty('error', 'SSH host key handler not found')
|
||||
})
|
||||
|
||||
it('should handle request ID matching correctly', async () => {
|
||||
const requestId = 'unique-request-id-12345'
|
||||
|
||||
await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId, response: 'accept' })
|
||||
})
|
||||
|
||||
expect(mockGitAuthService.sshHostKeyHandler?.respond).toHaveBeenCalledWith({
|
||||
requestId: 'unique-request-id-12345',
|
||||
response: 'accept'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return handler result on success', async () => {
|
||||
mockGitAuthService.sshHostKeyHandler = {
|
||||
respond: vi.fn().mockReturnValue({ success: true }),
|
||||
getPendingCount: vi.fn()
|
||||
}
|
||||
app = createSSHRoutes(mockGitAuthService as unknown as GitAuthService)
|
||||
|
||||
const response = await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId: 'test-123', response: 'accept' })
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(body).toEqual({ success: true })
|
||||
})
|
||||
|
||||
it('should return handler error when request not found', async () => {
|
||||
mockGitAuthService.sshHostKeyHandler = {
|
||||
respond: vi.fn().mockReturnValue({ success: false, error: 'Request not found or expired' }),
|
||||
getPendingCount: vi.fn()
|
||||
}
|
||||
app = createSSHRoutes(mockGitAuthService as unknown as GitAuthService)
|
||||
|
||||
const response = await app.request('/host-key/respond', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId: 'expired-123', response: 'accept' })
|
||||
})
|
||||
const body = await response.json()
|
||||
|
||||
expect(body).toEqual({ success: false, error: 'Request not found or expired' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /host-key/status', () => {
|
||||
it('should return pending count correctly when zero', async () => {
|
||||
mockGitAuthService.sshHostKeyHandler = {
|
||||
respond: vi.fn(),
|
||||
getPendingCount: vi.fn().mockReturnValue(0)
|
||||
}
|
||||
app = createSSHRoutes(mockGitAuthService as unknown as GitAuthService)
|
||||
|
||||
const response = await app.request('/host-key/status')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
expect(body).toHaveProperty('pendingCount', 0)
|
||||
})
|
||||
|
||||
it('should return pending count correctly when non-zero', async () => {
|
||||
mockGitAuthService.sshHostKeyHandler = {
|
||||
respond: vi.fn(),
|
||||
getPendingCount: vi.fn().mockReturnValue(5)
|
||||
}
|
||||
app = createSSHRoutes(mockGitAuthService as unknown as GitAuthService)
|
||||
|
||||
const response = await app.request('/host-key/status')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('success', true)
|
||||
expect(body).toHaveProperty('pendingCount', 5)
|
||||
})
|
||||
|
||||
it('should return 404 when handler not found', async () => {
|
||||
mockGitAuthService.sshHostKeyHandler = null
|
||||
app = createSSHRoutes(mockGitAuthService as unknown as GitAuthService)
|
||||
|
||||
const response = await app.request('/host-key/status')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('success', false)
|
||||
expect(body).toHaveProperty('error', 'SSH host key handler not found')
|
||||
})
|
||||
|
||||
it('should return 500 when getPendingCount is undefined', async () => {
|
||||
mockGitAuthService.sshHostKeyHandler = {
|
||||
respond: vi.fn(),
|
||||
getPendingCount: undefined as unknown as ReturnType<typeof vi.fn>
|
||||
}
|
||||
app = createSSHRoutes(mockGitAuthService as unknown as GitAuthService)
|
||||
|
||||
const response = await app.request('/host-key/status')
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body).toHaveProperty('success', false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,344 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type { GitCredential } from '../../src/utils/git-auth'
|
||||
import type { IPCServer } from '../../src/ipc/ipcServer'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
vi.mock('bun:sqlite', () => ({
|
||||
Database: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV: {
|
||||
AUTH: {
|
||||
SECRET: 'test-secret-for-encryption'
|
||||
},
|
||||
OPENCODE: {
|
||||
PORT: 5551
|
||||
},
|
||||
SERVER: {
|
||||
PORT: 5003
|
||||
}
|
||||
},
|
||||
getReposPath: vi.fn(() => '/tmp/test-repos'),
|
||||
getWorkspacePath: vi.fn(() => '/tmp/test-workspace')
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config', () => ({
|
||||
DEFAULTS: {
|
||||
SSE: {
|
||||
RECONNECT_DELAY_MS: 1000,
|
||||
MAX_RECONNECT_DELAY_MS: 30000,
|
||||
IDLE_GRACE_PERIOD_MS: 120000,
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('eventsource', () => ({
|
||||
EventSource: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/ssh-key-manager', () => ({
|
||||
writeTemporarySSHKey: vi.fn().mockResolvedValue('/tmp/test-workspace/.ssh-keys/test-key'),
|
||||
cleanupSSHKey: vi.fn().mockResolvedValue(undefined),
|
||||
buildSSHCommand: vi.fn((keyPath: string, passphrase?: string, knownHostsPath?: string) => {
|
||||
const knownHostsOption = knownHostsPath
|
||||
? `-o UserKnownHostsFile="${knownHostsPath}" -o StrictHostKeyChecking=accept-new`
|
||||
: '-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/dev/null'
|
||||
const baseCommand = `ssh -i ${keyPath} -o IdentitiesOnly=yes -o PasswordAuthentication=no ${knownHostsOption}`
|
||||
if (passphrase) {
|
||||
return {
|
||||
command: `sshpass -e ${baseCommand}`,
|
||||
env: { SSHPASS: passphrase }
|
||||
}
|
||||
}
|
||||
return { command: baseCommand }
|
||||
}),
|
||||
buildSSHCommandWithKnownHosts: vi.fn((knownHostsPath: string) =>
|
||||
`ssh -o UserKnownHostsFile="${knownHostsPath}" -o StrictHostKeyChecking=accept-new -o PasswordAuthentication=no`
|
||||
),
|
||||
}))
|
||||
|
||||
import { GitAuthService } from '../../src/services/git-auth'
|
||||
import { encryptSecret } from '../../src/utils/crypto'
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../ipc/ipcServer', () => ({
|
||||
IPCServer: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../ipc/askpassHandler', () => ({
|
||||
AskpassHandler: vi.fn().mockImplementation(() => ({
|
||||
getEnv: vi.fn().mockReturnValue({}),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/ipc/sshHostKeyHandler', () => ({
|
||||
SSHHostKeyHandler: vi.fn().mockImplementation(() => ({
|
||||
initialize: vi.fn().mockResolvedValue(undefined),
|
||||
getKnownHostsPath: vi.fn().mockReturnValue(null),
|
||||
getEnv: vi.fn().mockReturnValue({}),
|
||||
})),
|
||||
}))
|
||||
|
||||
describe('GitAuthService with passphrase support', () => {
|
||||
let gitAuthService: GitAuthService
|
||||
let mockIpcServer: IPCServer
|
||||
let mockDatabase: Database
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
gitAuthService = new GitAuthService()
|
||||
mockIpcServer = {
|
||||
registerHandler: vi.fn(),
|
||||
} as unknown as IPCServer
|
||||
mockDatabase = {} as Database
|
||||
gitAuthService.initialize(mockIpcServer, mockDatabase)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('setupSSHKey with passphrase', () => {
|
||||
it('decrypts and stores passphrase from credential', async () => {
|
||||
const privateKey = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
const passphrase = 'my-secret-passphrase'
|
||||
|
||||
const credential: GitCredential = {
|
||||
name: 'test-credential',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey),
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret(passphrase),
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential)
|
||||
|
||||
const sshPassphrase = gitAuthService['sshPassphrase']
|
||||
expect(sshPassphrase).toBe(passphrase)
|
||||
})
|
||||
|
||||
it('handles credential without passphrase', async () => {
|
||||
const privateKey = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
|
||||
const credential: GitCredential = {
|
||||
name: 'test-credential',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey),
|
||||
hasPassphrase: false,
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential)
|
||||
|
||||
const sshPassphrase = gitAuthService['sshPassphrase']
|
||||
expect(sshPassphrase).toBeNull()
|
||||
})
|
||||
|
||||
it('clears previous passphrase when setting up new credential', async () => {
|
||||
const privateKey1 = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
const passphrase1 = 'passphrase1'
|
||||
const privateKey2 = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
const passphrase2 = 'passphrase2'
|
||||
|
||||
const credential1: GitCredential = {
|
||||
name: 'test-credential-1',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey1),
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret(passphrase1),
|
||||
}
|
||||
|
||||
const credential2: GitCredential = {
|
||||
name: 'test-credential-2',
|
||||
host: 'gitlab.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey2),
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret(passphrase2),
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential1)
|
||||
expect(gitAuthService['sshPassphrase']).toBe(passphrase1)
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential2)
|
||||
expect(gitAuthService['sshPassphrase']).toBe(passphrase2)
|
||||
})
|
||||
|
||||
it('handles decryption errors gracefully', async () => {
|
||||
const credential: GitCredential = {
|
||||
name: 'test-credential',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: 'invalid-encrypted-data',
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret('passphrase'),
|
||||
}
|
||||
|
||||
await expect(gitAuthService['setupSSHKey'](credential)).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSSHEnvironment', () => {
|
||||
it('includes sshpass command when passphrase is available', async () => {
|
||||
const privateKey = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
const passphrase = 'my-passphrase'
|
||||
|
||||
const credential: GitCredential = {
|
||||
name: 'test-credential',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey),
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret(passphrase),
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential)
|
||||
const env = gitAuthService['getSSHEnvironment']()
|
||||
|
||||
expect(env.GIT_SSH_COMMAND).toContain('sshpass -e')
|
||||
expect(env.SSHPASS).toBe(passphrase)
|
||||
})
|
||||
|
||||
it('does not include sshpass when passphrase is not available', async () => {
|
||||
const privateKey = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
|
||||
const credential: GitCredential = {
|
||||
name: 'test-credential',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey),
|
||||
hasPassphrase: false,
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential)
|
||||
const env = gitAuthService['getSSHEnvironment']()
|
||||
|
||||
expect(env.GIT_SSH_COMMAND).not.toContain('sshpass')
|
||||
})
|
||||
|
||||
it('returns empty object when no SSH key is set up', () => {
|
||||
const env = gitAuthService['getSSHEnvironment']()
|
||||
expect(env).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('cleanupSSHKey', () => {
|
||||
it('clears passphrase from memory', async () => {
|
||||
const privateKey = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZ\niVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmlu\nZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
const passphrase = 'my-passphrase'
|
||||
|
||||
const credential: GitCredential = {
|
||||
name: 'test-credential',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey),
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret(passphrase),
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential)
|
||||
expect(gitAuthService['sshPassphrase']).toBe(passphrase)
|
||||
|
||||
await gitAuthService['cleanupSSHKey']()
|
||||
expect(gitAuthService['sshPassphrase']).toBeNull()
|
||||
})
|
||||
|
||||
it('clears passphrase and key path together', async () => {
|
||||
const privateKey = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
const passphrase = 'my-passphrase'
|
||||
|
||||
const credential: GitCredential = {
|
||||
name: 'test-credential',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey),
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret(passphrase),
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential)
|
||||
expect(gitAuthService['sshPassphrase']).toBe(passphrase)
|
||||
expect(gitAuthService['sshKeyPath']).toBeTruthy()
|
||||
|
||||
await gitAuthService['cleanupSSHKey']()
|
||||
expect(gitAuthService['sshPassphrase']).toBeNull()
|
||||
expect(gitAuthService['sshKeyPath']).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('integration with passphrase-protected keys', () => {
|
||||
it('properly handles full SSH key lifecycle with passphrase', async () => {
|
||||
const privateKey = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
const passphrase = 'secure-passphrase-123'
|
||||
|
||||
const credential: GitCredential = {
|
||||
name: 'production-ssh',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(privateKey),
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret(passphrase),
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credential)
|
||||
|
||||
expect(gitAuthService['sshPassphrase']).toBe(passphrase)
|
||||
expect(gitAuthService['sshKeyPath']).toBeTruthy()
|
||||
|
||||
const env = gitAuthService['getSSHEnvironment']()
|
||||
expect(env.GIT_SSH_COMMAND).toContain('sshpass -e')
|
||||
expect(env.SSHPASS).toBe(passphrase)
|
||||
|
||||
await gitAuthService['cleanupSSHKey']()
|
||||
|
||||
expect(gitAuthService['sshPassphrase']).toBeNull()
|
||||
expect(gitAuthService['sshKeyPath']).toBeNull()
|
||||
})
|
||||
|
||||
it('handles switching between credentials with and without passphrases', async () => {
|
||||
const validKey1 = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
const validKey2 = '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAAgBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4\naRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4aAAAADHN0cmluZy1rZXktdGVzdAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v\nMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr\nbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaan\nqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj\n5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==\n-----END OPENSSH PRIVATE KEY-----'
|
||||
|
||||
const credentialWithPassphrase: GitCredential = {
|
||||
name: 'ssh-with-pass',
|
||||
host: 'github.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(validKey1),
|
||||
hasPassphrase: true,
|
||||
passphrase: encryptSecret('pass1'),
|
||||
}
|
||||
|
||||
const credentialWithoutPassphrase: GitCredential = {
|
||||
name: 'ssh-no-pass',
|
||||
host: 'gitlab.com',
|
||||
type: 'ssh',
|
||||
sshPrivateKeyEncrypted: encryptSecret(validKey2),
|
||||
hasPassphrase: false,
|
||||
}
|
||||
|
||||
await gitAuthService['setupSSHKey'](credentialWithPassphrase)
|
||||
const env1 = gitAuthService['getSSHEnvironment']()
|
||||
expect(env1.GIT_SSH_COMMAND).toContain('sshpass -e')
|
||||
expect(env1.SSHPASS).toBe('pass1')
|
||||
|
||||
await gitAuthService['cleanupSSHKey']()
|
||||
|
||||
await gitAuthService['setupSSHKey'](credentialWithoutPassphrase)
|
||||
const env2 = gitAuthService['getSSHEnvironment']()
|
||||
expect(env2.GIT_SSH_COMMAND).not.toContain('sshpass')
|
||||
expect(env2.SSHPASS).toBeUndefined()
|
||||
|
||||
await gitAuthService['cleanupSSHKey']()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -54,6 +54,12 @@ describe('GitService', () => {
|
||||
database = {} as Database
|
||||
mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue({}),
|
||||
getSSHEnvironment: vi.fn().mockReturnValue({}),
|
||||
setupSSHKey: vi.fn().mockResolvedValue(undefined),
|
||||
cleanupSSHKey: vi.fn().mockResolvedValue(undefined),
|
||||
verifyHostKeyBeforeOperation: vi.fn().mockResolvedValue(true),
|
||||
setSSHPort: vi.fn(),
|
||||
setupSSHForRepoUrl: vi.fn().mockResolvedValue(false),
|
||||
} as unknown as GitAuthService
|
||||
mockSettingsService = {
|
||||
getSettings: vi.fn().mockReturnValue({
|
||||
@@ -104,18 +110,245 @@ describe('GitService', () => {
|
||||
|
||||
const result = await service.getStatus(1, database)
|
||||
|
||||
expect(result.files).toHaveLength(1)
|
||||
expect(result.files).toHaveLength(2)
|
||||
expect(result.files[0]).toEqual({ path: 'file.ts', status: 'modified', staged: true })
|
||||
expect(result.files[1]).toEqual({ path: 'file.ts', status: 'modified', staged: false })
|
||||
expect(result.hasChanges).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parsePorcelainOutput', () => {
|
||||
it('handles staged modification only (M )', () => {
|
||||
const output = 'M file.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({ path: 'file.ts', status: 'modified', staged: true })
|
||||
})
|
||||
|
||||
it('handles unstaged modification only ( M)', () => {
|
||||
const output = ' M file.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({ path: 'file.ts', status: 'modified', staged: false })
|
||||
})
|
||||
|
||||
it('handles both staged and unstaged modification (MM)', () => {
|
||||
const output = 'MM file.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0]).toEqual({ path: 'file.ts', status: 'modified', staged: true })
|
||||
expect(result[1]).toEqual({ path: 'file.ts', status: 'modified', staged: false })
|
||||
})
|
||||
|
||||
it('handles staged added file (A )', () => {
|
||||
const output = 'A newfile.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({ path: 'newfile.ts', status: 'added', staged: true })
|
||||
})
|
||||
|
||||
it('handles staged deleted file (D )', () => {
|
||||
const output = 'D oldfile.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({ path: 'oldfile.ts', status: 'deleted', staged: true })
|
||||
})
|
||||
|
||||
it('handles staged added then modified (AM)', () => {
|
||||
const output = 'AM newfile.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0]).toEqual({ path: 'newfile.ts', status: 'added', staged: true })
|
||||
expect(result[1]).toEqual({ path: 'newfile.ts', status: 'modified', staged: false })
|
||||
})
|
||||
|
||||
it('handles staged added then deleted (AD)', () => {
|
||||
const output = 'AD newfile.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0]).toEqual({ path: 'newfile.ts', status: 'added', staged: true })
|
||||
expect(result[1]).toEqual({ path: 'newfile.ts', status: 'deleted', staged: false })
|
||||
})
|
||||
|
||||
it('handles renamed file (R )', () => {
|
||||
const output = 'R old.ts -> new.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({ path: 'new.ts', status: 'renamed', staged: true, oldPath: 'old.ts' })
|
||||
})
|
||||
|
||||
it('handles copied file (C )', () => {
|
||||
const output = 'C original.ts -> copy.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({ path: 'copy.ts', status: 'copied', staged: true, oldPath: 'original.ts' })
|
||||
})
|
||||
|
||||
it('handles untracked file (??)', () => {
|
||||
const output = '?? untracked.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toEqual({ path: 'untracked.ts', status: 'untracked', staged: false })
|
||||
})
|
||||
|
||||
it('handles empty output', () => {
|
||||
const output = ''
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('handles multiple files with mixed statuses', () => {
|
||||
const output = 'M modified.ts\nA added.ts\n D unstaged.ts\nMM both.ts\n?? untracked.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(6)
|
||||
expect(result).toContainEqual({ path: 'modified.ts', status: 'modified', staged: true })
|
||||
expect(result).toContainEqual({ path: 'added.ts', status: 'added', staged: true })
|
||||
expect(result).toContainEqual({ path: 'unstaged.ts', status: 'deleted', staged: false })
|
||||
expect(result).toContainEqual({ path: 'both.ts', status: 'modified', staged: true })
|
||||
expect(result).toContainEqual({ path: 'both.ts', status: 'modified', staged: false })
|
||||
expect(result).toContainEqual({ path: 'untracked.ts', status: 'untracked', staged: false })
|
||||
})
|
||||
|
||||
it('ignores short lines', () => {
|
||||
const output = 'M file.ts\n\n A\n?? valid.ts'
|
||||
const result = (service as any).parsePorcelainOutput(output)
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0]).toEqual({ path: 'file.ts', status: 'modified', staged: true })
|
||||
expect(result[1]).toEqual({ path: 'valid.ts', status: 'untracked', staged: false })
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFileStatus', () => {
|
||||
it('returns clean status for file with no changes (empty output)', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('')
|
||||
|
||||
const result = await (service as any).getFileStatus('/path/to/repo', 'clean.ts', {})
|
||||
|
||||
expect(result).toEqual({ status: 'clean' })
|
||||
})
|
||||
|
||||
it('returns modified status for staged modified file', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('M modified.ts')
|
||||
|
||||
const result = await (service as any).getFileStatus('/path/to/repo', 'modified.ts', {})
|
||||
|
||||
expect(result).toEqual({ status: 'modified' })
|
||||
})
|
||||
|
||||
it('returns status for unstaged modified file', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue(' M modified.ts')
|
||||
|
||||
const result = await (service as any).getFileStatus('/path/to/repo', 'modified.ts', {})
|
||||
|
||||
expect(result).toEqual({ status: 'modified' })
|
||||
})
|
||||
|
||||
it('returns untracked status for untracked file', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('?? untracked.ts')
|
||||
|
||||
const result = await (service as any).getFileStatus('/path/to/repo', 'untracked.ts', {})
|
||||
|
||||
expect(result).toEqual({ status: 'untracked' })
|
||||
})
|
||||
|
||||
it('returns added status for staged added file', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('A new.ts')
|
||||
|
||||
const result = await (service as any).getFileStatus('/path/to/repo', 'new.ts', {})
|
||||
|
||||
expect(result).toEqual({ status: 'added' })
|
||||
})
|
||||
|
||||
it('returns deleted status for staged deleted file', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockResolvedValue('D deleted.ts')
|
||||
|
||||
const result = await (service as any).getFileStatus('/path/to/repo', 'deleted.ts', {})
|
||||
|
||||
expect(result).toEqual({ status: 'deleted' })
|
||||
})
|
||||
|
||||
it('returns clean status on error', async () => {
|
||||
const mockRepo = {
|
||||
id: 1,
|
||||
fullPath: '/path/to/repo',
|
||||
}
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockRejectedValue(new Error('git command failed'))
|
||||
|
||||
const result = await (service as any).getFileStatus('/path/to/repo', 'error.ts', {})
|
||||
|
||||
expect(result).toEqual({ status: 'clean' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFileDiff for clean files', () => {
|
||||
it('returns empty diff for clean file (no changes)', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
return Promise.resolve('')
|
||||
})
|
||||
|
||||
const result = await service.getFileDiff(1, 'clean.ts', database)
|
||||
|
||||
expect(result.status).toBe('modified')
|
||||
expect(result.diff).toBe('')
|
||||
expect(result.additions).toBe(0)
|
||||
expect(result.deletions).toBe(0)
|
||||
expect(result.isBinary).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFileDiff', () => {
|
||||
it('returns diff for untracked file', async () => {
|
||||
const mockRepo = { id: 1, fullPath: '/path/to/repo' }
|
||||
getRepoByIdMock.mockReturnValue(mockRepo as any)
|
||||
executeCommandMock.mockImplementation((args) => {
|
||||
if (args.includes('status')) return Promise.resolve('')
|
||||
if (args.includes('status')) return Promise.resolve('?? newfile.ts')
|
||||
if (args.includes('--no-index')) {
|
||||
return Promise.resolve(
|
||||
'diff --git a/dev/null b/newfile.ts\n' +
|
||||
|
||||
@@ -25,6 +25,20 @@ vi.mock('../../src/db/queries', () => ({
|
||||
deleteRepo,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/settings', () => ({
|
||||
SettingsService: vi.fn().mockImplementation(() => ({
|
||||
getSettings: vi.fn().mockReturnValue({ preferences: { gitCredentials: [] } }),
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/ssh-key-manager', () => ({
|
||||
parseSSHHost: vi.fn((url: string) => ({ user: 'git', host: url, port: null })),
|
||||
writeTemporarySSHKey: vi.fn(),
|
||||
buildSSHCommand: vi.fn(),
|
||||
buildSSHCommandWithKnownHosts: vi.fn(),
|
||||
cleanupSSHKey: vi.fn(),
|
||||
}))
|
||||
|
||||
const mockEnv = {
|
||||
GIT_TERMINAL_PROMPT: '0',
|
||||
LANG: 'en_US.UTF-8',
|
||||
@@ -33,6 +47,12 @@ const mockEnv = {
|
||||
|
||||
const mockGitAuthService = {
|
||||
getGitEnvironment: vi.fn().mockReturnValue(mockEnv),
|
||||
getSSHEnvironment: vi.fn().mockReturnValue({}),
|
||||
setupSSHKey: vi.fn(),
|
||||
cleanupSSHKey: vi.fn(),
|
||||
verifyHostKeyBeforeOperation: vi.fn().mockResolvedValue(true),
|
||||
setupSSHForRepoUrl: vi.fn().mockResolvedValue(false),
|
||||
setSSHPort: vi.fn(),
|
||||
} as unknown as GitAuthService
|
||||
|
||||
describe('repoService.cloneRepo auth env', () => {
|
||||
|
||||
@@ -4,6 +4,7 @@ beforeAll(() => {
|
||||
vi.stubEnv('NODE_ENV', 'test')
|
||||
vi.stubEnv('PORT', '3001')
|
||||
vi.stubEnv('DATABASE_PATH', ':memory:')
|
||||
vi.stubEnv('AUTH_SECRET', 'test-secret-for-encryption')
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
|
||||
@@ -209,9 +209,9 @@ describe('fetchGitHubUserInfo', () => {
|
||||
describe('findGitHubCredential', () => {
|
||||
it('should find GitHub credential in credentials array', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'gitlab', host: 'https://gitlab.com/', token: 'gitlab-token' },
|
||||
{ name: 'github', host: 'https://github.com/', token: 'github-token' },
|
||||
{ name: 'private', host: 'https://git.example.com/', token: 'private-token' },
|
||||
{ name: 'gitlab', host: 'https://gitlab.com/', type: 'pat', token: 'gitlab-token' },
|
||||
{ name: 'github', host: 'https://github.com/', type: 'pat', token: 'github-token' },
|
||||
{ name: 'private', host: 'https://git.example.com/', type: 'pat', token: 'private-token' },
|
||||
]
|
||||
|
||||
const result = findGitHubCredential(credentials)
|
||||
@@ -219,13 +219,14 @@ describe('findGitHubCredential', () => {
|
||||
expect(result).toEqual({
|
||||
name: 'github',
|
||||
host: 'https://github.com/',
|
||||
type: 'pat',
|
||||
token: 'github-token'
|
||||
})
|
||||
})
|
||||
|
||||
it('should not find GitHub credential with www subdomain', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://www.github.com/', token: 'github-token' },
|
||||
{ name: 'github', host: 'https://www.github.com/', type: 'pat', token: 'github-token' },
|
||||
]
|
||||
|
||||
const result = findGitHubCredential(credentials)
|
||||
@@ -241,8 +242,8 @@ describe('findGitHubCredential', () => {
|
||||
|
||||
it('should return null when no GitHub credential exists', () => {
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'gitlab', host: 'https://gitlab.com/', token: 'gitlab-token' },
|
||||
{ name: 'private', host: 'https://git.example.com/', token: 'private-token' },
|
||||
{ name: 'gitlab', host: 'https://gitlab.com/', type: 'pat', token: 'gitlab-token' },
|
||||
{ name: 'private', host: 'https://git.example.com/', type: 'pat', token: 'private-token' },
|
||||
]
|
||||
|
||||
const result = findGitHubCredential(credentials)
|
||||
@@ -273,7 +274,7 @@ describe('resolveGitIdentity', () => {
|
||||
it('should prioritize manual name but use GitHub email', async () => {
|
||||
const manual = { name: 'Custom Name', email: undefined }
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'gh-token' },
|
||||
{ name: 'github', host: 'https://github.com/', type: 'pat', token: 'gh-token' },
|
||||
]
|
||||
|
||||
const userResponse = {
|
||||
@@ -306,7 +307,7 @@ describe('resolveGitIdentity', () => {
|
||||
it('should use GitHub identity when no manual identity', async () => {
|
||||
const manual = undefined
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'gh-token' },
|
||||
{ name: 'github', host: 'https://github.com/', type: 'pat', token: 'gh-token' },
|
||||
]
|
||||
|
||||
const userResponse = {
|
||||
@@ -339,7 +340,7 @@ describe('resolveGitIdentity', () => {
|
||||
it('should use login as name when GitHub name is null', async () => {
|
||||
const manual = undefined
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'gh-token' },
|
||||
{ name: 'github', host: 'https://github.com/', type: 'pat', token: 'gh-token' },
|
||||
]
|
||||
|
||||
const userResponse = {
|
||||
@@ -372,7 +373,7 @@ describe('resolveGitIdentity', () => {
|
||||
it('should return partial identity when GitHub fails but manual has one field', async () => {
|
||||
const manual = { name: 'Only Name', email: undefined }
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'invalid-token' },
|
||||
{ name: 'github', host: 'https://github.com/', type: 'pat', token: 'invalid-token' },
|
||||
]
|
||||
|
||||
global.fetch = vi.fn() as any;
|
||||
@@ -399,7 +400,7 @@ describe('resolveGitIdentity', () => {
|
||||
it('should return null when both manual fields are empty and GitHub fails', async () => {
|
||||
const manual = { name: undefined, email: undefined }
|
||||
const credentials: GitCredential[] = [
|
||||
{ name: 'github', host: 'https://github.com/', token: 'invalid-token' },
|
||||
{ name: 'github', host: 'https://github.com/', type: 'pat', token: 'invalid-token' },
|
||||
]
|
||||
|
||||
global.fetch = vi.fn() as any;
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import * as fs from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { parseSSHHost, normalizeHostPort, parseHostPort, writeTemporarySSHKey, cleanupSSHKey, cleanupAllSSHKeys } from '../../src/utils/ssh-key-manager'
|
||||
import { getWorkspacePath } from '@opencode-manager/shared/config/env'
|
||||
|
||||
describe('SSH Host Parsing', () => {
|
||||
it('should parse git@host:path format', () => {
|
||||
const result = parseSSHHost('git@github.com:user/repo.git')
|
||||
expect(result.user).toBe('git')
|
||||
expect(result.host).toBe('github.com')
|
||||
expect(result.port).toBe('22')
|
||||
})
|
||||
|
||||
it('should parse ssh:// format', () => {
|
||||
const result = parseSSHHost('ssh://git@gitlab.com/user/repo.git')
|
||||
expect(result.user).toBe('git')
|
||||
expect(result.host).toBe('gitlab.com')
|
||||
expect(result.port).toBe('22')
|
||||
})
|
||||
|
||||
it('should parse ssh:// with custom port', () => {
|
||||
const result = parseSSHHost('ssh://git@git.example.com:2222/user/repo.git')
|
||||
expect(result.user).toBe('git')
|
||||
expect(result.host).toBe('git.example.com')
|
||||
expect(result.port).toBe('2222')
|
||||
})
|
||||
|
||||
it('should parse git@host:port:path format', () => {
|
||||
const result = parseSSHHost('git@github.com:22:user/repo.git')
|
||||
expect(result.user).toBe('git')
|
||||
expect(result.host).toBe('github.com')
|
||||
expect(result.port).toBe('22')
|
||||
})
|
||||
|
||||
it('should normalize host:port for non-standard ports', () => {
|
||||
expect(normalizeHostPort('github.com', '2222')).toBe('github.com:2222')
|
||||
expect(normalizeHostPort('github.com', '22')).toBe('github.com')
|
||||
expect(normalizeHostPort('github.com', undefined)).toBe('github.com')
|
||||
})
|
||||
|
||||
it('should parse host:port strings', () => {
|
||||
expect(parseHostPort('github.com:2222')).toEqual({ host: 'github.com', port: '2222' })
|
||||
expect(parseHostPort('github.com')).toEqual({ host: 'github.com', port: '22' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('SSH Key Validation', () => {
|
||||
describe('RSA Keys', () => {
|
||||
const rsaKey = `-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEAzR8u8I5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5
|
||||
-----END RSA PRIVATE KEY-----`
|
||||
|
||||
it('should accept RSA private key', async () => {
|
||||
const keyPath = await writeTemporarySSHKey(rsaKey, 'test-rsa')
|
||||
expect(keyPath).toBeTruthy()
|
||||
|
||||
const stats = await fs.stat(keyPath)
|
||||
const mode = stats.mode & 0o777
|
||||
expect(mode).toBe(0o600)
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
|
||||
it('should accept RSA public key', async () => {
|
||||
const rsaPublicKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
const keyPath = await writeTemporarySSHKey(rsaPublicKey, 'test-rsa-pub')
|
||||
expect(keyPath).toBeTruthy()
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ED25519 Keys', () => {
|
||||
const ed25519Key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
it('should accept ED25519 private key', async () => {
|
||||
const keyPath = await writeTemporarySSHKey(ed25519Key, 'test-ed25519')
|
||||
expect(keyPath).toBeTruthy()
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
|
||||
it('should accept ED25519 public key', async () => {
|
||||
const ed25519PublicKey = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test@test.com'
|
||||
const keyPath = await writeTemporarySSHKey(ed25519PublicKey, 'test-ed25519-pub')
|
||||
expect(keyPath).toBeTruthy()
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ECDSA Keys', () => {
|
||||
const ecdsaKey = `-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIP5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5Z5
|
||||
-----END EC PRIVATE KEY-----`
|
||||
|
||||
it('should accept ECDSA private key', async () => {
|
||||
const keyPath = await writeTemporarySSHKey(ecdsaKey, 'test-ecdsa')
|
||||
expect(keyPath).toBeTruthy()
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
|
||||
it('should accept ECDSA public key', async () => {
|
||||
const ecdsaPublicKey = 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEM/test@test.com'
|
||||
const keyPath = await writeTemporarySSHKey(ecdsaPublicKey, 'test-ecdsa-pub')
|
||||
expect(keyPath).toBeTruthy()
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
})
|
||||
|
||||
it('should reject invalid key format', async () => {
|
||||
const invalidKey = 'not a valid ssh key'
|
||||
await expect(writeTemporarySSHKey(invalidKey, 'test-invalid')).rejects.toThrow('Invalid SSH key format')
|
||||
})
|
||||
|
||||
it('should reject empty key', async () => {
|
||||
const emptyKey = ''
|
||||
await expect(writeTemporarySSHKey(emptyKey, 'test-empty')).rejects.toThrow('Invalid SSH key format')
|
||||
})
|
||||
|
||||
it('should set correct permissions on key file', async () => {
|
||||
const validKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
const keyPath = await writeTemporarySSHKey(validKey, 'test-perms')
|
||||
|
||||
const stats = await fs.stat(keyPath)
|
||||
const mode = stats.mode & 0o777
|
||||
expect(mode).toBe(0o600)
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SSH Key Cleanup', () => {
|
||||
it('should clean up individual key', async () => {
|
||||
const key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
const keyPath = await writeTemporarySSHKey(key, 'test-cleanup')
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
|
||||
await expect(fs.access(keyPath)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('should clean up all keys', async () => {
|
||||
const key1 = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test1@host'
|
||||
const key2 = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIQQ/test2@test.com'
|
||||
|
||||
await writeTemporarySSHKey(key1, 'test-cleanup-1')
|
||||
await writeTemporarySSHKey(key2, 'test-cleanup-2')
|
||||
|
||||
await cleanupAllSSHKeys()
|
||||
|
||||
const keysDir = join(getWorkspacePath(), '.ssh-keys')
|
||||
await expect(fs.access(keysDir)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('should handle cleanup of non-existent file gracefully', async () => {
|
||||
const nonExistentPath = '/tmp/non-existent-ssh-key-12345'
|
||||
|
||||
await expect(cleanupSSHKey(nonExistentPath)).resolves.not.toThrow()
|
||||
})
|
||||
|
||||
it('should handle cleanup of already cleaned up file gracefully', async () => {
|
||||
const key = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDRHw== test@host'
|
||||
const keyPath = await writeTemporarySSHKey(key, 'test-double-cleanup')
|
||||
|
||||
await cleanupSSHKey(keyPath)
|
||||
await expect(cleanupSSHKey(keyPath)).resolves.not.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,260 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const mockExecuteCommand = vi.fn()
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV: {
|
||||
AUTH: {
|
||||
SECRET: 'test-secret-for-encryption'
|
||||
},
|
||||
OPENCODE: {
|
||||
PORT: 5551
|
||||
},
|
||||
SERVER: {
|
||||
PORT: 5003
|
||||
}
|
||||
},
|
||||
getReposPath: vi.fn(() => '/tmp/test-repos'),
|
||||
getWorkspacePath: vi.fn(() => '/tmp/test-workspace')
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/process', () => ({
|
||||
executeCommand: mockExecuteCommand
|
||||
}))
|
||||
|
||||
vi.mock('fs', () => ({
|
||||
promises: {
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
unlink: vi.fn().mockResolvedValue(undefined)
|
||||
}
|
||||
}))
|
||||
|
||||
import { validateSSHPrivateKey } from '../../src/utils/ssh-validation'
|
||||
|
||||
describe('validateSSHPrivateKey', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockExecuteCommand.mockResolvedValue('ssh-ed25519 AAAAC...')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('valid key formats', () => {
|
||||
const validHeaders = [
|
||||
{ name: 'OPENSSH', header: '-----BEGIN OPENSSH PRIVATE KEY-----' },
|
||||
{ name: 'RSA', header: '-----BEGIN RSA PRIVATE KEY-----' },
|
||||
{ name: 'EC', header: '-----BEGIN EC PRIVATE KEY-----' },
|
||||
{ name: 'DSA', header: '-----BEGIN DSA PRIVATE KEY-----' },
|
||||
{ name: 'ED25519', header: '-----BEGIN ED25519 PRIVATE KEY-----' },
|
||||
{ name: 'PGP', header: '-----BEGIN PGP PRIVATE KEY BLOCK-----' }
|
||||
]
|
||||
|
||||
validHeaders.forEach(({ name, header }) => {
|
||||
it(`should accept valid ${name} key format`, async () => {
|
||||
const key = `${header}\n${'A'.repeat(100)}\n-----END ${name} PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('should accept properly formatted OPENSSH key', async () => {
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBmNkCQ0YDZiVJmHqMvK1PqjWxV4aRqK2Pm8RlV4aRqK2Pm8RlV4aRqK2Pm8RlV4
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('passphrase detection', () => {
|
||||
it('should detect key without passphrase', async () => {
|
||||
mockExecuteCommand.mockResolvedValue('ssh-ed25519 AAAAC3...')
|
||||
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.hasPassphrase).toBe(false)
|
||||
})
|
||||
|
||||
it('should detect key with passphrase via incorrect passphrase error', async () => {
|
||||
mockExecuteCommand.mockRejectedValue(new Error('incorrect passphrase supplied to decrypt private key'))
|
||||
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.hasPassphrase).toBe(true)
|
||||
})
|
||||
|
||||
it('should detect key with passphrase via failed error', async () => {
|
||||
mockExecuteCommand.mockRejectedValue(new Error('failed: incorrect passphrase supplied to decrypt private key'))
|
||||
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.hasPassphrase).toBe(true)
|
||||
})
|
||||
|
||||
it('should detect key with passphrase via Load key error', async () => {
|
||||
mockExecuteCommand.mockRejectedValue(new Error('Load key "/tmp/temp-ssh-key-123": bad passphrase'))
|
||||
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.hasPassphrase).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('invalid key rejection', () => {
|
||||
it('should reject key with invalid format', async () => {
|
||||
mockExecuteCommand.mockRejectedValue(new Error('invalid format'))
|
||||
|
||||
const key = `-----BEGIN INVALID KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END INVALID KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.error).toContain('Invalid SSH key')
|
||||
})
|
||||
|
||||
it('should reject corrupted key', async () => {
|
||||
mockExecuteCommand.mockRejectedValue(new Error('load key: invalid format'))
|
||||
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.error).toContain('Invalid SSH key')
|
||||
})
|
||||
})
|
||||
|
||||
describe('empty/null/undefined key handling', () => {
|
||||
it('should reject null key', async () => {
|
||||
const result = await validateSSHPrivateKey(null as unknown as string)
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.error).toBe('SSH key is required')
|
||||
})
|
||||
|
||||
it('should reject undefined key', async () => {
|
||||
const result = await validateSSHPrivateKey(undefined as unknown as string)
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.error).toBe('SSH key is required')
|
||||
})
|
||||
|
||||
it('should reject empty string', async () => {
|
||||
const result = await validateSSHPrivateKey('')
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.error).toBe('SSH key is required')
|
||||
})
|
||||
|
||||
it('should reject whitespace-only string', async () => {
|
||||
const result = await validateSSHPrivateKey(' \n\t ')
|
||||
|
||||
expect(result.valid).toBe(false)
|
||||
expect(result.error).toBe('SSH key cannot be empty')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
|
||||
describe('ssh-keygen command execution', () => {
|
||||
it('should call ssh-keygen with correct arguments', async () => {
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
await validateSSHPrivateKey(key)
|
||||
|
||||
expect(mockExecuteCommand).toHaveBeenCalled()
|
||||
const call = mockExecuteCommand.mock.calls[0]
|
||||
expect(call).toBeDefined()
|
||||
const args = call?.[0] as string[] | undefined
|
||||
expect(args?.[0]).toBe('ssh-keygen')
|
||||
expect(args?.[1]).toBe('-y')
|
||||
expect(args?.[2]).toBe('-P')
|
||||
expect(args?.[3]).toBe('')
|
||||
expect(args?.[4]).toBe('-f')
|
||||
})
|
||||
|
||||
it('should pass silent option to command execution', async () => {
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
await validateSSHPrivateKey(key)
|
||||
|
||||
expect(mockExecuteCommand).toHaveBeenCalled()
|
||||
const call = mockExecuteCommand.mock.calls[0]
|
||||
expect(call).toBeDefined()
|
||||
const options = call?.[1] as { silent?: boolean } | undefined
|
||||
expect(options?.silent).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('file cleanup after validation', () => {
|
||||
it('should complete validation successfully with cleanup', async () => {
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
})
|
||||
|
||||
it('should complete validation with passphrase detection with cleanup', async () => {
|
||||
mockExecuteCommand.mockRejectedValue(new Error('incorrect passphrase'))
|
||||
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
expect(result.hasPassphrase).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('temp file permission handling', () => {
|
||||
it('should complete validation which includes writing temp file', async () => {
|
||||
const key = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
${'A'.repeat(120)}
|
||||
-----END OPENSSH PRIVATE KEY-----`
|
||||
|
||||
const result = await validateSSHPrivateKey(key)
|
||||
|
||||
expect(result.valid).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
+15
-1
@@ -12,8 +12,9 @@ import { SettingsDialog } from './components/settings/SettingsDialog'
|
||||
import { useTheme } from './hooks/useTheme'
|
||||
import { TTSProvider } from './contexts/TTSContext'
|
||||
import { AuthProvider } from './contexts/AuthContext'
|
||||
import { EventProvider, usePermissions } from '@/contexts/EventContext'
|
||||
import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext'
|
||||
import { PermissionRequestDialog } from './components/session/PermissionRequestDialog'
|
||||
import { SSHHostKeyDialog } from './components/ssh/SSHHostKeyDialog'
|
||||
import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib/auth-loaders'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
@@ -25,6 +26,18 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
})
|
||||
|
||||
function SSHHostKeyDialogWrapper() {
|
||||
const { sshHostKey } = useEventContext()
|
||||
return (
|
||||
<SSHHostKeyDialog
|
||||
request={sshHostKey.request}
|
||||
onRespond={async (requestId, response) => {
|
||||
await sshHostKey.respond(requestId, response === 'accept')
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function PermissionDialogWrapper() {
|
||||
const {
|
||||
current: currentPermission,
|
||||
@@ -64,6 +77,7 @@ function AppShell() {
|
||||
<EventProvider>
|
||||
<Outlet />
|
||||
<PermissionDialogWrapper />
|
||||
<SSHHostKeyDialogWrapper />
|
||||
<SettingsDialog />
|
||||
<Toaster
|
||||
position="bottom-right"
|
||||
|
||||
@@ -181,6 +181,14 @@ export const settingsApi = {
|
||||
})
|
||||
},
|
||||
|
||||
testSSHConnection: async (host: string, sshPrivateKey: string, passphrase?: string): Promise<{ success: boolean; message: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/test-ssh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ host, sshPrivateKey, passphrase }),
|
||||
})
|
||||
},
|
||||
|
||||
getAgentsMd: async (): Promise<{ content: string }> => {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/agents-md`)
|
||||
},
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
|
||||
export function respondSSHHostKey(requestId: string, approved: boolean): Promise<{ success: boolean; error?: string }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/ssh/host-key/respond`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ requestId, response: approved ? 'accept' : 'reject' }),
|
||||
})
|
||||
}
|
||||
|
||||
export function getSSHHostKeyStatus(): Promise<{ success: boolean; pendingCount?: number; error?: string }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/ssh/host-key/status`)
|
||||
}
|
||||
@@ -179,6 +179,11 @@ export interface SSESessionErrorEvent {
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESSHHostKeyRequestEvent {
|
||||
type: 'ssh.host-key-request'
|
||||
properties: SSHHostKeyRequest
|
||||
}
|
||||
|
||||
export type SSEEvent =
|
||||
| SSEMessagePartUpdatedEvent
|
||||
| SSEMessageUpdatedEvent
|
||||
@@ -198,6 +203,7 @@ export type SSEEvent =
|
||||
| SSEQuestionRejectedEvent
|
||||
| SSEInstallationUpdatedEvent
|
||||
| SSEInstallationUpdateAvailableEvent
|
||||
| SSESSHHostKeyRequestEvent
|
||||
|
||||
export type ContentPart =
|
||||
| { type: 'text', content: string }
|
||||
@@ -216,3 +222,17 @@ export interface ImageAttachment {
|
||||
mime: string
|
||||
dataUrl: string
|
||||
}
|
||||
|
||||
export interface SSHHostKeyRequest {
|
||||
id: string
|
||||
requestId: string
|
||||
host: string
|
||||
ip?: string
|
||||
keyType: string
|
||||
fingerprint: string
|
||||
isKeyChanged?: boolean
|
||||
timestamp: number
|
||||
action: 'verify'
|
||||
}
|
||||
|
||||
export type SSHHostKeyResponse = 'accept' | 'reject'
|
||||
@@ -28,8 +28,13 @@ export interface CustomAgent {
|
||||
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 interface GitIdentity {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Lock, AlertCircle } from 'lucide-react'
|
||||
|
||||
interface PassphraseModalProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (passphrase: string) => void
|
||||
credentialName?: string
|
||||
}
|
||||
|
||||
export function PassphraseModal({ open, onOpenChange, onSubmit, credentialName = 'SSH key' }: PassphraseModalProps) {
|
||||
const [passphrase, setPassphrase] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setPassphrase('')
|
||||
setError(null)
|
||||
setTimeout(() => inputRef.current?.focus(), 100)
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!passphrase.trim()) {
|
||||
setError('Passphrase is required')
|
||||
return
|
||||
}
|
||||
|
||||
onSubmit(passphrase)
|
||||
setPassphrase('')
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[90%] sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Lock className="h-5 w-5" />
|
||||
SSH Key Passphrase Required
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter the passphrase for your <span className="font-medium">{credentialName}</span>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="passphrase">Passphrase</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id="passphrase"
|
||||
type="password"
|
||||
ref={inputRef}
|
||||
value={passphrase}
|
||||
onChange={(e) => {
|
||||
setPassphrase(e.target.value)
|
||||
setError(null)
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Enter your passphrase"
|
||||
className={error ? 'border-destructive' : ''}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-sm text-destructive flex items-center gap-1">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This passphrase is NOT stored and will be required each time you access this SSH key.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={!passphrase.trim()}>
|
||||
Submit
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Loader2, Key, Lock, AlertTriangle } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Alert } from '@/components/ui/alert'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import type { GitCredential } from '@/api/types/settings'
|
||||
|
||||
@@ -19,10 +21,16 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
|
||||
const [formData, setFormData] = useState<GitCredential>({
|
||||
name: '',
|
||||
host: '',
|
||||
type: 'pat',
|
||||
token: '',
|
||||
username: '',
|
||||
sshPrivateKey: '',
|
||||
passphrase: '',
|
||||
})
|
||||
const [tokenEdited, setTokenEdited] = useState(false)
|
||||
const [isTesting, setIsTesting] = useState(false)
|
||||
const [showPassphraseInput, setShowPassphraseInput] = useState(false)
|
||||
const [testPassphrase, setTestPassphrase] = useState('')
|
||||
|
||||
const maskToken = (token: string) => {
|
||||
if (!token) return ''
|
||||
@@ -33,13 +41,16 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setTokenEdited(false)
|
||||
setShowPassphraseInput(false)
|
||||
setTestPassphrase('')
|
||||
if (credential) {
|
||||
setFormData({
|
||||
...credential,
|
||||
token: ''
|
||||
sshPrivateKey: '',
|
||||
token: credential.type === 'pat' ? '' : credential.token
|
||||
})
|
||||
} else {
|
||||
setFormData({ name: '', host: 'https://github.com', token: '', username: '' })
|
||||
setFormData({ name: '', host: '', type: 'pat', token: '', username: '', sshPrivateKey: '', passphrase: '' })
|
||||
}
|
||||
}
|
||||
}, [open, credential])
|
||||
@@ -47,35 +58,77 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
|
||||
const handleSubmit = async (event?: React.MouseEvent) => {
|
||||
event?.preventDefault()
|
||||
event?.stopPropagation()
|
||||
|
||||
const isEditing = !!credential
|
||||
const tokenRequired = isEditing ? tokenEdited : true
|
||||
|
||||
if (!formData.name.trim() || !formData.host.trim() || (tokenRequired && !formData.token.trim())) {
|
||||
showToast.error('Please fill in all required fields')
|
||||
|
||||
if (!formData.name.trim() || !formData.host.trim()) {
|
||||
showToast.error('Name and host are required')
|
||||
return
|
||||
}
|
||||
|
||||
if (formData.type === 'pat') {
|
||||
if (!formData.token?.trim()) {
|
||||
showToast.error('Token is required for PAT type')
|
||||
return
|
||||
}
|
||||
} else if (formData.type === 'ssh') {
|
||||
if (!formData.sshPrivateKey?.trim()) {
|
||||
showToast.error('SSH key is required for SSH type')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const dataToSave: GitCredential = {
|
||||
...formData,
|
||||
token: (isEditing && !tokenEdited) ? credential.token : formData.token
|
||||
hasPassphrase: formData.type === 'ssh' ? Boolean(formData.passphrase?.trim()) : false
|
||||
}
|
||||
if (formData.type === 'pat' && credential?.token && !tokenEdited) {
|
||||
dataToSave.token = credential.token
|
||||
}
|
||||
await onSave(dataToSave)
|
||||
setFormData({ name: '', host: '', token: '', username: '' })
|
||||
setFormData({ name: '', host: '', type: 'pat', token: '', username: '', sshPrivateKey: '', passphrase: '' })
|
||||
onOpenChange(false)
|
||||
} catch {
|
||||
showToast.error('Failed to save credential')
|
||||
}
|
||||
}
|
||||
|
||||
const handleTestConnection = async () => {
|
||||
if (!formData.sshPrivateKey?.trim()) {
|
||||
showToast.error('Please enter an SSH key first')
|
||||
return
|
||||
}
|
||||
|
||||
setIsTesting(true)
|
||||
|
||||
try {
|
||||
const host = formData.host.replace(/^https?:\/\//, '').replace(/\/$/, '')
|
||||
const settingsApi = (await import('@/api/settings')).settingsApi
|
||||
const result = await settingsApi.testSSHConnection(
|
||||
host,
|
||||
formData.sshPrivateKey,
|
||||
testPassphrase || undefined
|
||||
)
|
||||
|
||||
if (result.success) {
|
||||
showToast.success(result.message)
|
||||
} else {
|
||||
showToast.error(result.message)
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to test SSH connection'
|
||||
showToast.error(message)
|
||||
} finally {
|
||||
setIsTesting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogContent className="max-w-lg z-[150]" overlayClassName="z-[140]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{credential ? 'Edit Git Credential' : 'Add Git Credential'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
|
||||
<form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-name">Name *</Label>
|
||||
@@ -85,52 +138,166 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||
disabled={isSaving}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-host">Host URL *</Label>
|
||||
<Label htmlFor="cred-type">Authentication Type</Label>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant={formData.type === 'pat' ? 'default' : 'outline'}
|
||||
onClick={() => setFormData({ ...formData, type: 'pat', sshPrivateKey: '', passphrase: '' })}
|
||||
disabled={isSaving}
|
||||
className="flex-1"
|
||||
>
|
||||
<Key className="h-4 w-4 mr-2" />
|
||||
PAT
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={formData.type === 'ssh' ? 'default' : 'outline'}
|
||||
onClick={() => setFormData({ ...formData, type: 'ssh', token: '' })}
|
||||
disabled={isSaving}
|
||||
className="flex-1"
|
||||
>
|
||||
<Lock className="h-4 w-4 mr-2" />
|
||||
SSH Key
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-host">Host *</Label>
|
||||
<Input
|
||||
id="cred-host"
|
||||
placeholder="https://github.com/"
|
||||
placeholder="github.com or git@github.com"
|
||||
value={formData.host}
|
||||
onChange={(e) => setFormData({ ...formData, host: e.target.value })}
|
||||
disabled={isSaving}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-token">
|
||||
Access Token {credential && !tokenEdited ? '(unchanged)' : '*'}
|
||||
</Label>
|
||||
<Input
|
||||
id="cred-token"
|
||||
type="password"
|
||||
placeholder={credential ? maskToken(credential.token) : 'Personal access token'}
|
||||
value={formData.token}
|
||||
onChange={(e) => {
|
||||
setTokenEdited(true)
|
||||
setFormData({ ...formData, token: e.target.value })
|
||||
}}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
{credential && !tokenEdited && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Leave empty to keep existing token
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{formData.type === 'pat' ? (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-token">
|
||||
Access Token {credential?.token && !tokenEdited ? '(unchanged)' : '*'}
|
||||
</Label>
|
||||
<Input
|
||||
id="cred-token"
|
||||
type="password"
|
||||
placeholder={credential?.token ? maskToken(credential.token) : 'Personal access token'}
|
||||
value={formData.token || ''}
|
||||
onChange={(e) => {
|
||||
setTokenEdited(true)
|
||||
setFormData({ ...formData, token: e.target.value })
|
||||
}}
|
||||
disabled={isSaving}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
{credential?.token && !tokenEdited && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Leave empty to keep existing token
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-username">Username (optional)</Label>
|
||||
<Input
|
||||
id="cred-username"
|
||||
placeholder="Auto-detected if empty"
|
||||
value={formData.username || ''}
|
||||
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-pat-username">Username (optional)</Label>
|
||||
<Input
|
||||
id="cred-pat-username"
|
||||
placeholder="Auto-detected if empty"
|
||||
value={formData.username || ''}
|
||||
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
||||
disabled={isSaving}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-ssh-key">SSH Private Key *</Label>
|
||||
<Textarea
|
||||
id="cred-ssh-key"
|
||||
placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
|
||||
value={formData.sshPrivateKey || ''}
|
||||
onChange={(e) => setFormData({ ...formData, sshPrivateKey: e.target.value })}
|
||||
disabled={isSaving}
|
||||
rows={8}
|
||||
className="font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Paste your private key content here
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setShowPassphraseInput(!showPassphraseInput)}
|
||||
disabled={isSaving}
|
||||
className="w-full"
|
||||
>
|
||||
{showPassphraseInput ? 'Remove' : 'Add'} Passphrase
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showPassphraseInput && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="cred-passphrase">Passphrase</Label>
|
||||
<Input
|
||||
id="cred-passphrase"
|
||||
type="password"
|
||||
placeholder="Enter passphrase for SSH key"
|
||||
value={formData.passphrase || ''}
|
||||
onChange={(e) => setFormData({ ...formData, passphrase: e.target.value })}
|
||||
disabled={isSaving}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This passphrase will be required for each git operation
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="test-passphrase">Passphrase for Test (if protected)</Label>
|
||||
<Input
|
||||
id="test-passphrase"
|
||||
type="password"
|
||||
placeholder="Enter passphrase to test connection"
|
||||
value={testPassphrase}
|
||||
onChange={(e) => setTestPassphrase(e.target.value)}
|
||||
disabled={isTesting || isSaving}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleTestConnection}
|
||||
disabled={isTesting || isSaving || !formData.sshPrivateKey?.trim()}
|
||||
className="w-full"
|
||||
>
|
||||
{isTesting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Test Connection
|
||||
</Button>
|
||||
|
||||
<Alert>
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<p className="text-sm font-medium">Security Notice</p>
|
||||
<p className="text-xs mt-1">
|
||||
Your private key will be encrypted at rest. Never share it with anyone.
|
||||
</p>
|
||||
</Alert>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-4">
|
||||
<Button
|
||||
@@ -143,7 +310,9 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSaving || !formData.name.trim() || !formData.host.trim() || (!credential && !formData.token.trim())}
|
||||
disabled={isSaving || !formData.name.trim() || !formData.host.trim() ||
|
||||
(formData.type === 'pat' && !formData.token?.trim()) ||
|
||||
(formData.type === 'ssh' && !formData.sshPrivateKey?.trim())}
|
||||
>
|
||||
{isSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{credential ? 'Update' : 'Add'}
|
||||
|
||||
@@ -45,6 +45,18 @@ export function GitSettings() {
|
||||
setIsCredentialDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleEditClick = (e: React.MouseEvent, index: number) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
openEditCredentialDialog(index)
|
||||
}
|
||||
|
||||
const handleDeleteClick = (e: React.MouseEvent, index: number) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
removeCredential(index)
|
||||
}
|
||||
|
||||
const saveCredential = async (credential: GitCredential) => {
|
||||
let newCredentials: GitCredential[]
|
||||
|
||||
@@ -216,10 +228,11 @@ export function GitSettings() {
|
||||
) : (
|
||||
<div className="border border-border rounded-lg overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50">
|
||||
<thead className="bg-muted/50">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium text-muted-foreground">Name</th>
|
||||
<th className="px-3 py-2 text-left font-medium text-muted-foreground hidden sm:table-cell">Host</th>
|
||||
<th className="px-3 py-2 text-left font-medium text-muted-foreground hidden sm:table-cell">Type</th>
|
||||
<th className="px-3 py-2 text-right font-medium text-muted-foreground">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -235,32 +248,37 @@ export function GitSettings() {
|
||||
<td className="px-3 py-2 text-muted-foreground hidden sm:table-cell">
|
||||
{cred.host}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<td className="px-3 py-2 text-muted-foreground hidden sm:table-cell">
|
||||
<span className="text-xs px-1.5 py-0.5 rounded bg-muted">
|
||||
{cred.type === 'ssh' ? 'SSH' : 'PAT'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0"
|
||||
onClick={(e) => handleEditClick(e, index)}
|
||||
disabled={isSaving}
|
||||
title="Edit"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0"
|
||||
onClick={() => openEditCredentialDialog(index)}
|
||||
className="h-7 w-7 p-0 text-destructive hover:text-destructive"
|
||||
onClick={(e) => handleDeleteClick(e, index)}
|
||||
disabled={isSaving}
|
||||
title="Edit"
|
||||
title="Delete"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-destructive hover:text-destructive"
|
||||
onClick={() => removeCredential(index)}
|
||||
disabled={isSaving}
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
|
||||
@@ -41,7 +41,10 @@ export function SettingsDialog() {
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') close()
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation()
|
||||
close()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', handleKeyDown)
|
||||
return () => document.removeEventListener('keydown', handleKeyDown)
|
||||
@@ -116,14 +119,14 @@ export function SettingsDialog() {
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="px-6 pb-6">
|
||||
<TabsContent value="account" className="mt-0"><AccountSettings /></TabsContent>
|
||||
<TabsContent value="general" className="mt-0"><GeneralSettings /></TabsContent>
|
||||
<TabsContent value="notifications" className="mt-0"><NotificationSettings /></TabsContent>
|
||||
<TabsContent value="voice" className="mt-0"><VoiceSettings /></TabsContent>
|
||||
<TabsContent value="git" className="mt-0"><GitSettings /></TabsContent>
|
||||
<TabsContent value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
|
||||
<TabsContent value="opencode" className="mt-0"><OpenCodeConfigManager /></TabsContent>
|
||||
<TabsContent value="providers" className="mt-0"><ProviderSettings /></TabsContent>
|
||||
<TabsContent key="account" value="account" className="mt-0"><AccountSettings /></TabsContent>
|
||||
<TabsContent key="general" value="general" className="mt-0"><GeneralSettings /></TabsContent>
|
||||
<TabsContent key="notifications" value="notifications" className="mt-0"><NotificationSettings /></TabsContent>
|
||||
<TabsContent key="voice" value="voice" className="mt-0"><VoiceSettings /></TabsContent>
|
||||
<TabsContent key="git" value="git" className="mt-0"><GitSettings /></TabsContent>
|
||||
<TabsContent key="shortcuts" value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
|
||||
<TabsContent key="opencode" value="opencode" className="mt-0"><OpenCodeConfigManager /></TabsContent>
|
||||
<TabsContent key="providers" value="providers" className="mt-0"><ProviderSettings /></TabsContent>
|
||||
</div>
|
||||
</div>
|
||||
</Tabs>
|
||||
@@ -156,41 +159,41 @@ export function SettingsDialog() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-32">
|
||||
{mobileView === 'menu' && (
|
||||
<div className="space-y-3">
|
||||
{menuItems.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => {
|
||||
setMobileView(item.id as SettingsView)
|
||||
setActiveTab(item.id as SettingsView)
|
||||
}}
|
||||
className="w-full bg-gradient-to-br from-card to-card-hover border border-border rounded-xl p-4 hover:border-border transition-all duration-200 text-left"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-3 bg-accent rounded-lg">
|
||||
<item.icon className="w-6 h-6 text-blue-600 dark:text-blue-400" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-foreground mb-1">{item.label}</h3>
|
||||
<p className="text-sm text-muted-foreground">{item.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-32">
|
||||
{mobileView === 'menu' && (
|
||||
<div className="space-y-3">
|
||||
{menuItems.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => {
|
||||
setMobileView(item.id as SettingsView)
|
||||
setActiveTab(item.id as SettingsView)
|
||||
}}
|
||||
className="w-full bg-gradient-to-br from-card to-card-hover border border-border rounded-xl p-4 hover:border-border transition-all duration-200 text-left"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-3 bg-accent rounded-lg">
|
||||
<item.icon className="w-6 h-6 text-blue-600 dark:text-blue-400" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-foreground mb-1">{item.label}</h3>
|
||||
<p className="text-sm text-muted-foreground">{item.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{mobileView === 'account' && <AccountSettings />}
|
||||
{mobileView === 'general' && <GeneralSettings />}
|
||||
{mobileView === 'notifications' && <NotificationSettings />}
|
||||
{mobileView === 'voice' && <VoiceSettings />}
|
||||
{mobileView === 'git' && <GitSettings />}
|
||||
{mobileView === 'shortcuts' && <KeyboardShortcuts />}
|
||||
{mobileView === 'opencode' && <OpenCodeConfigManager />}
|
||||
{mobileView === 'providers' && <ProviderSettings />}
|
||||
</div>
|
||||
{mobileView === 'account' && <div key="account"><AccountSettings /></div>}
|
||||
{mobileView === 'general' && <div key="general"><GeneralSettings /></div>}
|
||||
{mobileView === 'notifications' && <div key="notifications"><NotificationSettings /></div>}
|
||||
{mobileView === 'voice' && <div key="voice"><VoiceSettings /></div>}
|
||||
{mobileView === 'git' && <div key="git"><GitSettings /></div>}
|
||||
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
|
||||
{mobileView === 'opencode' && <div key="opencode"><OpenCodeConfigManager /></div>}
|
||||
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { Shield, ShieldAlert } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { SSHHostKeyRequest, SSHHostKeyResponse } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
interface SSHHostKeyDialogProps {
|
||||
request: SSHHostKeyRequest | null
|
||||
onRespond: (requestId: string, response: SSHHostKeyResponse) => Promise<void>
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export function SSHHostKeyDialog({
|
||||
request,
|
||||
onRespond,
|
||||
open: parentOpen,
|
||||
onOpenChange,
|
||||
timeoutMs = 120_000
|
||||
}: SSHHostKeyDialogProps) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [timeRemaining, setTimeRemaining] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (!request) {
|
||||
setTimeRemaining(0)
|
||||
return
|
||||
}
|
||||
|
||||
const elapsed = Date.now() - request.timestamp
|
||||
const remaining = Math.max(0, timeoutMs - elapsed)
|
||||
setTimeRemaining(Math.ceil(remaining / 1000))
|
||||
|
||||
const interval = setInterval(() => {
|
||||
const currentElapsed = Date.now() - request.timestamp
|
||||
const currentRemaining = Math.max(0, timeoutMs - currentElapsed)
|
||||
setTimeRemaining(Math.ceil(currentRemaining / 1000))
|
||||
|
||||
if (currentRemaining <= 0) {
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [request, timeoutMs])
|
||||
|
||||
if (!request) return null
|
||||
if (parentOpen === false) return null
|
||||
|
||||
const handleResponse = async (response: SSHHostKeyResponse) => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await onRespond(request.id, response)
|
||||
if (response === 'accept') {
|
||||
showToast.success('Host key accepted')
|
||||
}
|
||||
} catch {
|
||||
showToast.error('Failed to respond to host key request. Please try again.')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const formatTime = (seconds: number): string => {
|
||||
const mins = Math.floor(seconds / 60)
|
||||
const secs = seconds % 60
|
||||
return `${mins}:${secs.toString().padStart(2, '0')}`
|
||||
}
|
||||
|
||||
const isExpired = timeRemaining === 0
|
||||
const WarningIcon = request.isKeyChanged ? ShieldAlert : Shield
|
||||
|
||||
return (
|
||||
<Dialog open={parentOpen ?? true} onOpenChange={onOpenChange ?? (() => {})}>
|
||||
<DialogContent className="max-w-[calc(100vw-2rem)] sm:max-w-md p-4 sm:p-6">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2 flex-wrap">
|
||||
<WarningIcon className={cn(
|
||||
"h-5 w-5",
|
||||
request.isKeyChanged ? "text-red-500" : "text-amber-500"
|
||||
)} />
|
||||
<span>{request.isKeyChanged ? 'Host Key Changed' : 'Verify SSH Host Key'}</span>
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{request.isKeyChanged
|
||||
? 'WARNING: The host key for this server has changed!'
|
||||
: 'Verify the authenticity of this SSH server before connecting.'}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-3">
|
||||
{request.isKeyChanged && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription className="text-sm">
|
||||
<strong>Security Warning:</strong> This could indicate a man-in-the-middle attack.
|
||||
Only proceed if you are certain the server is legitimate.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between items-start">
|
||||
<span className="text-muted-foreground">Host:</span>
|
||||
<span className="font-mono font-medium">{request.host}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-start">
|
||||
<span className="text-muted-foreground">IP Address:</span>
|
||||
<span className="font-mono font-medium">{request.ip}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-start">
|
||||
<span className="text-muted-foreground">Key Type:</span>
|
||||
<span className="font-mono font-medium">{request.keyType}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-start gap-4">
|
||||
<span className="text-muted-foreground">Fingerprint:</span>
|
||||
<div className="flex items-center gap-2 flex-1 justify-end">
|
||||
<span className="font-mono text-xs break-all">{request.fingerprint}</span>
|
||||
<CopyButton content={request.fingerprint} variant="ghost" iconSize="sm" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<div className="flex justify-between">
|
||||
<span>Auto-reject in:</span>
|
||||
<span className={cn("font-mono", isExpired && "text-red-500")}>
|
||||
{isExpired ? 'Expired' : formatTime(timeRemaining)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex-col-reverse gap-2 sm:flex-row sm:gap-2 mt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleResponse('reject')}
|
||||
disabled={isLoading || isExpired}
|
||||
className="w-full sm:flex-1 text-sm h-9 sm:h-10"
|
||||
>
|
||||
{isLoading ? 'Processing...' : 'Reject'}
|
||||
</Button>
|
||||
<Button
|
||||
variant={request.isKeyChanged ? 'destructive' : 'default'}
|
||||
onClick={() => handleResponse('accept')}
|
||||
disabled={isLoading || isExpired}
|
||||
className="w-full sm:flex-1 text-sm h-9 sm:h-10"
|
||||
>
|
||||
{isLoading ? 'Processing...' : 'Accept'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -32,17 +32,18 @@ interface DialogContentProps
|
||||
hideCloseButton?: boolean
|
||||
fullscreen?: boolean
|
||||
mobileFullscreen?: boolean
|
||||
overlayClassName?: string
|
||||
}
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
DialogContentProps
|
||||
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, ...props }, ref) => {
|
||||
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, overlayClassName, ...props }, ref) => {
|
||||
const isMobileFullscreenMode = fullscreen || mobileFullscreen
|
||||
|
||||
return (
|
||||
<DialogPortal>
|
||||
{!fullscreen && <DialogOverlay />}
|
||||
{!fullscreen && <DialogOverlay className={overlayClassName} />}
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
aria-describedby={undefined}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useNavigate, useLocation } from 'react-router-dom'
|
||||
import { useQueryClient, useQuery } from '@tanstack/react-query'
|
||||
import { OpenCodeClient } from '@/api/opencode'
|
||||
import { listRepos } from '@/api/repos'
|
||||
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent } from '@/api/types'
|
||||
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { subscribeToSSE, addSSEDirectory, ensureSSEConnected } from '@/lib/sseManager'
|
||||
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||
@@ -13,7 +13,13 @@ import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessi
|
||||
type PermissionsBySession = Record<string, PermissionRequest[]>
|
||||
type QuestionsBySession = Record<string, QuestionRequest[]>
|
||||
|
||||
interface SSHHostKeyState {
|
||||
request: SSHHostKeyRequest | null
|
||||
respond: (requestId: string, approved: boolean) => Promise<void>
|
||||
}
|
||||
|
||||
interface EventContextValue {
|
||||
sshHostKey: SSHHostKeyState
|
||||
permissions: {
|
||||
current: PermissionRequest | null
|
||||
pendingCount: number
|
||||
@@ -45,6 +51,18 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
|
||||
const [sshHostKeyRequest, setSSHHostKeyRequest] = useState<SSHHostKeyRequest | null>(null)
|
||||
|
||||
const respondToSSHHostKey = useCallback(async (requestId: string, approved: boolean) => {
|
||||
try {
|
||||
const { respondSSHHostKey } = await import('@/api/ssh')
|
||||
await respondSSHHostKey(requestId, approved)
|
||||
setSSHHostKeyRequest(null)
|
||||
} catch {
|
||||
showToast.error('Failed to respond to SSH host key verification')
|
||||
}
|
||||
}, [])
|
||||
|
||||
const [permissionsBySession, setPermissionsBySession] = useState<PermissionsBySession>({})
|
||||
const [questionsBySession, setQuestionsBySession] = useState<QuestionsBySession>({})
|
||||
const [showPermissionDialog, setShowPermissionDialog] = useState(true)
|
||||
@@ -272,6 +290,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
addQuestion(event.properties as QuestionRequest)
|
||||
}
|
||||
break
|
||||
case 'ssh.host-key-request':
|
||||
if ('requestId' in event.properties && 'host' in event.properties) {
|
||||
setSSHHostKeyRequest(event.properties as SSHHostKeyRequest)
|
||||
}
|
||||
break
|
||||
case 'question.replied':
|
||||
case 'question.rejected':
|
||||
if ('requestID' in event.properties && 'sessionID' in event.properties) {
|
||||
@@ -325,6 +348,10 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
}, [repos, fetchInitialPendingData])
|
||||
|
||||
const value: EventContextValue = useMemo(() => ({
|
||||
sshHostKey: {
|
||||
request: sshHostKeyRequest,
|
||||
respond: respondToSSHHostKey,
|
||||
},
|
||||
permissions: {
|
||||
current: currentPermission,
|
||||
pendingCount: allPermissions.length,
|
||||
@@ -348,6 +375,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
getRepoIdForSession,
|
||||
getClient,
|
||||
}), [
|
||||
sshHostKeyRequest,
|
||||
respondToSSHHostKey,
|
||||
currentPermission,
|
||||
allPermissions.length,
|
||||
respondToPermission,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
|
||||
interface PassphraseRequest {
|
||||
type: 'passphrase-request'
|
||||
credentialName: string
|
||||
host: string
|
||||
}
|
||||
|
||||
interface UsePassphraseHandlerProps {
|
||||
enabled?: boolean
|
||||
onSubmit?: (passphrase: string) => void
|
||||
}
|
||||
|
||||
export function usePassphraseHandler({ enabled = true, onSubmit }: UsePassphraseHandlerProps = {}) {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [credentialName, setCredentialName] = useState<string>('SSH key')
|
||||
const [host, setHost] = useState<string>('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return
|
||||
|
||||
const handlePassphraseRequest = (event: MessageEvent) => {
|
||||
const data = event.data as PassphraseRequest
|
||||
if (data.type === 'passphrase-request') {
|
||||
setCredentialName(data.credentialName)
|
||||
setHost(data.host)
|
||||
setIsOpen(true)
|
||||
setError(null)
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('message', handlePassphraseRequest)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('message', handlePassphraseRequest)
|
||||
}
|
||||
}, [enabled])
|
||||
|
||||
const handleSubmitPassphrase = useCallback((passphrase: string) => {
|
||||
try {
|
||||
onSubmit?.(passphrase)
|
||||
setIsOpen(false)
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to submit passphrase')
|
||||
}
|
||||
}, [onSubmit])
|
||||
|
||||
const sendPassphraseResponse = useCallback((passphrase: string) => {
|
||||
window.postMessage({
|
||||
type: 'passphrase-response',
|
||||
passphrase
|
||||
}, '*')
|
||||
}, [])
|
||||
|
||||
const handleSubmit = useCallback((passphrase: string) => {
|
||||
sendPassphraseResponse(passphrase)
|
||||
handleSubmitPassphrase(passphrase)
|
||||
}, [sendPassphraseResponse, handleSubmitPassphrase])
|
||||
|
||||
return {
|
||||
isOpen,
|
||||
credentialName,
|
||||
host,
|
||||
error,
|
||||
onSubmit: handleSubmit,
|
||||
onOpenChange: setIsOpen
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { useEventContext } from '@/contexts/EventContext'
|
||||
|
||||
export function useSSH() {
|
||||
const { sshHostKey } = useEventContext()
|
||||
return sshHostKey
|
||||
}
|
||||
@@ -18,7 +18,7 @@ export function useSettingsDialogUrl(): UseSettingsDialogUrlReturn {
|
||||
|
||||
const searchParams = new URLSearchParams(location.search)
|
||||
const isOpen = searchParams.get('settings') === 'open'
|
||||
const activeTab = (searchParams.get('tab') as Tab) || 'menu'
|
||||
const activeTab = (searchParams.get('tab') as Tab) || 'account'
|
||||
|
||||
const open = useCallback(() => {
|
||||
const newParams = new URLSearchParams(location.search)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "opencode-manager",
|
||||
"version": "0.8.25",
|
||||
"version": "0.8.26",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@10.28.1",
|
||||
|
||||
@@ -5,3 +5,4 @@ export * from './opencode'
|
||||
export * from './auth'
|
||||
export * from './sse'
|
||||
export * from './notifications'
|
||||
export * from './ssh'
|
||||
@@ -89,8 +89,13 @@ export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
|
||||
export const GitCredentialSchema = z.object({
|
||||
name: z.string(),
|
||||
host: z.string(),
|
||||
token: z.string(),
|
||||
type: z.enum(['pat', 'ssh']).default('pat'),
|
||||
token: z.string().optional(),
|
||||
sshPrivateKey: z.string().optional(),
|
||||
sshPrivateKeyEncrypted: z.string().optional(),
|
||||
hasPassphrase: z.boolean().optional(),
|
||||
username: z.string().optional(),
|
||||
passphrase: z.string().optional(),
|
||||
});
|
||||
|
||||
export type GitCredential = z.infer<typeof GitCredentialSchema>;
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const SSHHostKeyRequestSchema = z.object({
|
||||
id: z.string(),
|
||||
host: z.string(),
|
||||
ip: z.string(),
|
||||
keyType: z.string(),
|
||||
fingerprint: z.string(),
|
||||
timestamp: z.number(),
|
||||
isKeyChanged: z.boolean()
|
||||
})
|
||||
|
||||
export const SSHHostKeyResponseSchema = z.enum(['accept', 'reject'])
|
||||
|
||||
export const TrustedSSHHostSchema = z.object({
|
||||
id: z.number(),
|
||||
host: z.string(),
|
||||
key_type: z.string(),
|
||||
fingerprint: z.string(),
|
||||
created_at: z.number(),
|
||||
updated_at: z.number()
|
||||
})
|
||||
|
||||
export type SSHHostKeyRequest = z.infer<typeof SSHHostKeyRequestSchema>
|
||||
export type SSHHostKeyResponse = z.infer<typeof SSHHostKeyResponseSchema>
|
||||
export type TrustedSSHHost = z.infer<typeof TrustedSSHHostSchema>
|
||||
@@ -77,3 +77,6 @@ export interface ErrorResponse {
|
||||
export interface SuccessResponse {
|
||||
success: boolean
|
||||
}
|
||||
|
||||
export type { SSHHostKeyRequest, SSHHostKeyResponse, TrustedSSHHost } from '../schemas/ssh'
|
||||
export type { GitCredential } from '../schemas/settings'
|
||||
@@ -0,0 +1 @@
|
||||
export type { SSHHostKeyRequest, SSHHostKeyResponse, TrustedSSHHost } from '../schemas/ssh'
|
||||
Reference in new issue
Block a user