feat: add API key validation flow for AI provider config
All checks were successful
Beta Release / beta (push) Successful in 37s
All checks were successful
Beta Release / beta (push) Successful in 37s
- Add POST /api/providers/validate backend endpoint that sends a test request to the provider's chat/completions API to verify the key - Add validateProvider to frontend API client - Redesign PanelProviders: show token input inline with Validate button, display valid/invalid badge after validation, Save only appears after successful validation - Add i18n keys (EN/FR) for validation flow 💾 Generated with Crush Assisted-by: GLM-5-Turbo via Crush <crush@charm.land>
This commit is contained in:
@@ -1,9 +1,13 @@
|
|||||||
package api
|
package api
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/muyue/muyue/internal/config"
|
"github.com/muyue/muyue/internal/config"
|
||||||
"github.com/muyue/muyue/internal/lsp"
|
"github.com/muyue/muyue/internal/lsp"
|
||||||
@@ -529,3 +533,95 @@ func (s *Server) handleRunUpdate(w http.ResponseWriter, r *http.Request) {
|
|||||||
"updated": len(needsUpdate),
|
"updated": len(needsUpdate),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleValidateProvider(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != "POST" {
|
||||||
|
writeError(w, "POST only", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
APIKey string `json:"api_key"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
BaseURL string `json:"base_url"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||||
|
writeError(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if body.APIKey == "" {
|
||||||
|
writeError(w, "api_key required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
baseURL := body.BaseURL
|
||||||
|
if baseURL == "" {
|
||||||
|
for _, p := range s.config.AI.Providers {
|
||||||
|
if p.Name == body.Name {
|
||||||
|
baseURL = p.BaseURL
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if baseURL == "" {
|
||||||
|
switch body.Name {
|
||||||
|
case "minimax":
|
||||||
|
baseURL = "https://api.minimax.io/v1"
|
||||||
|
case "openai":
|
||||||
|
baseURL = "https://api.openai.com/v1"
|
||||||
|
case "anthropic":
|
||||||
|
baseURL = "https://api.anthropic.com/v1"
|
||||||
|
default:
|
||||||
|
baseURL = "https://api.minimax.io/v1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
model := body.Model
|
||||||
|
if model == "" {
|
||||||
|
for _, p := range s.config.AI.Providers {
|
||||||
|
if p.Name == body.Name {
|
||||||
|
model = p.Model
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if model == "" {
|
||||||
|
model = "MiniMax-Text-01"
|
||||||
|
}
|
||||||
|
|
||||||
|
reqBody, _ := json.Marshal(map[string]interface{}{
|
||||||
|
"model": model,
|
||||||
|
"messages": []map[string]string{{"role": "user", "content": "Hi"}},
|
||||||
|
"max_tokens": 5,
|
||||||
|
"stream": false,
|
||||||
|
})
|
||||||
|
|
||||||
|
url := strings.TrimRight(baseURL, "/") + "/chat/completions"
|
||||||
|
req, err := http.NewRequest("POST", url, bytes.NewReader(reqBody))
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+body.APIKey)
|
||||||
|
|
||||||
|
client := &http.Client{Timeout: 15 * time.Second}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, "connection failed: "+err.Error(), http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
|
||||||
|
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
||||||
|
writeError(w, "invalid_api_key", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
writeError(w, "api_error: "+string(respBody), http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, map[string]interface{}{"status": "valid"})
|
||||||
|
}
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ func (s *Server) routes() {
|
|||||||
s.mux.HandleFunc("/api/mcp/configure", s.handleMCPConfigure)
|
s.mux.HandleFunc("/api/mcp/configure", s.handleMCPConfigure)
|
||||||
s.mux.HandleFunc("/api/config/profile", s.handleSaveProfile)
|
s.mux.HandleFunc("/api/config/profile", s.handleSaveProfile)
|
||||||
s.mux.HandleFunc("/api/config/provider", s.handleSaveProvider)
|
s.mux.HandleFunc("/api/config/provider", s.handleSaveProvider)
|
||||||
|
s.mux.HandleFunc("/api/providers/validate", s.handleValidateProvider)
|
||||||
s.mux.HandleFunc("/api/update/run", s.handleRunUpdate)
|
s.mux.HandleFunc("/api/update/run", s.handleRunUpdate)
|
||||||
s.mux.HandleFunc("/api/chat", s.handleChat)
|
s.mux.HandleFunc("/api/chat", s.handleChat)
|
||||||
s.mux.HandleFunc("/api/chat/history", s.handleChatHistory)
|
s.mux.HandleFunc("/api/chat/history", s.handleChatHistory)
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ const api = {
|
|||||||
savePreferences: (prefs) => request('/preferences', { method: 'PUT', body: JSON.stringify(prefs) }),
|
savePreferences: (prefs) => request('/preferences', { method: 'PUT', body: JSON.stringify(prefs) }),
|
||||||
saveProfile: (profile) => request('/config/profile', { method: 'PUT', body: JSON.stringify(profile) }),
|
saveProfile: (profile) => request('/config/profile', { method: 'PUT', body: JSON.stringify(profile) }),
|
||||||
saveProvider: (provider) => request('/config/provider', { method: 'PUT', body: JSON.stringify(provider) }),
|
saveProvider: (provider) => request('/config/provider', { method: 'PUT', body: JSON.stringify(provider) }),
|
||||||
|
validateProvider: (provider) => request('/providers/validate', { method: 'POST', body: JSON.stringify(provider) }),
|
||||||
runUpdate: (tool) => request('/update/run', { method: 'POST', body: JSON.stringify({ tool: tool || '' }) }),
|
runUpdate: (tool) => request('/update/run', { method: 'POST', body: JSON.stringify({ tool: tool || '' }) }),
|
||||||
runCommand: (command, cwd) => request('/terminal', { method: 'POST', body: JSON.stringify({ command, cwd }) }),
|
runCommand: (command, cwd) => request('/terminal', { method: 'POST', body: JSON.stringify({ command, cwd }) }),
|
||||||
getTerminalSessions: () => request('/terminal/sessions'),
|
getTerminalSessions: () => request('/terminal/sessions'),
|
||||||
|
|||||||
@@ -252,48 +252,79 @@ function PanelProfile({ config, editProfile, profileForm, setProfileForm, setEdi
|
|||||||
}
|
}
|
||||||
|
|
||||||
function PanelProviders({ providers, editProvider, providerForm, setProviderForm, setEditProvider, openProviderEdit, handleSaveProvider, api, loadData, t }) {
|
function PanelProviders({ providers, editProvider, providerForm, setProviderForm, setEditProvider, openProviderEdit, handleSaveProvider, api, loadData, t }) {
|
||||||
|
const [validating, setValidating] = useState(null)
|
||||||
|
const [validationStatus, setValidationStatus] = useState(null)
|
||||||
|
|
||||||
|
const handleValidate = async (name, apiKey, model, baseUrl) => {
|
||||||
|
setValidating(name)
|
||||||
|
setValidationStatus(null)
|
||||||
|
try {
|
||||||
|
await api.validateProvider({ name, api_key: apiKey, model, base_url: baseUrl })
|
||||||
|
setValidationStatus({ provider: name, valid: true })
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err.message || ''
|
||||||
|
if (msg.includes('invalid_api_key')) {
|
||||||
|
setValidationStatus({ provider: name, valid: false, error: t('config.keyInvalid') })
|
||||||
|
} else {
|
||||||
|
setValidationStatus({ provider: name, valid: false, error: `${t('config.connectionFailed')}: ${msg}` })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setValidating(null)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="config-providers-list">
|
<div className="config-providers-list">
|
||||||
{providers.map((p, i) => (
|
<div className="provider-setup-hint">{t('config.setupDescription')}</div>
|
||||||
<div key={i} className="config-card provider-card-v2">
|
{providers.map((p, i) => {
|
||||||
<div className="provider-card-top">
|
const isEditing = editProvider === p.name
|
||||||
<div className="provider-card-identity">
|
const isValidationTarget = validationStatus?.provider === p.name
|
||||||
<span className="provider-card-name">{p.name}</span>
|
return (
|
||||||
{p.active && <span className="badge accent">{t('config.active')}</span>}
|
<div key={i} className="config-card provider-card-v2">
|
||||||
</div>
|
<div className="provider-card-top">
|
||||||
<div className="provider-card-actions">
|
<div className="provider-card-identity">
|
||||||
{editProvider !== p.name && (
|
<span className="provider-card-name">{p.name}</span>
|
||||||
<button className="ghost sm" onClick={() => openProviderEdit(p)}>{t('config.editProvider')}</button>
|
{p.apiKey && <span className="badge ok">{t('config.keyConfigured')}</span>}
|
||||||
)}
|
{!p.apiKey && <span className="badge error">{t('config.noKey')}</span>}
|
||||||
{!p.active && editProvider !== p.name && (
|
{isValidationTarget && validationStatus.valid && <span className="badge ok">{t('config.keyValid')}</span>}
|
||||||
<button className="sm" onClick={async () => {
|
{isValidationTarget && !validationStatus.valid && <span className="badge error">{validationStatus.error}</span>}
|
||||||
await api.saveProvider({ name: p.name, active: true })
|
|
||||||
loadData()
|
|
||||||
}}>{t('config.activate')}</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{editProvider !== p.name ? (
|
|
||||||
<div className="provider-card-meta">
|
|
||||||
<span className="mono">{p.model || '—'}</span>
|
|
||||||
<span style={{ color: p.apiKey ? 'var(--success)' : 'var(--error)' }}>
|
|
||||||
{p.apiKey ? t('config.keyConfigured') : t('config.noKey')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="provider-card-form">
|
|
||||||
<FormInput label={t('config.apiKey')} value={providerForm.api_key} onChange={v => setProviderForm(f => ({ ...f, api_key: v }))} type="password" />
|
|
||||||
<FormInput label={t('config.model')} value={providerForm.model} onChange={v => setProviderForm(f => ({ ...f, model: v }))} />
|
|
||||||
<FormInput label={t('config.baseUrl')} value={providerForm.base_url} onChange={v => setProviderForm(f => ({ ...f, base_url: v }))} />
|
|
||||||
<div className="config-card-actions">
|
|
||||||
<button className="primary sm" onClick={handleSaveProvider}>{t('config.save')}</button>
|
|
||||||
<button className="ghost sm" onClick={() => setEditProvider(null)}>{t('config.cancel')}</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</div>
|
<div className="provider-card-form">
|
||||||
))}
|
<div className="provider-setup-token-row">
|
||||||
|
<div className="provider-setup-token-input">
|
||||||
|
<label className="config-form-label">{t('config.apiKey')}</label>
|
||||||
|
<input
|
||||||
|
className="config-form-input"
|
||||||
|
type="password"
|
||||||
|
placeholder={t('config.tokenPlaceholder')}
|
||||||
|
value={isEditing ? providerForm.api_key : ''}
|
||||||
|
onChange={e => {
|
||||||
|
if (!isEditing) openProviderEdit(p)
|
||||||
|
setProviderForm(f => ({ ...f, api_key: e.target.value }))
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="provider-setup-token-actions">
|
||||||
|
<button
|
||||||
|
className="sm primary"
|
||||||
|
disabled={validating === p.name || !providerForm.api_key}
|
||||||
|
onClick={() => handleValidate(p.name, providerForm.api_key, providerForm.model, providerForm.base_url)}
|
||||||
|
>
|
||||||
|
{validating === p.name ? t('config.validating') : t('config.validateKey')}
|
||||||
|
</button>
|
||||||
|
{isValidationTarget && validationStatus.valid && (
|
||||||
|
<button className="sm" onClick={handleSaveProvider}>{t('config.save')}</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="provider-card-meta" style={{ marginTop: 8 }}>
|
||||||
|
<span className="mono">{p.model || '—'}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -166,6 +166,14 @@ const en = {
|
|||||||
editProfile: 'Edit',
|
editProfile: 'Edit',
|
||||||
cancel: 'Cancel',
|
cancel: 'Cancel',
|
||||||
editProvider: 'Configure',
|
editProvider: 'Configure',
|
||||||
|
validateKey: 'Validate',
|
||||||
|
validating: 'Validating...',
|
||||||
|
keyValid: 'Valid key',
|
||||||
|
keyInvalid: 'Invalid key',
|
||||||
|
connectionFailed: 'Connection failed',
|
||||||
|
enterToken: 'Enter your API token for {provider}',
|
||||||
|
tokenPlaceholder: 'sk-...',
|
||||||
|
setupDescription: 'Configure your AI provider token to use the assistant.',
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -165,6 +165,14 @@ const fr = {
|
|||||||
missing: 'Manquant',
|
missing: 'Manquant',
|
||||||
editProfile: 'Modifier',
|
editProfile: 'Modifier',
|
||||||
editProvider: 'Configurer',
|
editProvider: 'Configurer',
|
||||||
|
validateKey: 'Valider',
|
||||||
|
validating: 'Vérification...',
|
||||||
|
keyValid: 'Clé valide',
|
||||||
|
keyInvalid: 'Clé invalide',
|
||||||
|
connectionFailed: 'Connexion échouée',
|
||||||
|
enterToken: 'Entrez votre token API pour {provider}',
|
||||||
|
tokenPlaceholder: 'sk-...',
|
||||||
|
setupDescription: 'Configurez le token de votre fournisseur IA pour utiliser l\'assistant.',
|
||||||
cancel: 'Annuler',
|
cancel: 'Annuler',
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -475,6 +475,15 @@ input::placeholder { color: var(--text-disabled); }
|
|||||||
.provider-card-meta { display: flex; gap: 16px; font-size: 12px; color: var(--text-tertiary); font-family: var(--font-mono); margin-top: 8px; }
|
.provider-card-meta { display: flex; gap: 16px; font-size: 12px; color: var(--text-tertiary); font-family: var(--font-mono); margin-top: 8px; }
|
||||||
.provider-card-form { margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border); }
|
.provider-card-form { margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border); }
|
||||||
|
|
||||||
|
.provider-setup-hint {
|
||||||
|
font-size: 13px; color: var(--text-tertiary); margin-bottom: 16px;
|
||||||
|
padding: 10px 14px; border-radius: var(--radius); background: var(--bg-surface);
|
||||||
|
border-left: 3px solid var(--accent-dim);
|
||||||
|
}
|
||||||
|
.provider-setup-token-row { display: flex; gap: 12px; align-items: flex-end; }
|
||||||
|
.provider-setup-token-input { flex: 1; }
|
||||||
|
.provider-setup-token-actions { display: flex; gap: 8px; flex-shrink: 0; padding-bottom: 1px; }
|
||||||
|
|
||||||
.config-update-controls {
|
.config-update-controls {
|
||||||
display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap;
|
display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user