diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 01461811..8250d058 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -204,7 +204,8 @@ export function createRepoRoutes(database: Database) { return c.json({ error: 'Repo not found' }, 404) } - const branches = await repoService.listBranches(repo) + const branches = await repoService.listBranches(database, repo) + return c.json(branches) } catch (error: any) { @@ -223,7 +224,8 @@ export function createRepoRoutes(database: Database) { } const repoPath = path.resolve(getReposPath(), repo.localPath) - const status = await gitOperations.getGitStatus(repoPath) + const status = await gitOperations.getGitStatus(repoPath, database) + return c.json(status) } catch (error: any) { @@ -248,7 +250,8 @@ export function createRepoRoutes(database: Database) { } const repoPath = path.resolve(getReposPath(), repo.localPath) - const diff = await gitOperations.getFileDiff(repoPath, filePath) + const diff = await gitOperations.getFileDiff(repoPath, filePath, database) + return c.json(diff) } catch (error: any) { diff --git a/backend/src/services/git-operations.ts b/backend/src/services/git-operations.ts index bb8564f8..dd5c8846 100644 --- a/backend/src/services/git-operations.ts +++ b/backend/src/services/git-operations.ts @@ -3,6 +3,7 @@ import { logger } from '../utils/logger' import { SettingsService } from './settings' import type { Database } from 'bun:sqlite' import path from 'path' +import { createGitHubGitEnv, createNoPromptGitEnv } from '../utils/git-auth' async function hasCommits(repoPath: string): Promise { try { @@ -18,25 +19,15 @@ function getGitEnvironment(database: Database): Record { const settingsService = new SettingsService(database) const settings = settingsService.getSettings('default') const gitToken = settings.preferences.gitToken - + if (gitToken) { - return { - GITHUB_TOKEN: gitToken, - GIT_ASKPASS: 'echo $GITHUB_TOKEN', - GIT_TERMINAL_PROMPT: '0' - } - } - - return { - GIT_ASKPASS: 'echo', - GIT_TERMINAL_PROMPT: '0' + return createGitHubGitEnv(gitToken) } + + return createNoPromptGitEnv() } catch (error) { logger.warn('Failed to get git token from settings:', error) - return { - GIT_ASKPASS: 'echo', - GIT_TERMINAL_PROMPT: '0' - } + return createNoPromptGitEnv() } } diff --git a/backend/src/services/opencode-single-server.ts b/backend/src/services/opencode-single-server.ts index 81cd633c..b8f43eb2 100644 --- a/backend/src/services/opencode-single-server.ts +++ b/backend/src/services/opencode-single-server.ts @@ -1,6 +1,7 @@ import { spawn, execSync } from 'child_process' import path from 'path' import { logger } from '../utils/logger' +import { createGitHubGitEnv, createNoPromptGitEnv } from '../utils/git-auth' import { SettingsService } from './settings' import { getWorkspacePath, getOpenCodeConfigFilePath, ENV } from '@opencode-manager/shared' import type { Database } from 'bun:sqlite' @@ -101,8 +102,9 @@ class OpenCodeServerManager { logger.info(`OpenCode server working directory: ${OPENCODE_SERVER_DIRECTORY}`) logger.info(`OpenCode XDG_CONFIG_HOME: ${path.join(OPENCODE_SERVER_DIRECTORY, '.config')}`) logger.info(`OpenCode will use ?directory= parameter for session isolation`) - - + + const gitEnv = gitToken ? createGitHubGitEnv(gitToken) : createNoPromptGitEnv() + this.serverProcess = spawn( 'opencode', ['serve', '--port', OPENCODE_SERVER_PORT.toString(), '--hostname', '127.0.0.1'], @@ -112,12 +114,10 @@ class OpenCodeServerManager { stdio: isDevelopment ? 'inherit' : 'ignore', env: { ...process.env, + ...gitEnv, XDG_DATA_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.opencode/state'), XDG_CONFIG_HOME: path.join(OPENCODE_SERVER_DIRECTORY, '.config'), OPENCODE_CONFIG: OPENCODE_CONFIG_PATH, - GITHUB_TOKEN: gitToken, - GIT_ASKPASS: gitToken ? 'echo $GITHUB_TOKEN' : 'echo', - GIT_TERMINAL_PROMPT: '0' } } ) diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 099e16de..de446a01 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -5,6 +5,7 @@ import type { Database } from 'bun:sqlite' import type { Repo, CreateRepoInput } from '../types/repo' import { logger } from '../utils/logger' import { SettingsService } from './settings' +import { createGitEnvForRepoUrl, createNoPromptGitEnv } from '../utils/git-auth' import { getReposPath } from '@opencode-manager/shared' import path from 'path' @@ -37,6 +38,22 @@ async function safeGetCurrentBranch(repoPath: string): Promise { } } +function getGitEnv(database: Database, repoUrl?: string | null): Record { + try { + const settingsService = new SettingsService(database) + const settings = settingsService.getSettings('default') + const gitToken = settings.preferences.gitToken + + if (!repoUrl) { + return createNoPromptGitEnv() + } + + return createGitEnvForRepoUrl(repoUrl, gitToken) + } catch { + return createNoPromptGitEnv() + } +} + export async function initLocalRepo( database: Database, localPath: string, @@ -77,17 +94,7 @@ export async function initLocalRepo( logger.info(`Created directory for local repo: ${fullPath}`) logger.info(`Initializing git repository: ${fullPath}`) - const settingsService = new SettingsService(database) - const settings = settingsService.getSettings('default') - const gitToken = settings.preferences.gitToken - const env: Record = gitToken ? - { - GITHUB_TOKEN: gitToken, - GIT_ASKPASS: 'echo $GITHUB_TOKEN', - GIT_TERMINAL_PROMPT: '0' - } : - { GIT_ASKPASS: 'echo', GIT_TERMINAL_PROMPT: '0' } - + await executeCommand(['git', 'init'], { cwd: fullPath }) if (branch && branch !== 'main') { @@ -167,19 +174,16 @@ export async function cloneRepo( const repo = db.createRepo(database, createRepoInput) try { - const settingsService = new SettingsService(database) - const settings = settingsService.getSettings('default') - const gitToken = settings.preferences.gitToken - - const cloneUrl = repoUrl - + const env = getGitEnv(database, repoUrl) + if (shouldUseWorktree) { logger.info(`Creating worktree for branch: ${branch}`) const baseRepoPath = path.resolve(getReposPath(), baseRepoDirName) const worktreePath = path.resolve(getReposPath(), worktreeDirName) - await executeCommand(['git', '-C', baseRepoPath, 'fetch', '--all']) + await executeCommand(['git', '-C', baseRepoPath, 'fetch', '--all'], { env }) + await createWorktreeSafely(baseRepoPath, worktreePath, branch) @@ -213,7 +217,7 @@ export async function cloneRepo( try { const cloneCmd = ['git', 'clone', '-b', branch, repoUrl, worktreeDirName] - await executeCommand(cloneCmd, getReposPath()) + await executeCommand(cloneCmd, { cwd: getReposPath(), env }) } catch (error: any) { if (error.message.includes('destination path') && error.message.includes('already exists')) { logger.error(`Clone failed: directory still exists after cleanup attempt`) @@ -222,7 +226,7 @@ export async function cloneRepo( logger.info(`Branch '${branch}' not found during clone, cloning default branch and creating branch locally`) const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, getReposPath()) + await executeCommand(cloneCmd, { cwd: getReposPath(), env }) let localBranchExists = 'missing' try { await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`]) @@ -246,7 +250,8 @@ export async function cloneRepo( if (branch) { logger.info(`Switching to branch: ${branch}`) - await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'fetch', '--all']) + await executeCommand(['git', '-C', path.resolve(getReposPath(), baseRepoDirName), 'fetch', '--all'], { env }) + let remoteBranchExists = false try { @@ -306,7 +311,7 @@ export async function cloneRepo( ? ['git', 'clone', '-b', branch, repoUrl, worktreeDirName] : ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, getReposPath()) + await executeCommand(cloneCmd, { cwd: getReposPath(), env }) } catch (error: any) { if (error.message.includes('destination path') && error.message.includes('already exists')) { logger.error(`Clone failed: directory still exists after cleanup attempt`) @@ -316,7 +321,7 @@ export async function cloneRepo( if (branch && (error.message.includes('Remote branch') || error.message.includes('not found'))) { logger.info(`Branch '${branch}' not found, cloning default branch and creating branch locally`) const cloneCmd = ['git', 'clone', repoUrl, worktreeDirName] - await executeCommand(cloneCmd, getReposPath()) + await executeCommand(cloneCmd, { cwd: getReposPath(), env }) let localBranchExists = 'missing' try { await executeCommand(['git', '-C', path.resolve(getReposPath(), worktreeDirName), 'rev-parse', '--verify', `refs/heads/${branch}`]) @@ -352,12 +357,13 @@ export async function getCurrentBranch(repo: Repo): Promise { return branch || repo.branch || repo.defaultBranch || null } -export async function listBranches(repo: Repo): Promise<{ local: string[], remote: string[], current: string | null }> { +export async function listBranches(database: Database, repo: Repo): Promise<{ local: string[], remote: string[], current: string | null }> { try { const repoPath = path.resolve(getReposPath(), repo.localPath) - + const env = getGitEnv(database, repo.repoUrl) + if (!repo.isLocal) { - await executeCommand(['git', '-C', repoPath, 'fetch', '--all']) + await executeCommand(['git', '-C', repoPath, 'fetch', '--all'], { env }) } const localBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '--format=%(refname:short)']) @@ -399,10 +405,11 @@ export async function switchBranch(database: Database, repoId: number, branch: s try { const repoPath = path.resolve(getReposPath(), repo.localPath) - + const env = getGitEnv(database, repo.repoUrl) + logger.info(`Switching to branch: ${branch} in ${repo.localPath}`) - - await executeCommand(['git', '-C', repoPath, 'fetch', '--all']) + + await executeCommand(['git', '-C', repoPath, 'fetch', '--all'], { env }) let localBranchExists = false try { @@ -450,8 +457,10 @@ export async function pullRepo(database: Database, repoId: number): Promise { + return { + GIT_TERMINAL_PROMPT: '0' + } +} + +export function createGitHubGitEnv(gitToken: string): Record { + const basicAuth = Buffer.from(`x-access-token:${gitToken}`, 'utf8').toString('base64') + + return { + ...createNoPromptGitEnv(), + GITHUB_TOKEN: gitToken, + GIT_CONFIG_COUNT: '1', + GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader', + GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basicAuth}` + } +} + +export function createGitEnvForRepoUrl(repoUrl: string, gitToken?: string): Record { + if (!gitToken) { + return createNoPromptGitEnv() + } + + if (isGitHubHttpsUrl(repoUrl)) { + return createGitHubGitEnv(gitToken) + } + + return createNoPromptGitEnv() +} diff --git a/backend/test/services/repo-auth-env.test.ts b/backend/test/services/repo-auth-env.test.ts new file mode 100644 index 00000000..6400c192 --- /dev/null +++ b/backend/test/services/repo-auth-env.test.ts @@ -0,0 +1,79 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { getReposPath } from '@opencode-manager/shared' +import { createGitHubGitEnv } from '../../src/utils/git-auth' + +const executeCommand = vi.fn() +const ensureDirectoryExists = vi.fn() + +const getRepoByUrlAndBranch = vi.fn() +const createRepo = vi.fn() +const updateRepoStatus = vi.fn() +const deleteRepo = vi.fn() + +vi.mock('../../src/utils/process', () => ({ + executeCommand, +})) + +vi.mock('../../src/services/file-operations', () => ({ + ensureDirectoryExists, +})) + +vi.mock('../../src/db/queries', () => ({ + getRepoByUrlAndBranch, + createRepo, + updateRepoStatus, + deleteRepo, +})) + +vi.mock('../../src/services/settings', () => ({ + SettingsService: vi.fn().mockImplementation(() => ({ + getSettings: () => ({ + preferences: { + gitToken: 'ghp_test_token', + }, + updatedAt: Date.now(), + }), + })), +})) + +describe('repoService.cloneRepo auth env', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('passes github extraheader env to git clone', async () => { + const { cloneRepo } = await import('../../src/services/repo') + + const database = {} as any + const repoUrl = 'https://github.com/acme/forge.git' + + getRepoByUrlAndBranch.mockReturnValue(null) + createRepo.mockReturnValue({ + id: 1, + repoUrl, + localPath: 'forge', + defaultBranch: 'main', + cloneStatus: 'cloning', + clonedAt: Date.now(), + }) + + executeCommand + .mockResolvedValueOnce('missing') + .mockResolvedValueOnce('missing') + .mockResolvedValueOnce('') + + await cloneRepo(database, repoUrl) + + const expectedEnv = createGitHubGitEnv('ghp_test_token') + + expect(executeCommand).toHaveBeenNthCalledWith( + 3, + ['git', 'clone', repoUrl, 'forge'], + { cwd: getReposPath(), env: expectedEnv } + ) + + expect(ensureDirectoryExists).toHaveBeenCalledWith(getReposPath()) + expect(updateRepoStatus).toHaveBeenCalledWith(database, 1, 'ready') + expect(deleteRepo).not.toHaveBeenCalled() + }) +})