mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
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:
1 parent
ba08f5c24a
commit
7c8a4fe64c
31 files changed
+1136
-132
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface Repo {
|
||||
lastPulled?: number
|
||||
lastAccessedAt?: number
|
||||
openCodeConfigName?: string
|
||||
gitCredentialId?: string
|
||||
isWorktree?: boolean
|
||||
isLocal?: boolean
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user