mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +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,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user