* Fix git credential saving and improve host matching

- Fix token masking bug in GitCredentialDialog that corrupted tokens on edit
- Add tokenEdited state to preserve original token when not modified
- Default new credential host to https://github.com
- Add normalizeHostname helper for consistent host comparison
- Improve credential lookup logging to show configured vs requested hosts
- Remove overly permissive fuzzy matching that could leak tokens

* Make OpenCode reload non-fatal when saving git credentials

Settings are now saved to database even if the OpenCode server reload
fails. The reload error is returned separately so the UI can inform
the user that credentials were saved but the server needs a manual
restart.

* Fix git fetch using credentials in silent mode

Previously, silent mode (used for UI fetch operations) would skip
credential lookup entirely and return empty, causing auth failures.
Now credentials are always looked up via IPC regardless of silent mode.
This commit is contained in:
Chris Scott authored and GitHub committed 2026-01-25 00:38:47 -05:00
1 parent 3a8d4993c1
commit 24aa4f6c83
6 files changed
+80 -39

No files matched your search

+2 -7
View File
@@ -33,13 +33,8 @@ function main(argv: string[]): void {
const ipcHandlePath = process.env['VSCODE_GIT_IPC_HANDLE']
console.error(`[askpass-main] pid=${process.pid}, output=${output}, askpassType=${askpassType}, ipcHandlePath=${ipcHandlePath}, argv=${argv.join(', ')}`)
if (process.env['VSCODE_GIT_FETCH_SILENT']) {
console.error('[askpass-main] Silent fetch mode, returning empty')
fs.writeFileSync(output, '\n')
return process.exit(0)
}
const isSilent = !!process.env['VSCODE_GIT_FETCH_SILENT']
console.error(`[askpass-main] pid=${process.pid}, output=${output}, askpassType=${askpassType}, ipcHandlePath=${ipcHandlePath}, silent=${isSilent}, argv=${argv.join(', ')}`)
if (!ipcHandlePath) {
console.error('[askpass-main] No IPC handle, returning empty')
+34 -18
View File
@@ -88,34 +88,50 @@ 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> {
logger.info(`Looking up credentials for host: ${hostname}`)
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 gitCredentials: GitCredential[] = settings.preferences.gitCredentials || []
logger.info(`Found ${gitCredentials.length} configured git credentials`)
for (const cred of gitCredentials) {
try {
const parsed = new URL(cred.host)
if (parsed.hostname.toLowerCase() === hostname.toLowerCase()) {
logger.info(`Found matching credential for ${hostname}`)
return {
username: cred.username || this.getDefaultUsername(cred.host),
password: cred.token,
}
}
} catch {
if (cred.host.toLowerCase().includes(hostname.toLowerCase())) {
logger.info(`Found matching credential (fuzzy match) for ${hostname}`)
return {
username: cred.username || 'oauth2',
password: cred.token,
}
const normalizedCred = this.normalizeHostname(cred.host)
logger.debug(`Comparing: request='${normalizedRequest}' vs stored='${normalizedCred}' (raw: ${cred.host})`)
if (normalizedCred === normalizedRequest) {
logger.info(`Found matching credential '${cred.name}' for ${hostname}`)
return {
username: cred.username || this.getDefaultUsername(cred.host),
password: cred.token,
}
}
}
logger.warn(`No credentials found for host: ${hostname}`)
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
}
+9 -3
View File
@@ -101,14 +101,20 @@ export function createSettingsRoutes(db: Database) {
const identityChanged = validated.preferences.gitIdentity !== undefined &&
JSON.stringify(currentSettings.preferences.gitIdentity || {}) !== JSON.stringify(validated.preferences.gitIdentity)
let reloadError: string | undefined
if (credentialsChanged || identityChanged) {
const changeType = [credentialsChanged && 'credentials', identityChanged && 'identity'].filter(Boolean).join(' and ')
logger.info(`Git ${changeType} changed, reloading OpenCode configuration`)
await opencodeServerManager.reloadConfig()
serverRestarted = true
try {
await opencodeServerManager.reloadConfig()
serverRestarted = true
} catch (error) {
logger.warn('Failed to reload OpenCode config after git settings change:', error)
reloadError = error instanceof Error ? error.message : 'Unknown error'
}
}
return c.json({ ...settings, serverRestarted })
return c.json({ ...settings, serverRestarted, reloadError })
} catch (error) {
logger.error('Failed to update settings:', error)
if (error instanceof z.ZodError) {
+1
View File
@@ -58,6 +58,7 @@ export interface SettingsResponse {
preferences: UserPreferences
updatedAt: number
serverRestarted?: boolean
reloadError?: string
}
export interface UpdateSettingsRequest {
@@ -22,22 +22,24 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
token: '',
username: '',
})
const [tokenEdited, setTokenEdited] = useState(false)
const maskToken = (token: string) => {
if (!token) return ''
if (token.length <= 8) return '•'.repeat(token.length)
return token.slice(0, 8) + '...'
return token.slice(0, 4) + '•'.repeat(Math.min(token.length - 4, 12)) + '...'
}
useEffect(() => {
if (open) {
setTokenEdited(false)
if (credential) {
setFormData({
...credential,
token: maskToken(credential.token)
token: ''
})
} else {
setFormData({ name: '', host: '', token: '', username: '' })
setFormData({ name: '', host: 'https://github.com', token: '', username: '' })
}
}
}, [open, credential])
@@ -46,13 +48,20 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
event?.preventDefault()
event?.stopPropagation()
if (!formData.name.trim() || !formData.host.trim() || !formData.token.trim()) {
const isEditing = !!credential
const tokenRequired = isEditing ? tokenEdited : true
if (!formData.name.trim() || !formData.host.trim() || (tokenRequired && !formData.token.trim())) {
showToast.error('Please fill in all required fields')
return
}
try {
await onSave(formData)
const dataToSave: GitCredential = {
...formData,
token: (isEditing && !tokenEdited) ? credential.token : formData.token
}
await onSave(dataToSave)
setFormData({ name: '', host: '', token: '', username: '' })
onOpenChange(false)
} catch {
@@ -91,15 +100,25 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
</div>
<div className="space-y-2">
<Label htmlFor="cred-token">Access Token *</Label>
<Label htmlFor="cred-token">
Access Token {credential && !tokenEdited ? '(unchanged)' : '*'}
</Label>
<Input
id="cred-token"
type="password"
placeholder="Personal access token"
placeholder={credential ? maskToken(credential.token) : 'Personal access token'}
value={formData.token}
onChange={(e) => setFormData({ ...formData, token: e.target.value })}
onChange={(e) => {
setTokenEdited(true)
setFormData({ ...formData, token: e.target.value })
}}
disabled={isSaving}
/>
{credential && !tokenEdited && (
<p className="text-xs text-muted-foreground">
Leave empty to keep existing token
</p>
)}
</div>
<div className="space-y-2">
@@ -124,7 +143,7 @@ export function GitCredentialDialog({ open, onOpenChange, onSave, credential, is
</Button>
<Button
type="submit"
disabled={isSaving || !formData.name.trim() || !formData.host.trim() || !formData.token.trim()}
disabled={isSaving || !formData.name.trim() || !formData.host.trim() || (!credential && !formData.token.trim())}
>
{isSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
{credential ? 'Update' : 'Add'}
@@ -75,9 +75,13 @@ export function GitSettings() {
setIsSaving(true)
try {
showToast.loading('Saving git configuration...', { id: 'git-config' })
await updateSettingsAsync({ gitCredentials, gitIdentity })
const result = await updateSettingsAsync({ gitCredentials, gitIdentity })
setHasChanges(false)
showToast.success('Git configuration saved', { id: 'git-config' })
if (result.reloadError) {
showToast.success('Git configuration saved (server reload pending)', { id: 'git-config' })
} else {
showToast.success('Git configuration saved', { id: 'git-config' })
}
} catch {
showToast.error('Failed to save git configuration', { id: 'git-config' })
} finally {