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

+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