refactor: extract CredentialProvider service and consolidate git-auth utilities (#283)

* refactor: extract CredentialProvider service and consolidate git-auth utilities

* refactor: add git-credentials route and gh env plugin, pass internal token to OpenCode

* refactor: update credential provider integration and git route

* refactor: integrate credential provider across git auth, routes, and IPC
This commit is contained in:
Chris Scott committed 2026-06-20 23:20:39 -04:00
1 parent ba08f5c24a
commit 7c8a4fe64c
31 files changed
+1136 -132

No files matched your search

+9 -1
View File
@@ -5,6 +5,8 @@ import fs from 'fs'
interface AskpassRequest {
askpassType: 'https' | 'ssh'
argv: string[]
cwd?: string
repoId?: number
}
function fatal(err: unknown): never {
@@ -86,7 +88,13 @@ function main(argv: string[]): void {
process.exit(1)
})
const requestPayload: AskpassRequest = { askpassType, argv }
const repoId = process.env['OCM_GIT_REPO_ID'] ? Number(process.env['OCM_GIT_REPO_ID']) : undefined
const requestPayload: AskpassRequest = {
askpassType,
argv,
cwd: process.env['OCM_GIT_REPO_CWD'],
repoId: Number.isFinite(repoId) ? repoId : undefined,
}
console.error('[askpass-main] Sending request:', JSON.stringify(requestPayload))
req.write(JSON.stringify(requestPayload))
req.end()
+51
View File
@@ -21,6 +21,8 @@ interface RepoRow {
is_local?: number
}
const REPO_GIT_CREDENTIAL_SETTING_KEY = 'gitCredentialId'
function rowToRepo(row: RepoRow): Repo {
const fullPath = row.source_path || path.join(getReposPath(), row.local_path)
@@ -42,6 +44,55 @@ function rowToRepo(row: RepoRow): Repo {
}
}
export function getRepoSetting(db: Database, repoId: number, key: string): string | null {
const row = db
.prepare('SELECT value FROM repo_settings WHERE repo_id = ? AND key = ?')
.get(repoId, key) as { value: string } | undefined
return row?.value ?? null
}
export function setRepoSetting(db: Database, repoId: number, key: string, value: string | null): void {
const now = Date.now()
const updateSetting = db.transaction(() => {
if (value === null || value === '') {
db.prepare('DELETE FROM repo_settings WHERE repo_id = ? AND key = ?').run(repoId, key)
return
}
db.prepare(`
INSERT INTO repo_settings (repo_id, key, value, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(repo_id, key) DO UPDATE SET
value = excluded.value,
updated_at = excluded.updated_at
`).run(repoId, key, value, now)
})
updateSetting()
}
export function getRepoGitCredentialId(db: Database, repoId: number): string | null {
return getRepoSetting(db, repoId, REPO_GIT_CREDENTIAL_SETTING_KEY)
}
export function setRepoGitCredentialId(db: Database, repoId: number, credentialId: string | null): void {
setRepoSetting(db, repoId, REPO_GIT_CREDENTIAL_SETTING_KEY, credentialId)
}
export function getRepoByDirectory(db: Database, directory: string): Repo | null {
const resolvedDirectory = path.resolve(directory)
const repos = listRepos(db)
return repos
.filter((repo) => {
const resolvedRepoPath = path.resolve(repo.fullPath)
const relativePath = path.relative(resolvedRepoPath, resolvedDirectory)
return relativePath === '' || (!!relativePath && !relativePath.startsWith('..') && !path.isAbsolute(relativePath))
})
.sort((a, b) => b.fullPath.length - a.fullPath.length)[0] ?? null
}
const TABLES_WITH_REPO_ID = ['schedule_jobs', 'schedule_runs', 'repo_settings'] as const
type RepoIdTable = typeof TABLES_WITH_REPO_ID[number]
+18 -78
View File
@@ -1,9 +1,7 @@
import * as path from 'path'
import { fileURLToPath } from 'url'
import type { IPCServer, IPCHandler } from './ipcServer'
import type { Database } from 'bun:sqlite'
import { SettingsService } from '../services/settings'
import type { GitCredential } from '@opencode-manager/shared'
import { CredentialProvider } from '../services/credential-provider'
import { logger } from '../utils/logger'
const __filename = fileURLToPath(import.meta.url)
@@ -17,6 +15,8 @@ interface Credentials {
interface AskpassRequest {
askpassType: 'https' | 'ssh'
argv: string[]
cwd?: string
repoId?: number
}
export class AskpassHandler implements IPCHandler {
@@ -25,7 +25,7 @@ export class AskpassHandler implements IPCHandler {
constructor(
private ipcServer: IPCServer | undefined,
private database: Database
private credentialProvider: CredentialProvider
) {
const scriptsDir = path.join(__dirname, '../../scripts')
@@ -49,13 +49,14 @@ export class AskpassHandler implements IPCHandler {
async handle(request: AskpassRequest): Promise<string> {
logger.info(`Askpass request received: type=${request.askpassType}, argv=${JSON.stringify(request.argv)}`)
if (request.askpassType === 'https') {
return this.handleHttpsAskpass(request.argv)
return this.handleHttpsAskpass(request)
}
return this.handleSshAskpass()
}
private async handleHttpsAskpass(argv: string[]): Promise<string> {
const request = argv[2] || ''
private async handleHttpsAskpass(request: AskpassRequest): Promise<string> {
const { argv } = request
const prompt = argv[2] || ''
const host = argv[4]?.replace(/^["']+|["':]+$/g, '') || ''
let authority = ''
@@ -66,18 +67,22 @@ export class AskpassHandler implements IPCHandler {
authority = host
}
const isPassword = /password/i.test(request)
const isPassword = /password/i.test(prompt)
const cached = this.cache.get(authority)
const cacheKey = `${authority}:${request.repoId ?? ''}:${request.cwd ?? ''}`
const cached = this.cache.get(cacheKey)
if (cached && isPassword) {
this.cache.delete(authority)
this.cache.delete(cacheKey)
return cached.password
}
const credentials = await this.getCredentialsForHost(authority)
const credentials = this.credentialProvider.getPatCredentialForHost(authority, {
cwd: request.cwd,
repoId: request.repoId,
})
if (credentials) {
this.cache.set(authority, credentials)
setTimeout(() => this.cache.delete(authority), 60_000)
this.cache.set(cacheKey, credentials)
setTimeout(() => this.cache.delete(cacheKey), 60_000)
return isPassword ? credentials.password : credentials.username
}
@@ -88,71 +93,6 @@ export class AskpassHandler implements IPCHandler {
return ''
}
private normalizeHostname(host: string): string {
let normalized = host.toLowerCase().trim()
normalized = normalized.replace(/\/+$/, '')
if (!normalized.includes('://')) {
normalized = 'https://' + normalized
}
try {
const parsed = new URL(normalized)
return parsed.hostname
} catch {
const stripped = normalized.replace(/^https?:\/\//, '')
return stripped.split('/')[0] || stripped
}
}
private async getCredentialsForHost(hostname: string): Promise<Credentials | null> {
const normalizedRequest = this.normalizeHostname(hostname)
logger.info(`Looking up credentials for host: ${hostname} (normalized: ${normalizedRequest})`)
const settingsService = new SettingsService(this.database)
const settings = settingsService.getSettings('default')
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 PAT credential '${cred.name}' for ${hostname}`)
return {
username: cred.username || this.getDefaultUsername(cred.host),
password: cred.token || '',
}
}
}
if (gitCredentials.length > 0) {
logger.warn(`No credentials found for host: ${hostname}. Configured hosts: ${gitCredentials.map(c => c.host).join(', ')}`)
} else {
logger.warn(`No credentials found for host: ${hostname}. No git credentials configured.`)
}
return null
}
private getDefaultUsername(host: string): string {
try {
const parsed = new URL(host)
const hostname = parsed.hostname.toLowerCase()
if (hostname === 'github.com') {
return 'x-access-token'
}
if (hostname === 'gitlab.com' || hostname.includes('gitlab')) {
return 'oauth2'
}
return 'oauth2'
} catch {
return 'oauth2'
}
}
getEnv(): Record<string, string> {
return {
...this.env,
@@ -0,0 +1,14 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { CredentialProvider } from '../../services/credential-provider'
export function createInternalGitCredentialsRoutes(db: Database) {
const app = new Hono()
app.get('/gh-env', (c) => {
const provider = new CredentialProvider(db)
return c.json(provider.getGhCliEnv({ cwd: c.req.query('cwd') }))
})
return app
}
+2
View File
@@ -13,6 +13,7 @@ import { createInternalRepoSyncRoutes } from './repo-sync'
import { createInternalRepoMirrorRoutes as mirrorRoutes } from './repo-mirror'
import { createInternalOpenCodeWorkspacesRoutes } from './opencode-workspaces'
import { createInternalAssistantRoutes } from './assistant'
import { createInternalGitCredentialsRoutes } from './git-credentials'
export function createInternalRoutes(
db: Database,
@@ -34,5 +35,6 @@ export function createInternalRoutes(
app.route('/repos', repos)
app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db))
app.route('/assistant', createInternalAssistantRoutes(openCodeClient))
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
return app
}
+3 -1
View File
@@ -7,12 +7,14 @@ import { parseGitError } from '../utils/git-errors'
import { GitService } from '../services/git/GitService'
import type { GitAuthService } from '../services/git-auth'
import { SettingsService } from '../services/settings'
import { CredentialProvider } from '../services/credential-provider'
import type { GitStatusResponse } from '../types/git'
export function createRepoGitRoutes(database: Database, gitAuthService: GitAuthService) {
const app = new Hono()
const settingsService = new SettingsService(database)
const git = new GitService(gitAuthService, settingsService)
const credentialProvider = new CredentialProvider(database)
const git = new GitService(gitAuthService, settingsService, credentialProvider)
app.get('/:id/git/status', async (c) => {
try {
+40 -3
View File
@@ -3,7 +3,7 @@ import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { Database } from 'bun:sqlite'
import type { Repo } from '@opencode-manager/shared/types'
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema } from '@opencode-manager/shared/schemas'
import { listRepos, getRepoById, updateLastAccessed, updateRepoConfigName } from '../db/queries'
import { listRepos, getRepoById, updateLastAccessed, updateRepoConfigName, getRepoGitCredentialId, setRepoGitCredentialId } from '../db/queries'
import * as repoService from '../services/repo'
import * as archiveService from '../services/archive'
import { SettingsService } from '../services/settings'
@@ -36,6 +36,13 @@ function resolveRepo(database: Database, id: number): Repo | null {
return getRepoById(database, id) ?? (id === ASSISTANT_REPO_ID ? buildAssistantRepo() : null)
}
function withRepoSettings(database: Database, repo: Repo): Repo {
return {
...repo,
gitCredentialId: getRepoGitCredentialId(database, repo.id) ?? undefined,
}
}
export function createRepoRoutes(
database: Database,
gitAuthService: GitAuthService,
@@ -128,7 +135,7 @@ app.get('/', async (c) => {
repos.map(async (repo) => {
const env = gitAuthService.getGitEnvironment()
const currentBranch = repo.id === ASSISTANT_REPO_ID ? undefined : await repoService.getCurrentBranch(repo, env)
return { ...repo, currentBranch }
return { ...withRepoSettings(database, repo), currentBranch }
})
)
return c.json(reposWithCurrentBranch)
@@ -170,7 +177,7 @@ app.get('/', async (c) => {
const currentBranch = id === ASSISTANT_REPO_ID ? undefined : await repoService.getCurrentBranch(repo, gitAuthService.getGitEnvironment())
return c.json({ ...repo, currentBranch })
return c.json({ ...withRepoSettings(database, repo), currentBranch })
} catch (error: unknown) {
logger.error('Failed to get repo:', error)
return c.json({ error: getErrorMessage(error) }, 500)
@@ -212,6 +219,36 @@ app.get('/', async (c) => {
}
})
app.patch('/:id/git-credential', async (c) => {
try {
const id = parseInt(c.req.param('id'))
const repo = getRepoById(database, id)
if (!repo) {
return c.json({ error: 'Repo not found' }, 404)
}
const body = await c.req.json()
const credentialId = typeof body.credentialId === 'string' && body.credentialId.trim() !== ''
? body.credentialId.trim()
: null
if (credentialId) {
const settingsService = new SettingsService(database)
const settings = settingsService.getSettings()
if (!(settings.preferences.gitCredentials || []).some((credential) => credential.id === credentialId)) {
return c.json({ error: 'Credential not found' }, 400)
}
}
setRepoGitCredentialId(database, id, credentialId)
return c.json(withRepoSettings(database, repo))
} catch (error: unknown) {
logger.error('Failed to update repo git credential:', error)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
app.delete('/:id/workspaces/:workspaceId', async (c) => {
try {
const id = parseInt(c.req.param('id'))
+6 -1
View File
@@ -1,6 +1,7 @@
import { Hono, type Context } from 'hono'
import { z } from 'zod'
import { execSync, spawnSync } from 'child_process'
import { randomUUID } from 'crypto'
import { existsSync } from 'fs'
import { resolve, dirname } from 'path'
import type { Database } from 'bun:sqlite'
@@ -394,6 +395,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
const result: GitCredential = {
...cred,
id: cred.id || randomUUID(),
sshPrivateKeyEncrypted: encryptSecret(cred.sshPrivateKey),
hasPassphrase: validation.hasPassphrase,
passphrase: cred.passphrase ? encryptSecret(cred.passphrase) : undefined,
@@ -401,10 +403,13 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
delete result.sshPrivateKey
return result
}
return cred
return { ...cred, id: cred.id || randomUUID() }
})
)
validated.preferences.gitCredentials = validations
if (validated.preferences.defaultGitCredentialId && !validations.some((cred) => cred.id === validated.preferences.defaultGitCredentialId)) {
validated.preferences.defaultGitCredentialId = undefined
}
}
const currentSettings = settingsService.getSettings(userId)
@@ -0,0 +1,89 @@
import type { Database } from 'bun:sqlite'
import type { GitCredential } from '@opencode-manager/shared'
import { SettingsService } from './settings'
import {
findPatCredentialForHost,
getSSHCredentialsForHost,
createGitEnv,
findGitHubCredential,
type ResolvedGitCredential,
} from '../utils/git-auth'
import { getRepoByDirectory, getRepoGitCredentialId } from '../db/queries'
interface CredentialResolutionOptions {
cwd?: string
repoId?: number
}
export class CredentialProvider {
private settingsService: SettingsService
private database: Database
constructor(database: Database) {
this.database = database
this.settingsService = new SettingsService(database)
}
getGitCredentials(): GitCredential[] {
const settings = this.settingsService.getSettings('default')
return (settings.preferences.gitCredentials || []) as GitCredential[]
}
getGitCredentialById(credentialId: string | undefined): GitCredential | null {
if (!credentialId) return null
return this.getGitCredentials().find((credential) => credential.id === credentialId) ?? null
}
getPatCredentialForHost(hostname: string, options: CredentialResolutionOptions = {}): ResolvedGitCredential | null {
const credentials = this.getGitCredentials()
const selectedCredential = this.getSelectedCredential(options, credentials)
const selectedMatch = selectedCredential ? findPatCredentialForHost([selectedCredential], hostname) : null
return selectedMatch ?? findPatCredentialForHost(credentials, hostname)
}
getSshCredentialsForHost(host: string): GitCredential[] {
return getSSHCredentialsForHost(this.getGitCredentials(), host)
}
getSshCredentialsWithPrivateKey(): GitCredential[] {
return this.getGitCredentials().filter((cred) => cred.type === 'ssh' && cred.sshPrivateKeyEncrypted)
}
getGitEnv(): Record<string, string> {
return createGitEnv(this.getGitCredentials())
}
getGhCliEnv(options: CredentialResolutionOptions = {}): Record<string, string> {
const credential = this.getGhCliCredential(options)
if (!credential?.token) return {}
return { GH_TOKEN: credential.token, GITHUB_TOKEN: credential.token }
}
private getGhCliCredential(options: CredentialResolutionOptions): GitCredential | null {
const credentials = this.getGitCredentials()
const selectedCredential = this.getSelectedCredential(options, credentials)
if (this.isGithubPatCredential(selectedCredential)) return selectedCredential
return findGitHubCredential(credentials)
}
private getSelectedCredential(options: CredentialResolutionOptions, credentials: GitCredential[]): GitCredential | null {
const repoCredential = this.getRepoCredential(options, credentials)
if (repoCredential) return repoCredential
const settings = this.settingsService.getSettings('default')
return credentials.find((credential) => credential.id === settings.preferences.defaultGitCredentialId) ?? null
}
private getRepoCredential(options: CredentialResolutionOptions, credentials: GitCredential[]): GitCredential | null {
const repoId = options.repoId ?? (options.cwd ? getRepoByDirectory(this.database, options.cwd)?.id : undefined)
if (!repoId) return null
const credentialId = getRepoGitCredentialId(this.database, repoId)
return credentials.find((credential) => credential.id === credentialId) ?? null
}
private isGithubPatCredential(credential: GitCredential | null): credential is GitCredential {
return !!credential && credential.type !== 'ssh' && findGitHubCredential([credential]) === credential
}
}
+6 -7
View File
@@ -4,10 +4,10 @@ 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, normalizeSSHUrl, extractHostFromSSHUrl, getSSHCredentialsForHost } from '../utils/git-auth'
import { isSSHUrl, normalizeSSHUrl, extractHostFromSSHUrl } from '../utils/git-auth'
import type { GitCredential } from '@opencode-manager/shared'
import { logger } from '../utils/logger'
import { SettingsService } from './settings'
import { CredentialProvider } from './credential-provider'
export class GitAuthService {
private askpassHandler: AskpassHandler | null = null
@@ -15,9 +15,11 @@ export class GitAuthService {
private sshKeyPath: string | null = null
private sshPassphrase: string | null = null
private sshPort: string | null = null
private credentialProvider: CredentialProvider | null = null
async initialize(ipcServer: IPCServer | undefined, database: Database): Promise<void> {
this.askpassHandler = new AskpassHandler(ipcServer, database)
this.credentialProvider = new CredentialProvider(database)
this.askpassHandler = new AskpassHandler(ipcServer, this.credentialProvider)
this.sshHostKeyHandler = new SSHHostKeyHandler(database, 120_000)
await this.sshHostKeyHandler.initialize()
@@ -97,10 +99,7 @@ export class GitAuthService {
const { port } = parseSSHHost(normalizedUrl)
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)
const sshCredentials = this.credentialProvider!.getSshCredentialsForHost(sshHost)
if (sshCredentials.length > 0 && sshCredentials[0]) {
try {
+13 -7
View File
@@ -6,15 +6,16 @@ import { getRepoById } from '../../db/queries'
import { resolveGitIdentity, createGitIdentityEnv, isSSHUrl } from '../../utils/git-auth'
import { isNoUpstreamError, parseBranchNameFromError } from '../../utils/git-errors'
import { SettingsService } from '../settings'
import { CredentialProvider } from '../credential-provider'
import type { Database } from 'bun:sqlite'
import type { GitBranch, GitCommit, FileDiffResponse, GitDiffOptions, GitStatusResponse, GitFileStatus, GitFileStatusType, CommitDetails, CommitFile } from '../../types/git'
import type { GitCredential } from '@opencode-manager/shared'
import path from 'path'
export class GitService {
constructor(
private gitAuthService: GitAuthService,
private settingsService: SettingsService
private settingsService: SettingsService,
private credentialProvider: CredentialProvider
) {}
async getStatus(repoId: number, database: Database): Promise<GitStatusResponse> {
@@ -196,10 +197,10 @@ export class GitService {
}
const repoPath = repo.fullPath
const authEnv = this.gitAuthService.getGitEnvironment()
const authEnv = this.getEnvironmentForRepo(repo)
const settings = this.settingsService.getSettings('default')
const gitCredentials = (settings.preferences.gitCredentials || []) as GitCredential[]
const gitCredentials = this.credentialProvider.getGitCredentials()
const identity = await resolveGitIdentity(settings.preferences.gitIdentity, gitCredentials)
const identityEnv = identity ? createGitIdentityEnv(identity) : {}
@@ -523,13 +524,18 @@ export class GitService {
await this.gitAuthService.cleanupSSHKey()
}
private getEnvironmentForRepo(repo: { repoUrl?: string; fullPath: string }, silent: boolean = false): Record<string, string> {
private getEnvironmentForRepo(repo: { id?: number; repoUrl?: string; fullPath: string }, silent: boolean = false): Record<string, string> {
const repoContextEnv = {
...(repo.id ? { OCM_GIT_REPO_ID: String(repo.id) } : {}),
OCM_GIT_REPO_CWD: repo.fullPath,
}
if (!repo.repoUrl) {
return this.gitAuthService.getGitEnvironment(silent)
return { ...this.gitAuthService.getGitEnvironment(silent), ...repoContextEnv }
}
const isSSH = isSSHUrl(repo.repoUrl)
const baseEnv = this.gitAuthService.getGitEnvironment(silent)
const baseEnv = { ...this.gitAuthService.getGitEnvironment(silent), ...repoContextEnv }
if (!isSSH) {
return baseEnv
@@ -0,0 +1,56 @@
import { promises as fs } from 'fs'
import path from 'path'
import { logger } from '../utils/logger'
const PLUGIN_FILENAME = 'ocm-gh-env.js'
const PLUGIN_SOURCE = `const TTL_MS = 5000
let cache = new Map()
async function fetchGhEnv(cwd) {
const baseUrl = process.env.OCM_INTERNAL_API_URL
const token = process.env.OCM_INTERNAL_TOKEN
if (!baseUrl || !token) return {}
const now = Date.now()
const cacheKey = cwd || ''
const cached = cache.get(cacheKey)
if (cached && now < cached.expiry) return cached.env
try {
const url = new URL(baseUrl + '/git-credentials/gh-env')
if (cwd) url.searchParams.set('cwd', cwd)
const res = await fetch(url, {
headers: { Authorization: 'Bearer ' + token },
})
if (!res.ok) return cached?.env || {}
const env = await res.json()
const next = { expiry: now + TTL_MS, env: env && typeof env === 'object' ? env : {} }
cache.set(cacheKey, next)
return next.env
} catch {
return cached?.env || {}
}
}
export default async function () {
return {
'shell.env': async (input, output) => {
const env = await fetchGhEnv(input.cwd)
Object.assign(output.env, env)
},
}
}
`
export function getGhEnvPluginDir(configHome: string): string {
return path.join(configHome, 'opencode', 'plugin')
}
export async function installGhEnvPlugin(configHome: string): Promise<void> {
try {
const dir = getGhEnvPluginDir(configHome)
await fs.mkdir(dir, { recursive: true })
await fs.writeFile(path.join(dir, PLUGIN_FILENAME), PLUGIN_SOURCE, 'utf-8')
} catch (error) {
logger.warn('Failed to install gh-env OpenCode plugin:', error)
}
}
+16 -6
View File
@@ -2,8 +2,7 @@ import { spawn, execSync, spawnSync } from 'child_process'
import path from 'path'
import { promises as fs } from 'fs'
import { logger } from '../utils/logger'
import { createGitEnv, createGitIdentityEnv, resolveGitIdentity } from '../utils/git-auth'
import type { GitCredential } from '@opencode-manager/shared'
import { createGitIdentityEnv, resolveGitIdentity } from '../utils/git-auth'
import {
buildSSHCommandWithKnownHosts,
buildSSHCommandWithConfig,
@@ -24,6 +23,9 @@ import { compareVersions } from '../utils/version-utils'
import { patchConfigWithRecovery } from './opencode/config-recovery'
import type { OpenCodeClient } from './opencode/client'
import { writeFileContent } from './file-operations'
import { getOrCreateInternalToken } from './internal-token'
import { installGhEnvPlugin } from './opencode-gh-env-plugin'
import { CredentialProvider } from './credential-provider'
const MIN_OPENCODE_VERSION = '1.0.137'
@@ -202,14 +204,15 @@ class OpenCodeServerManager {
throw new Error(msg)
}
let gitCredentials: GitCredential[] = []
let credentialProvider: CredentialProvider | null = null
let gitIdentityEnv: Record<string, string> = {}
let userEnvVars: Record<string, string> = {}
if (this.db) {
try {
credentialProvider = new CredentialProvider(this.db)
const settingsService = new SettingsService(this.db)
const settings = settingsService.getSettings('default')
gitCredentials = settings.preferences.gitCredentials || []
const gitCredentials = credentialProvider.getGitCredentials()
const disabledDefaultEnvVars = new Set(settings.preferences.disabledDefaultServerEnvVars || [])
const rawEnvVars = [
...DEFAULT_SERVER_ENV_VARS.filter((envVar) => !disabledDefaultEnvVars.has(envVar.key)),
@@ -279,12 +282,12 @@ class OpenCodeServerManager {
logger.info(`OpenCode XDG_CONFIG_HOME: ${path.join(openCodeServerDirectory, '.config')}`)
logger.info(`OpenCode will use ?directory= parameter for session isolation`)
const gitEnv = createGitEnv(gitCredentials)
const gitEnv = credentialProvider?.getGitEnv() ?? {}
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)
const sshCredentials = credentialProvider?.getSshCredentialsWithPrivateKey() ?? []
if (sshCredentials.length > 0) {
logger.info(`Setting up ${sshCredentials.length} SSH credential(s) for OpenCode server`)
@@ -327,6 +330,7 @@ class OpenCodeServerManager {
logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`)
await this.initializeOpencodeBinDirectory()
await installGhEnvPlugin(path.join(openCodeServerDirectory, '.config'))
const configuredPlugins = await this.getConfiguredPlugins(openCodeConfigPath)
await this.installConfiguredPlugins(configuredPlugins)
const configuredPluginCount = configuredPlugins.length
@@ -352,6 +356,12 @@ class OpenCodeServerManager {
...userEnvVars,
...gitEnv,
...gitIdentityEnv,
...(this.db
? {
OCM_INTERNAL_API_URL: `http://localhost:${ENV.SERVER.PORT}/api/internal`,
OCM_INTERNAL_TOKEN: getOrCreateInternalToken(this.db),
}
: {}),
GIT_SSH_COMMAND: gitSshCommand,
XDG_DATA_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
XDG_STATE_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
+30
View File
@@ -112,6 +112,36 @@ export function findGitHubCredential(credentials: GitCredential[]): GitCredentia
}) || null
}
export function createGhCliEnv(credentials: GitCredential[]): Record<string, string> {
const githubCred = findGitHubCredential(credentials)
if (!githubCred?.token) return {}
return { GH_TOKEN: githubCred.token, GITHUB_TOKEN: githubCred.token }
}
export interface ResolvedGitCredential {
username: string
password: string
}
export function findPatCredentialForHost(
credentials: GitCredential[],
hostname: string
): ResolvedGitCredential | null {
const target = normalizeGitCredentialUrl(hostname)?.hostname.toLowerCase()
if (!target) return null
for (const cred of credentials) {
if (cred.type && cred.type !== 'pat') continue
const credHost = normalizeGitCredentialUrl(cred.host)?.hostname.toLowerCase()
if (credHost && credHost === target) {
return {
username: cred.username || getDefaultUsername(cred.host),
password: cred.token || '',
}
}
}
return null
}
export function getSSHCredentialsForHost(credentials: GitCredential[], host: string): GitCredential[] {
return credentials.filter(cred => {
if (cred.type !== 'ssh') return false
+146
View File
@@ -0,0 +1,146 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { SettingsService } from '../../src/services/settings'
import { CredentialProvider } from '../../src/services/credential-provider'
import { AskpassHandler } from '../../src/ipc/askpassHandler'
import { createRepo, setRepoGitCredentialId } from '../../src/db/queries'
import type { GitCredential } from '@opencode-manager/shared'
function createGitHubPatCredential(token: string = 'ghp_test_token', id?: string): GitCredential {
return {
...(id ? { id } : {}),
name: 'github-pat',
host: 'github.com',
type: 'pat' as const,
username: 'x-access-token',
token,
} as GitCredential
}
describe('AskpassHandler', () => {
let db: Database
let settingsService: SettingsService
let provider: CredentialProvider
let handler: AskpassHandler
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
settingsService = new SettingsService(db)
settingsService.updateSettings({
gitCredentials: [createGitHubPatCredential()],
})
provider = new CredentialProvider(db)
handler = new AskpassHandler(undefined, provider)
})
it('returns username on Username prompt for configured host', async () => {
const result = await handler.handle({
askpassType: 'https',
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
})
expect(result).toBe('x-access-token')
})
it('returns token on Password prompt after Username (cache path)', async () => {
// First call to populate cache
await handler.handle({
askpassType: 'https',
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
})
// Second call should use cache
const result = await handler.handle({
askpassType: 'https',
argv: ['', '', "Password for 'https://github.com'", '', 'https://github.com'],
})
expect(result).toBe('ghp_test_token')
})
it('returns empty string for unknown host', async () => {
const result = await handler.handle({
askpassType: 'https',
argv: ['', '', "Username for 'https://unknown.example.com'", '', 'https://unknown.example.com'],
})
expect(result).toBe('')
})
it('returns the repo-specific token for askpass requests with repo cwd', async () => {
const defaultCredential = createGitHubPatCredential('default-token', 'default-id')
const repoCredential = createGitHubPatCredential('repo-token', 'repo-id')
settingsService.updateSettings({
gitCredentials: [defaultCredential, repoCredential],
defaultGitCredentialId: 'default-id',
})
const repo = createRepo(db, {
repoUrl: 'https://github.com/acme/repo.git',
localPath: 'repo',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
setRepoGitCredentialId(db, repo.id, 'repo-id')
await handler.handle({
askpassType: 'https',
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
cwd: repo.fullPath,
})
const result = await handler.handle({
askpassType: 'https',
argv: ['', '', "Password for 'https://github.com'", '', 'https://github.com'],
cwd: repo.fullPath,
})
expect(result).toBe('repo-token')
})
it('keeps askpass cache separate per repo cwd', async () => {
const repoOneCredential = createGitHubPatCredential('repo-one-token', 'repo-one-id')
const repoTwoCredential = createGitHubPatCredential('repo-two-token', 'repo-two-id')
settingsService.updateSettings({ gitCredentials: [repoOneCredential, repoTwoCredential] })
const repoOne = createRepo(db, {
repoUrl: 'https://github.com/acme/one.git',
localPath: 'one',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
const repoTwo = createRepo(db, {
repoUrl: 'https://github.com/acme/two.git',
localPath: 'two',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
setRepoGitCredentialId(db, repoOne.id, 'repo-one-id')
setRepoGitCredentialId(db, repoTwo.id, 'repo-two-id')
await handler.handle({
askpassType: 'https',
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
cwd: repoOne.fullPath,
})
await handler.handle({
askpassType: 'https',
argv: ['', '', "Username for 'https://github.com'", '', 'https://github.com'],
cwd: repoTwo.fullPath,
})
const repoOnePassword = await handler.handle({
askpassType: 'https',
argv: ['', '', "Password for 'https://github.com'", '', 'https://github.com'],
cwd: repoOne.fullPath,
})
const repoTwoPassword = await handler.handle({
askpassType: 'https',
argv: ['', '', "Password for 'https://github.com'", '', 'https://github.com'],
cwd: repoTwo.fullPath,
})
expect(repoOnePassword).toBe('repo-one-token')
expect(repoTwoPassword).toBe('repo-two-token')
})
})
+4
View File
@@ -17,6 +17,10 @@ export class Database {
}
}
query(sql: string) {
return this.prepare(sql)
}
exec(sql: string) {
this.db.exec(sql)
}
@@ -0,0 +1,40 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { migrate } from '../../../src/db/migration-runner'
import { allMigrations } from '../../../src/db/migrations'
import { SettingsService } from '../../../src/services/settings'
import { createInternalGitCredentialsRoutes } from '../../../src/routes/internal/git-credentials'
import type { GitCredential } from '@opencode-manager/shared'
describe('internal git-credentials routes', () => {
let db: Database
let settingsService: SettingsService
let app: ReturnType<typeof createInternalGitCredentialsRoutes>
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
settingsService = new SettingsService(db)
app = createInternalGitCredentialsRoutes(db)
})
it('GET /gh-env returns GH_TOKEN and GITHUB_TOKEN for a GitHub PAT', async () => {
settingsService.updateSettings({
gitCredentials: [
{ name: 'github', host: 'github.com', type: 'pat', token: 'ghp_test_token' } as GitCredential,
],
})
const res = await app.request('/gh-env')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' })
})
it('GET /gh-env returns an empty object when no GitHub credential exists', async () => {
const res = await app.request('/gh-env')
expect(res.status).toBe(200)
expect(await res.json()).toEqual({})
})
})
@@ -0,0 +1,181 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { SettingsService } from '../../src/services/settings'
import { CredentialProvider } from '../../src/services/credential-provider'
import { createRepo, setRepoGitCredentialId } from '../../src/db/queries'
import type { GitCredential } from '@opencode-manager/shared'
function createPatCredential(name: string, host: string, token: string, username?: string, id?: string): GitCredential {
return {
...(id ? { id } : {}),
name,
host,
token,
...(username ? { username } : {}),
} as GitCredential
}
function createSshCredential(name: string, host: string, sshPrivateKeyEncrypted?: string): GitCredential {
return {
name,
host,
type: 'ssh',
...(sshPrivateKeyEncrypted ? { sshPrivateKeyEncrypted } : {}),
} as GitCredential
}
describe('CredentialProvider', () => {
let db: Database
let settingsService: SettingsService
let provider: CredentialProvider
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
settingsService = new SettingsService(db)
provider = new CredentialProvider(db)
})
describe('with seeded credentials', () => {
const githubPat: GitCredential = createPatCredential('github-pat', 'github.com', 'ghp_test_token')
const gitlabPat: GitCredential = createPatCredential('gitlab-pat', 'gitlab.com', 'glpat_test_token', 'custom-user')
const githubSsh: GitCredential = createSshCredential('github-ssh', 'github.com')
beforeEach(() => {
settingsService.updateSettings({ gitCredentials: [githubPat, gitlabPat, githubSsh] })
})
it('getPatCredentialForHost returns the matching PAT credential', () => {
const result = provider.getPatCredentialForHost('github.com')
expect(result).toEqual({ username: 'x-access-token', password: 'ghp_test_token' })
})
it('getPatCredentialForHost uses custom username when provided', () => {
const result = provider.getPatCredentialForHost('gitlab.com')
expect(result).toEqual({ username: 'custom-user', password: 'glpat_test_token' })
})
it('getPatCredentialForHost returns null for unmatched host', () => {
expect(provider.getPatCredentialForHost('bitbucket.org')).toBeNull()
})
it('getPatCredentialForHost prefers the configured default PAT for the host', () => {
const first = createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id')
const second = createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id')
settingsService.updateSettings({ gitCredentials: [first, second], defaultGitCredentialId: 'second-id' })
expect(provider.getPatCredentialForHost('github.com')).toEqual({ username: 'x-access-token', password: 'second-token' })
})
it('getPatCredentialForHost prefers repo-specific PAT for the cwd', () => {
const first = createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id')
const second = createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id')
settingsService.updateSettings({ gitCredentials: [first, second], defaultGitCredentialId: 'first-id' })
const repo = createRepo(db, {
repoUrl: 'https://github.com/acme/repo.git',
localPath: 'repo',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
setRepoGitCredentialId(db, repo.id, 'second-id')
expect(provider.getPatCredentialForHost('github.com', { cwd: repo.fullPath })).toEqual({ username: 'x-access-token', password: 'second-token' })
})
it('getPatCredentialForHost ignores selected credentials for other hosts', () => {
const github = createPatCredential('github', 'github.com', 'github-token', undefined, 'github-id')
const gitlab = createPatCredential('gitlab', 'gitlab.com', 'gitlab-token', 'custom-user', 'gitlab-id')
settingsService.updateSettings({ gitCredentials: [github, gitlab], defaultGitCredentialId: 'github-id' })
expect(provider.getPatCredentialForHost('gitlab.com')).toEqual({ username: 'custom-user', password: 'gitlab-token' })
})
it('getGhCliEnv returns GH_TOKEN and GITHUB_TOKEN for GitHub PAT', () => {
const env = provider.getGhCliEnv()
expect(env).toEqual({ GH_TOKEN: 'ghp_test_token', GITHUB_TOKEN: 'ghp_test_token' })
})
it('getGhCliEnv prefers the configured default GitHub PAT', () => {
const first = createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id')
const second = createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id')
settingsService.updateSettings({ gitCredentials: [first, second], defaultGitCredentialId: 'second-id' })
expect(provider.getGhCliEnv()).toEqual({ GH_TOKEN: 'second-token', GITHUB_TOKEN: 'second-token' })
})
it('getGhCliEnv prefers repo-specific GitHub PAT for the cwd', () => {
const first = createPatCredential('first', 'github.com', 'first-token', undefined, 'first-id')
const second = createPatCredential('second', 'github.com', 'second-token', undefined, 'second-id')
settingsService.updateSettings({ gitCredentials: [first, second], defaultGitCredentialId: 'first-id' })
const repo = createRepo(db, {
repoUrl: 'https://github.com/acme/repo.git',
localPath: 'repo',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: Date.now(),
})
setRepoGitCredentialId(db, repo.id, 'second-id')
expect(provider.getGhCliEnv({ cwd: repo.fullPath })).toEqual({ GH_TOKEN: 'second-token', GITHUB_TOKEN: 'second-token' })
})
it('getGitEnv returns git config env for configured PATs', () => {
const env = provider.getGitEnv()
expect(env.GIT_TERMINAL_PROMPT).toBe('0')
expect(env.GIT_CONFIG_COUNT).toBe('2')
})
it('getSshCredentialsForHost returns SSH credentials and excludes PATs', () => {
const sshCreds = provider.getSshCredentialsForHost('github.com')
expect(sshCreds).toHaveLength(1)
expect(sshCreds[0]).toMatchObject({ name: 'github-ssh', type: 'ssh' })
})
it('getSshCredentialsForHost returns empty array for unmatched host', () => {
expect(provider.getSshCredentialsForHost('gitlab.com')).toEqual([])
})
it('getSshCredentialsWithPrivateKey returns only encrypted SSH credentials', () => {
const encryptedSsh = createSshCredential('encrypted-ssh', 'example.com', 'encrypted-key')
settingsService.updateSettings({ gitCredentials: [githubPat, githubSsh, encryptedSsh] })
expect(provider.getSshCredentialsWithPrivateKey()).toEqual([encryptedSsh])
})
})
describe('with no credentials', () => {
it('getPatCredentialForHost returns null', () => {
expect(provider.getPatCredentialForHost('github.com')).toBeNull()
})
it('getGhCliEnv returns empty object', () => {
expect(provider.getGhCliEnv()).toEqual({})
})
it('getGitEnv returns disabled terminal prompt defaults', () => {
expect(provider.getGitEnv()).toEqual({ GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_COUNT: '0' })
})
it('getSshCredentialsForHost returns empty array', () => {
expect(provider.getSshCredentialsForHost('github.com')).toEqual([])
})
it('getSshCredentialsWithPrivateKey returns empty array', () => {
expect(provider.getSshCredentialsWithPrivateKey()).toEqual([])
})
})
describe('getGitCredentials', () => {
it('returns empty array when no credentials are stored', () => {
expect(provider.getGitCredentials()).toEqual([])
})
it('returns all stored credentials', () => {
const creds = [createPatCredential('test', 'example.com', 'tok'), createSshCredential('ssh-test', 'example.com')]
settingsService.updateSettings({ gitCredentials: creds })
expect(provider.getGitCredentials()).toHaveLength(2)
})
})
})
+10 -1
View File
@@ -89,7 +89,7 @@ vi.mock('../ipc/ipcServer', () => ({
IPCServer: vi.fn(),
}))
vi.mock('../ipc/askpassHandler', () => ({
vi.mock('../../src/ipc/askpassHandler', () => ({
AskpassHandler: vi.fn().mockImplementation(() => ({
getEnv: vi.fn().mockReturnValue({}),
})),
@@ -103,6 +103,15 @@ vi.mock('../../src/ipc/sshHostKeyHandler', () => ({
})),
}))
vi.mock('../../src/services/credential-provider', () => ({
CredentialProvider: vi.fn().mockImplementation(() => ({
getGhCliEnv: vi.fn().mockReturnValue({}),
getSshCredentialsForHost: vi.fn().mockReturnValue([]),
getPatCredentialForHost: vi.fn().mockReturnValue(null),
getGitCredentials: vi.fn().mockReturnValue([]),
})),
}))
describe('GitAuthService with passphrase support', () => {
let gitAuthService: GitAuthService
let mockIpcServer: IPCServer
+14 -2
View File
@@ -49,6 +49,7 @@ describe('GitService', () => {
let database: Database
let mockGitAuthService: GitAuthService
let mockSettingsService: any
let mockCredentialProvider: any
beforeEach(() => {
vi.clearAllMocks()
@@ -70,7 +71,10 @@ describe('GitService', () => {
},
}),
}
service = new GitService(mockGitAuthService, mockSettingsService)
mockCredentialProvider = {
getGitCredentials: vi.fn().mockReturnValue([]),
}
service = new GitService(mockGitAuthService, mockSettingsService, mockCredentialProvider)
})
describe('getStatus', () => {
@@ -639,7 +643,7 @@ describe('GitService', () => {
expect(getRepoById).toHaveBeenCalledWith(database, 1)
expect(executeCommand).toHaveBeenCalledWith(
['git', '-C', '/path/to/repo', 'push'],
{ env: expect.any(Object) }
{ env: expect.objectContaining({ OCM_GIT_REPO_ID: '1', OCM_GIT_REPO_CWD: '/path/to/repo' }) }
)
expect(result).toBe('Everything up-to-date')
})
@@ -681,6 +685,10 @@ describe('GitService', () => {
const result = await service.fetch(1, database)
expect(executeCommand).toHaveBeenCalledWith(
['git', '-C', '/path/to/repo', 'fetch', '--all', '--prune'],
{ env: expect.objectContaining({ OCM_GIT_REPO_ID: '1', OCM_GIT_REPO_CWD: '/path/to/repo' }) }
)
expect(result).toBe('')
})
})
@@ -700,6 +708,10 @@ describe('GitService', () => {
const result = await service.pull(1, database)
expect(executeCommand).toHaveBeenCalledWith(
['git', '-C', '/path/to/repo', 'pull'],
{ env: expect.objectContaining({ OCM_GIT_REPO_ID: '1', OCM_GIT_REPO_CWD: '/path/to/repo' }) }
)
expect(result).toBe('')
})
})
@@ -0,0 +1,119 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { promises as fs } from 'fs'
import path from 'path'
import os from 'os'
import { pathToFileURL } from 'url'
import { installGhEnvPlugin, getGhEnvPluginDir } from '../../src/services/opencode-gh-env-plugin'
type ShellEnvHook = (
input: { cwd: string },
output: { env: Record<string, string> },
) => Promise<void>
type PluginFactory = () => Promise<{ 'shell.env': ShellEnvHook }>
async function loadPlugin(configHome: string): Promise<PluginFactory> {
const file = path.join(getGhEnvPluginDir(configHome), 'ocm-gh-env.js')
const mod = await import(pathToFileURL(file).href)
return mod.default as PluginFactory
}
describe('ocm-gh-env plugin', () => {
let configHome: string
beforeEach(async () => {
configHome = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-ghenv-'))
await installGhEnvPlugin(configHome)
process.env.OCM_INTERNAL_API_URL = 'http://localhost:5003/api/internal'
process.env.OCM_INTERNAL_TOKEN = 'secret-token'
})
afterEach(async () => {
vi.unstubAllGlobals()
delete process.env.OCM_INTERNAL_API_URL
delete process.env.OCM_INTERNAL_TOKEN
await fs.rm(configHome, { recursive: true, force: true })
})
it('writes the plugin file into the auto-discovery dir', async () => {
const file = path.join(getGhEnvPluginDir(configHome), 'ocm-gh-env.js')
await expect(fs.access(file)).resolves.toBeUndefined()
})
it('injects fetched GH env into output.env', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' }),
})
vi.stubGlobal('fetch', fetchMock)
const factory = await loadPlugin(configHome)
const hooks = await factory()
const output = { env: {} as Record<string, string> }
await hooks['shell.env']({ cwd: '/repo' }, output)
expect(output.env).toEqual({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' })
const [url, options] = fetchMock.mock.calls[0]!
expect(url.toString()).toBe('http://localhost:5003/api/internal/git-credentials/gh-env?cwd=%2Frepo')
expect(options).toEqual({ headers: { Authorization: 'Bearer secret-token' } })
})
it('does not fetch when the internal env vars are missing', async () => {
delete process.env.OCM_INTERNAL_API_URL
delete process.env.OCM_INTERNAL_TOKEN
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const factory = await loadPlugin(configHome)
const hooks = await factory()
const output = { env: {} as Record<string, string> }
await hooks['shell.env']({ cwd: '/repo' }, output)
expect(output.env).toEqual({})
expect(fetchMock).not.toHaveBeenCalled()
})
it('never throws when the fetch fails', async () => {
const fetchMock = vi.fn().mockRejectedValue(new Error('network down'))
vi.stubGlobal('fetch', fetchMock)
const factory = await loadPlugin(configHome)
const hooks = await factory()
const output = { env: {} as Record<string, string> }
await expect(hooks['shell.env']({ cwd: '/repo' }, output)).resolves.toBeUndefined()
expect(output.env).toEqual({})
})
it('caches results within the TTL so rapid calls fetch once', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' }),
})
vi.stubGlobal('fetch', fetchMock)
const factory = await loadPlugin(configHome)
const hooks = await factory()
const out1 = { env: {} as Record<string, string> }
const out2 = { env: {} as Record<string, string> }
await hooks['shell.env']({ cwd: '/repo' }, out1)
await hooks['shell.env']({ cwd: '/repo' }, out2)
expect(fetchMock).toHaveBeenCalledTimes(1)
expect(out2.env).toEqual({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' })
})
it('caches results per cwd', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ GH_TOKEN: 'ghp', GITHUB_TOKEN: 'ghp' }),
})
vi.stubGlobal('fetch', fetchMock)
const factory = await loadPlugin(configHome)
const hooks = await factory()
await hooks['shell.env']({ cwd: '/repo-a' }, { env: {} })
await hooks['shell.env']({ cwd: '/repo-b' }, { env: {} })
expect(fetchMock).toHaveBeenCalledTimes(2)
})
})
@@ -179,7 +179,7 @@ describe('OpenCodeServerManager - server auth', () => {
function createPasswordDb(password: string | null) {
const encrypted = password ? encryptSecret(password) : null
return {
const db = {
prepare: vi.fn((sql: string) => ({
get: (key?: string) => {
if (key === 'opencode_server_password' && sql.includes('SELECT value FROM app_secrets') && encrypted) {
@@ -190,7 +190,10 @@ describe('OpenCodeServerManager - server auth', () => {
run: vi.fn(),
all: vi.fn(() => []),
})),
} as any
query: vi.fn((sql: string) => db.prepare(sql)),
}
return db as any
}
})
+116 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { fetchGitHubUserInfo, findGitHubCredential, resolveGitIdentity, createGitIdentityEnv, getSSHCredentialsForHost, createGitEnv, getDefaultUsername, normalizeHost } from '../../src/utils/git-auth'
import { fetchGitHubUserInfo, findGitHubCredential, findPatCredentialForHost, resolveGitIdentity, createGitIdentityEnv, getSSHCredentialsForHost, createGitEnv, createGhCliEnv, getDefaultUsername, normalizeHost } from '../../src/utils/git-auth'
import type { GitCredential } from '@opencode-manager/shared'
describe('fetchGitHubUserInfo', () => {
@@ -239,6 +239,48 @@ describe('createGitEnv', () => {
})
})
describe('createGhCliEnv', () => {
it('returns GH_TOKEN and GITHUB_TOKEN set to the token for a github PAT', () => {
const credentials: GitCredential[] = [
{ name: 'github', host: 'https://github.com/', type: 'pat', token: 'gh-cli-token' },
]
const env = createGhCliEnv(credentials)
expect(env).toEqual({ GH_TOKEN: 'gh-cli-token', GITHUB_TOKEN: 'gh-cli-token' })
})
it('returns {} when no github credential exists', () => {
const credentials: GitCredential[] = [
{ name: 'gitlab', host: 'https://gitlab.com/', type: 'pat', token: 'gl-token' },
]
const env = createGhCliEnv(credentials)
expect(env).toEqual({})
})
it('returns {} when github credential has an empty token', () => {
const credentials: GitCredential[] = [
{ name: 'github', host: 'https://github.com/', type: 'pat', token: '' },
]
const env = createGhCliEnv(credentials)
expect(env).toEqual({})
})
it('returns {} when only an ssh github credential exists', () => {
const credentials: GitCredential[] = [
{ name: 'github-ssh', host: 'git@github.com', type: 'ssh', sshPrivateKey: 'key' },
]
const env = createGhCliEnv(credentials)
expect(env).toEqual({})
})
})
describe('normalizeHost', () => {
it('returns a URL-form host prefix for git url matching', () => {
expect(normalizeHost('github.com')).toBe('https://github.com/')
@@ -325,6 +367,79 @@ describe('findGitHubCredential', () => {
})
})
describe('findPatCredentialForHost', () => {
it('matches by hostname when stored as full https URL', () => {
const credentials: GitCredential[] = [
{ name: 'github', host: 'https://github.com/owner/repo.git', type: 'pat', token: 'gh-token' },
]
const result = findPatCredentialForHost(credentials, 'github.com')
expect(result).toEqual({ username: 'x-access-token', password: 'gh-token' })
})
it('uses explicit username when provided', () => {
const credentials: GitCredential[] = [
{ name: 'github', host: 'github.com', type: 'pat', token: 'gh-token', username: 'custom-user' },
]
const result = findPatCredentialForHost(credentials, 'github.com')
expect(result).toEqual({ username: 'custom-user', password: 'gh-token' })
})
it('returns x-access-token default for github hosts', () => {
const credentials: GitCredential[] = [
{ name: 'github', host: 'github.com', type: 'pat', token: 'gh-token' },
]
const result = findPatCredentialForHost(credentials, 'github.com')
expect(result?.username).toBe('x-access-token')
})
it('returns oauth2 default for non-github hosts', () => {
const credentials: GitCredential[] = [
{ name: 'gitlab', host: 'gitlab.com', type: 'pat', token: 'gl-token' },
]
const result = findPatCredentialForHost(credentials, 'gitlab.com')
expect(result?.username).toBe('oauth2')
})
it('ignores ssh credentials', () => {
const credentials: GitCredential[] = [
{ name: 'github-ssh', host: 'github.com', type: 'ssh', sshPrivateKey: 'key' },
{ name: 'github-pat', host: 'github.com', type: 'pat', token: 'pat-token' },
]
const result = findPatCredentialForHost(credentials, 'github.com')
expect(result).toEqual({ username: 'x-access-token', password: 'pat-token' })
})
it('returns null when no credential matches the host', () => {
const credentials: GitCredential[] = [
{ name: 'gitlab', host: 'gitlab.com', type: 'pat', token: 'gl-token' },
]
const result = findPatCredentialForHost(credentials, 'github.com')
expect(result).toBeNull()
})
it('returns empty password when matched credential has no token', () => {
const credentials: GitCredential[] = [
{ name: 'github', host: 'github.com', type: 'pat' },
]
const result = findPatCredentialForHost(credentials, 'github.com')
expect(result).toEqual({ username: 'x-access-token', password: '' })
})
})
describe('resolveGitIdentity', () => {
beforeEach(() => {
vi.clearAllMocks()
+8
View File
@@ -114,6 +114,14 @@ export async function switchRepoConfig(id: number, configName: string): Promise<
})
}
export async function updateRepoGitCredential(id: number, credentialId?: string): Promise<Repo> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${id}/git-credential`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ credentialId }),
})
}
export class GitAuthError extends Error {
code: string
constructor(message: string, code: string) {
+1
View File
@@ -12,6 +12,7 @@ export interface Repo {
lastPulled?: number
lastAccessedAt?: number
openCodeConfigName?: string
gitCredentialId?: string
isWorktree?: boolean
isLocal?: boolean
}
+2
View File
@@ -30,6 +30,7 @@ export interface CustomCommand {
}
export interface GitCredential {
id?: string
name: string
host: string
type: 'pat' | 'ssh'
@@ -61,6 +62,7 @@ export interface UserPreferences {
keyboardShortcuts: Record<string, string>
customCommands: CustomCommand[]
gitCredentials?: GitCredential[]
defaultGitCredentialId?: string
gitIdentity?: GitIdentity
tts?: TTSConfig
stt?: STTConfig
@@ -6,18 +6,29 @@ 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 { Checkbox } from '@/components/ui/checkbox'
import { MultiSelect, type MultiSelectOption } from '@/components/ui/multi-select'
import { showToast } from '@/lib/toast'
import type { GitCredential } from '@/api/types/settings'
import type { Repo } from '@/api/types'
export interface GitCredentialSaveOptions {
makeDefault: boolean
repoIds: number[]
}
interface GitCredentialDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onSave: (credential: GitCredential) => Promise<void>
onSave: (credential: GitCredential, options: GitCredentialSaveOptions) => Promise<void>
credential?: GitCredential
repos: Repo[]
assignedRepoIds: number[]
isDefault: boolean
isSaving: boolean
}
export function GitCredentialDialog({ open, onOpenChange, onSave, credential, isSaving }: GitCredentialDialogProps) {
export function GitCredentialDialog({ open, onOpenChange, onSave, credential, repos, assignedRepoIds, isDefault, isSaving }: GitCredentialDialogProps) {
const [formData, setFormData] = useState<GitCredential>({
name: '',
host: '',
@@ -31,6 +42,8 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
const [isTesting, setIsTesting] = useState(false)
const [showPassphraseInput, setShowPassphraseInput] = useState(false)
const [testPassphrase, setTestPassphrase] = useState('')
const [makeDefault, setMakeDefault] = useState(false)
const [selectedRepoIds, setSelectedRepoIds] = useState<number[]>([])
const maskToken = (token: string) => {
if (!token) return ''
@@ -43,6 +56,8 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
setTokenEdited(false)
setShowPassphraseInput(false)
setTestPassphrase('')
setMakeDefault(isDefault)
setSelectedRepoIds(assignedRepoIds)
if (credential) {
setFormData({
...credential,
@@ -61,7 +76,16 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
})
}
}
}, [open, credential])
}, [open, credential, assignedRepoIds, isDefault])
const normalizedHost = formData.host.toLowerCase().replace(/^https?:\/\//, '').replace(/\/+$/, '')
const isGithubPat = formData.type === 'pat' && normalizedHost === 'github.com'
const repoOptions: MultiSelectOption[] = repos.map((repo) => ({
value: String(repo.id),
label: repo.repoUrl?.split('/').pop()?.replace('.git', '') || repo.localPath,
description: repo.repoUrl || repo.fullPath,
}))
const handleSubmit = async (event?: React.MouseEvent) => {
event?.preventDefault()
@@ -92,7 +116,10 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
if (formData.type === 'pat' && credential?.token && !tokenEdited) {
dataToSave.token = credential.token
}
await onSave(dataToSave)
await onSave(dataToSave, {
makeDefault: isGithubPat && makeDefault,
repoIds: isGithubPat ? selectedRepoIds : [],
})
setFormData({ name: '', host: '', type: 'pat', token: '', username: '', sshPrivateKey: '', passphrase: '' })
onOpenChange(false)
} catch {
@@ -237,6 +264,42 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
autoComplete="off"
/>
</div>
{isGithubPat && (
<div className="space-y-3 rounded-lg border border-border p-3">
<div className="flex items-start gap-2">
<Checkbox
id="cred-default-github-token"
checked={makeDefault}
onCheckedChange={(checked) => setMakeDefault(checked === true)}
disabled={isSaving}
/>
<div className="space-y-1">
<Label htmlFor="cred-default-github-token">Use as default GitHub token</Label>
<p className="text-xs text-muted-foreground">
Used for GH_TOKEN/GITHUB_TOKEN unless a repository below overrides it.
</p>
</div>
</div>
<div className="space-y-2">
<Label>Use for specific repositories</Label>
{repos.length === 0 ? (
<p className="text-xs text-muted-foreground">No repositories available.</p>
) : (
<MultiSelect
value={selectedRepoIds.map(String)}
onChange={(values) => setSelectedRepoIds(values.map(Number))}
options={repoOptions}
placeholder="Select repositories..."
searchPlaceholder="Search repositories..."
emptyMessage="No repositories found"
disabled={isSaving}
/>
)}
</div>
</div>
)}
</>
) : (
<>
@@ -336,7 +399,7 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
type="button"
onClick={handleSubmit}
disabled={isSaving || !formData.name.trim() || !formData.host.trim() ||
(formData.type === 'pat' && !formData.token?.trim()) ||
(formData.type === 'pat' && !formData.token?.trim() && !(credential?.token && !tokenEdited)) ||
(formData.type === 'ssh' && !formData.sshPrivateKey?.trim())}
className="flex-1 sm:flex-none"
>
@@ -1,27 +1,41 @@
import { useState, useEffect } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useSettings } from '@/hooks/useSettings'
import { Loader2, Plus, Trash2, Save, User, Key, Pencil } from 'lucide-react'
import { showToast } from '@/lib/toast'
import { GitCredentialDialog } from './GitCredentialDialog'
import { GitCredentialDialog, type GitCredentialSaveOptions } from './GitCredentialDialog'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import type { GitCredential, GitIdentity } from '@/api/types/settings'
import { listRepos, updateRepoGitCredential } from '@/api/repos'
function ensureCredentialId(credential: GitCredential): GitCredential {
return credential.id ? credential : { ...credential, id: crypto.randomUUID() }
}
export function GitSettings() {
const { preferences, isLoading, updateSettingsAsync, isUpdating } = useSettings()
const queryClient = useQueryClient()
const [gitCredentials, setGitCredentials] = useState<GitCredential[]>([])
const [gitIdentity, setGitIdentity] = useState<GitIdentity>({ name: '', email: '' })
const [defaultGitCredentialId, setDefaultGitCredentialId] = useState<string | undefined>()
const [isSaving, setIsSaving] = useState(false)
const [hasChanges, setHasChanges] = useState(false)
const [isCredentialDialogOpen, setIsCredentialDialogOpen] = useState(false)
const [editingCredentialIndex, setEditingCredentialIndex] = useState<number | null>(null)
const { data: repos = [] } = useQuery({
queryKey: ['repos'],
queryFn: listRepos,
})
useEffect(() => {
if (preferences) {
setGitCredentials(preferences.gitCredentials || [])
setGitIdentity(preferences.gitIdentity || { name: '', email: '' })
setDefaultGitCredentialId(preferences.defaultGitCredentialId)
setHasChanges(false)
}
}, [preferences])
@@ -54,20 +68,37 @@ export function GitSettings() {
removeCredential(index)
}
const saveCredential = async (credential: GitCredential) => {
const syncRepoAssignments = async (credentialId: string, repoIds: number[]) => {
const selectedRepoIds = new Set(repoIds)
const affectedRepos = repos.filter((repo) => selectedRepoIds.has(repo.id) || repo.gitCredentialId === credentialId)
await Promise.all(
affectedRepos.map((repo) => updateRepoGitCredential(
repo.id,
selectedRepoIds.has(repo.id) ? credentialId : undefined
))
)
await queryClient.invalidateQueries({ queryKey: ['repos'] })
}
const saveCredential = async (credential: GitCredential, options: GitCredentialSaveOptions) => {
let newCredentials: GitCredential[]
const nextCredential = ensureCredentialId(credential)
const nextDefaultGitCredentialId = options.makeDefault ? nextCredential.id : defaultGitCredentialId === nextCredential.id ? undefined : defaultGitCredentialId
if (editingCredentialIndex !== null) {
newCredentials = [...gitCredentials]
newCredentials[editingCredentialIndex] = credential
newCredentials[editingCredentialIndex] = nextCredential
} else {
newCredentials = [...gitCredentials, credential]
newCredentials = [...gitCredentials, nextCredential]
}
setGitCredentials(newCredentials)
setDefaultGitCredentialId(nextDefaultGitCredentialId)
try {
await updateSettingsAsync({ gitCredentials: newCredentials, gitIdentity })
await updateSettingsAsync({ gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId, gitIdentity })
await syncRepoAssignments(nextCredential.id!, options.repoIds)
showToast.success('Credential saved')
} catch {
showToast.error('Failed to save credential')
@@ -75,11 +106,19 @@ export function GitSettings() {
}
const removeCredential = async (index: number) => {
const removedCredentialId = gitCredentials[index]?.id
const newCredentials = gitCredentials.filter((_, i) => i !== index)
const nextDefaultGitCredentialId = newCredentials.some((credential) => credential.id === defaultGitCredentialId)
? defaultGitCredentialId
: undefined
setGitCredentials(newCredentials)
setDefaultGitCredentialId(nextDefaultGitCredentialId)
try {
await updateSettingsAsync({ gitCredentials: newCredentials, gitIdentity })
await updateSettingsAsync({ gitCredentials: newCredentials, defaultGitCredentialId: nextDefaultGitCredentialId, gitIdentity })
if (removedCredentialId) {
await syncRepoAssignments(removedCredentialId, [])
}
showToast.success('Credential deleted')
} catch {
showToast.error('Failed to delete credential')
@@ -96,7 +135,7 @@ export function GitSettings() {
setIsSaving(true)
try {
showToast.loading('Saving git configuration...', { id: 'git-config' })
const result = await updateSettingsAsync({ gitCredentials, gitIdentity })
const result = await updateSettingsAsync({ gitCredentials, defaultGitCredentialId, gitIdentity })
setHasChanges(false)
if (result.reloadError) {
showToast.success('Git configuration saved (server reload pending)', { id: 'git-config' })
@@ -206,10 +245,10 @@ export function GitSettings() {
>
<Plus className="h-4 w-4 mr-2" />
Add
</Button>
</div>
</Button>
</div>
{gitCredentials.length === 0 ? (
{gitCredentials.length === 0 ? (
<div className="rounded-lg border border-dashed border-border p-4 text-center">
<p className="text-sm text-muted-foreground">
No credentials configured. Click "Add" to add credentials.
@@ -279,13 +318,18 @@ export function GitSettings() {
</div>
</div>
<GitCredentialDialog
<GitCredentialDialog
open={isCredentialDialogOpen}
onOpenChange={setIsCredentialDialogOpen}
onSave={saveCredential}
credential={editingCredentialIndex !== null ? gitCredentials[editingCredentialIndex] : undefined}
isSaving={isSaving || isUpdating}
/>
onSave={saveCredential}
credential={editingCredentialIndex !== null ? gitCredentials[editingCredentialIndex] : undefined}
repos={repos}
assignedRepoIds={editingCredentialIndex !== null && gitCredentials[editingCredentialIndex]?.id
? repos.filter((repo) => repo.gitCredentialId === gitCredentials[editingCredentialIndex]?.id).map((repo) => repo.id)
: []}
isDefault={editingCredentialIndex !== null && !!gitCredentials[editingCredentialIndex]?.id && defaultGitCredentialId === gitCredentials[editingCredentialIndex]?.id}
isSaving={isSaving || isUpdating}
/>
</div>
)
}
+6 -2
View File
@@ -13,6 +13,8 @@ interface MultiSelectProps {
onChange: (values: string[]) => void
options: MultiSelectOption[]
placeholder?: string
searchPlaceholder?: string
emptyMessage?: string
disabled?: boolean
className?: string
}
@@ -22,6 +24,8 @@ export function MultiSelect({
onChange,
options,
placeholder = 'Select...',
searchPlaceholder = 'Search...',
emptyMessage = 'No options found',
disabled = false,
className,
}: MultiSelectProps) {
@@ -167,7 +171,7 @@ export function MultiSelect({
value={search}
onChange={e => setSearch(e.target.value)}
onKeyDown={handleInputKeyDown}
placeholder="Search skills..."
placeholder={searchPlaceholder}
className={cn(
'flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors',
'placeholder:text-muted-foreground',
@@ -177,7 +181,7 @@ export function MultiSelect({
</div>
<div className="max-h-52 overflow-y-auto" role="listbox">
{filteredOptions.length === 0 ? (
<div className="px-3 py-4 text-center text-sm text-muted-foreground">No skills found</div>
<div className="px-3 py-4 text-center text-sm text-muted-foreground">{emptyMessage}</div>
) : (
filteredOptions.map((option, index) => {
const isSelected = value.includes(option.value)
+1
View File
@@ -15,6 +15,7 @@ export const RepoSchema = z.object({
lastPulled: z.number().optional(),
lastAccessedAt: z.number().optional(),
openCodeConfigName: z.string().optional(),
gitCredentialId: z.string().optional(),
isWorktree: z.boolean().optional(),
isLocal: z.boolean().optional(),
})
+3
View File
@@ -83,6 +83,7 @@ export const DEFAULT_KEYBOARD_SHORTCUTS: Record<string, string> = {
};
export const GitCredentialSchema = z.object({
id: z.string().optional(),
name: z.string(),
host: z.string(),
type: z.enum(['pat', 'ssh']).default('pat'),
@@ -146,6 +147,7 @@ export const UserPreferencesSchema = z.object({
keyboardShortcuts: z.record(z.string(), z.string()),
customCommands: z.array(CustomCommandSchema),
gitCredentials: z.array(GitCredentialSchema).optional(),
defaultGitCredentialId: z.string().optional(),
gitIdentity: GitIdentitySchema.optional(),
tts: TTSConfigSchema.optional(),
stt: STTConfigSchema.optional(),
@@ -197,6 +199,7 @@ export const DEFAULT_USER_PREFERENCES = {
customCommands: [],
customAgents: [],
gitCredentials: [] as GitCredential[],
defaultGitCredentialId: undefined as string | undefined,
gitIdentity: DEFAULT_GIT_IDENTITY,
tts: DEFAULT_TTS_CONFIG,
stt: DEFAULT_STT_CONFIG,