feat: sign in to Copilot, ChatGPT, and Mistral Vibe

Three provider kinds have a browser sign-in, but the add-provider
dialog only accepted a pasted key. A per-account login record now runs
the adapter's InteractiveLogin on the server, reports the instruction,
URL, and code to the dialog, and stores the credential before the
browser sees completion. The credential never reaches the client.

The dialog gets a sign-in stage for flow kinds, with a link, a
copyable code, and retry after failure. Closing the dialog cancels the
flow. ChatGPT's callback lands on the server's loopback port, and the
instruction names the port to forward.
This commit is contained in:
vhaudiquet committed 2026-11-28 18:06:21 +01:00
1 parent 369075a842
commit f5087220da
12 files changed
+927 -23

No files matched your search

+8
View File
@@ -40,6 +40,14 @@ pub fn router(state: Shared) -> Router {
"/provider-configs",
get(settings::list_providers).post(settings::create_provider),
)
.route(
"/provider-configs/login",
post(settings::start_provider_login),
)
.route(
"/provider-configs/login/{id}",
get(settings::provider_login_status).delete(settings::cancel_provider_login),
)
.route("/provider-configs/{id}", delete(settings::delete_provider))
.route(
"/provider-configs/{id}/models",
+152 -5
View File
@@ -6,7 +6,8 @@ use std::time::Duration;
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use rhema_sandbox::Sandbox;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -27,10 +28,17 @@ const KINDS: &[&str] = &[
"zai",
"mistral",
"mistral-vibe",
"copilot",
"chatgpt",
"opencode",
"llama-cpp",
];
/// Kinds whose credential comes from a browser sign-in instead of a
/// pasted key. The adapter owns the protocol; the server owns the
/// record the browser polls and stores the token it produces.
pub const FLOW_KINDS: &[&str] = &["copilot", "chatgpt", "mistral-vibe"];
/// The caller's provider configurations.
pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
let conn = state.db.conn();
@@ -48,7 +56,11 @@ pub async fn list_providers(user: AuthUser, State(state): State<Shared>) -> AppR
})
})?;
let configs = rows.collect::<Result<Vec<_>, _>>()?;
Ok(Json(json!({ "providers": configs, "kinds": KINDS })))
Ok(Json(json!({
"providers": configs,
"kinds": KINDS,
"flow_kinds": FLOW_KINDS,
})))
}
#[derive(Deserialize)]
@@ -90,10 +102,36 @@ pub async fn create_provider(
if body.kind == "llama-cpp" && base_url.is_none() {
return Err(AppError::bad_request("llama.cpp needs a server url"));
}
if matches!(body.kind.as_str(), "copilot" | "chatgpt") && base_url.is_some() {
return Err(AppError::bad_request("this provider has no base url"));
}
if body.kind != "llama-cpp" && body.api_key.trim().is_empty() {
return Err(AppError::bad_request("an api key is required"));
}
let sealed = state.secrets.seal_str(body.api_key.trim())?;
let id = insert_provider(
&state,
&user.user.id,
name,
&body.kind,
&model,
base_url.as_deref(),
body.api_key.trim(),
)?;
Ok(Json(json!({ "id": id })))
}
/// Seals and stores one provider row. The callers validate the kind
/// and credential first; this only owns the encryption and the insert.
fn insert_provider(
state: &Shared,
account_id: &str,
name: &str,
kind: &str,
model: &str,
base_url: Option<&str>,
api_key: &str,
) -> AppResult<String> {
let sealed = state.secrets.seal_str(api_key)?;
let id = random_id(12);
state.db.conn().execute(
"INSERT INTO provider_configs (id, account_id, name, kind, model, base_url,
@@ -101,18 +139,110 @@ pub async fn create_provider(
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
rusqlite::params![
id,
user.user.id,
account_id,
name,
body.kind,
kind,
model,
base_url,
sealed,
crate::util::now_ms()
],
)?;
Ok(id)
}
/// The adapter behind a flow kind. `None` means the kind takes a pasted
/// key; [`FLOW_KINDS`] is the list the browser uses to choose a stage.
fn login_flow(kind: &str) -> Option<Box<dyn rhema_provider::InteractiveLogin>> {
match kind {
"copilot" => Some(Box::new(rhema_provider_copilot::CopilotLogin::new())),
// The ChatGPT callback lands on the server's loopback port; a
// server cannot open the user's browser for them.
"chatgpt" => Some(Box::new(
rhema_provider_chatgpt::ChatGptLogin::new().with_open_browser(false),
)),
"mistral-vibe" => Some(Box::new(rhema_provider_mistral::MistralVibeLogin::new())),
_ => None,
}
}
#[derive(Deserialize)]
pub struct StartProviderLogin {
pub name: String,
pub kind: String,
}
/// Starts a browser sign-in for a flow kind. The provider row appears
/// only when the flow completes; the browser polls the returned id for
/// instructions and the final provider id.
pub async fn start_provider_login(
user: AuthUser,
State(state): State<Shared>,
Json(body): Json<StartProviderLogin>,
) -> AppResult<Json<Value>> {
if user.user.kind != "user" {
return Err(AppError::forbidden("create an account to add a provider"));
}
let name = body.name.trim();
if name.is_empty() || name.chars().count() > 60 {
return Err(AppError::bad_request("name must be 1 to 60 characters"));
}
let Some(flow) = login_flow(&body.kind) else {
return Err(AppError::bad_request(
"this provider does not have a sign-in flow",
));
};
let complete_state = state.clone();
let account_id = user.user.id.clone();
let provider_name = name.to_owned();
let provider_kind = body.kind.clone();
let complete: crate::login::Complete = Box::new(move |token: &str| {
if token.trim().is_empty() {
return Err("the sign-in returned no credential".to_owned());
}
insert_provider(
&complete_state,
&account_id,
&provider_name,
&provider_kind,
"",
None,
token.trim(),
)
.map_err(|err| err.message)
});
let id = state.logins.start(&user.user.id, flow, complete);
Ok(Json(json!({ "id": id })))
}
/// The flow's last update, for its owner only.
pub async fn provider_login_status(
user: AuthUser,
State(state): State<Shared>,
Path(id): Path<String>,
) -> AppResult<Response> {
let snapshot = state
.logins
.snapshot(&user.user.id, &id)
.ok_or_else(|| AppError::not_found("sign-in not found"))?;
let mut response = Json(snapshot).into_response();
response
.headers_mut()
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
Ok(response)
}
/// Cancels a flow and forgets its record. A completed flow's provider
/// row stays; only the sign-in record goes.
pub async fn cancel_provider_login(
user: AuthUser,
State(state): State<Shared>,
Path(id): Path<String>,
) -> AppResult<Json<Value>> {
state.logins.cancel(&user.user.id, &id);
Ok(Json(json!({ "ok": true })))
}
/// The provider's live model catalog. The registry builds the same
/// adapter a turn uses and asks it for the rows a coding agent can
/// drive; the model-facts decorator fills price, context, and vision
@@ -392,3 +522,20 @@ pub async fn test_target(
Err(err) => Ok(Json(json!({ "ok": false, "detail": err.to_string() }))),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_flow_kind_has_an_adapter() {
for kind in FLOW_KINDS {
assert!(login_flow(kind).is_some(), "{kind} has no login flow");
}
}
#[test]
fn a_keyed_kind_has_no_login_flow() {
assert!(login_flow("anthropic").is_none());
}
}