diff --git a/Cargo.lock b/Cargo.lock index 51f07ad..ae43d4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3695,6 +3695,9 @@ dependencies = [ "rhema-core", "rhema-host-agent", "rhema-provider", + "rhema-provider-chatgpt", + "rhema-provider-copilot", + "rhema-provider-mistral", "rhema-provider-registry", "rhema-sandbox", "rhema-sandbox-ssh", diff --git a/Cargo.toml b/Cargo.toml index c38547f..fa10316 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,9 @@ rhema-bash = { path = "../rhema/crates/rhema-bash" } rhema-core = { path = "../rhema/crates/rhema-core" } rhema-host-agent = { path = "../rhema/crates/rhema-host-agent" } rhema-provider = { path = "../rhema/crates/rhema-provider" } +rhema-provider-chatgpt = { path = "../rhema/crates/rhema-provider-chatgpt" } +rhema-provider-copilot = { path = "../rhema/crates/rhema-provider-copilot" } +rhema-provider-mistral = { path = "../rhema/crates/rhema-provider-mistral" } rhema-provider-registry = { path = "../rhema/crates/rhema-provider-registry" } rhema-sandbox = { path = "../rhema/crates/rhema-sandbox" } rhema-sandbox-ssh = { path = "../rhema/crates/rhema-sandbox-ssh" } diff --git a/README.md b/README.md index 753ec4f..6273e5e 100644 --- a/README.md +++ b/README.md @@ -102,9 +102,11 @@ issue certificates. ## First room -1. **Settings โ†’ Providers.** Add a provider kind and key. The key is - sealed with the server's master key before it touches SQLite. A new - provider stores no model; the room picks one. +1. **Settings โ†’ Providers.** Add a provider kind and its key, address, + or sign-in. For GitHub Copilot, ChatGPT, and Mistral Vibe the dialog + runs the provider's sign-in. The credential is sealed with the + server's master key before it touches SQLite. A new provider stores + no model; the room picks one. 2. **Settings โ†’ Sandboxes.** Add a target. Leave the private key empty and the server generates an ed25519 pair and shows the public key. Append that line to `~/.ssh/authorized_keys` on the target. Set the diff --git a/specs/rhema-together.md b/specs/rhema-together.md index 7e923b6..c6a2506 100644 --- a/specs/rhema-together.md +++ b/specs/rhema-together.md @@ -526,7 +526,29 @@ private range in the config when every user is on the same network. Provider keys and sandbox private keys are encrypted at rest with a key from the environment or a 0600 file. The server refuses to start without -it. No route, log line, or event carries a key. +it. No route, log line, or event carries a stored key. + +### Provider sign-in + +GitHub Copilot, ChatGPT, and Mistral Vibe do not ask for a key. The +server runs the adapter's `InteractiveLogin` and keeps a per-account +record of its last update. The browser asks the server to start the +flow, polls the record, and renders the instruction, URL, and code. It +never receives the credential. When the adapter completes, the server +seals the credential and inserts the provider row before the browser +sees the completion, so a missed poll cannot lose a token. Closing the +dialog cancels the flow. Records expire after 15 minutes, and only +their owner can read or cancel them. They live in memory, so a restart +drops a sign-in in progress. No provider row exists until the adapter +completes. + +ChatGPT's callback returns to loopback port 1455, or 1457 when 1455 is +taken. The machine that runs the browser must forward that port to the +server before opening the URL. Copilot's device code and Mistral Vibe's +console sign-in need no inbound port. + +A sign-in URL can carry a short-lived device or PKCE token. The server +does not log it, and it is not the stored provider key. ## 9. Storage @@ -669,8 +691,9 @@ This repository, as committed: provider switch. - A model picker over the provider's live catalog, with context, output, price, and vision from the adapter and models.dev. A custom - id is always accepted. Adding a provider asks for its kind and key; - the room chooses the model. + id is always accepted. The add-provider dialog asks for a kind and + key, or runs a sign-in for GitHub Copilot, ChatGPT, and Mistral Vibe. + The room chooses the model. - One conversation per room, a `@rhema` mention starts a turn, human messages are stamped with their author's name, and only the `message` tool puts agent text in the room. diff --git a/src/api/mod.rs b/src/api/mod.rs index b2ed95e..4cada65 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -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", diff --git a/src/api/settings.rs b/src/api/settings.rs index 5df5853..6143f36 100644 --- a/src/api/settings.rs +++ b/src/api/settings.rs @@ -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) -> AppResult> { let conn = state.db.conn(); @@ -48,7 +56,11 @@ pub async fn list_providers(user: AuthUser, State(state): State) -> AppR }) })?; let configs = rows.collect::, _>>()?; - 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 { + 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> { + 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, + Json(body): Json, +) -> AppResult> { + 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, + Path(id): Path, +) -> AppResult { + 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, + Path(id): Path, +) -> AppResult> { + 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()); + } +} diff --git a/src/login.rs b/src/login.rs new file mode 100644 index 0000000..9ca3c4a --- /dev/null +++ b/src/login.rs @@ -0,0 +1,397 @@ +//! Provider sign-in flows running on the server. +//! +//! A flow is an `InteractiveLogin` from a provider adapter plus a +//! per-account record of what it last told the browser. The browser +//! polls the record, never the provider, and the completed credential +//! goes straight into the secret box through the caller's closure. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use rhema_provider::{InteractiveLogin, LoginInstruction, LoginSink, LoginUpdate}; +use serde::Serialize; +use tokio::task::JoinHandle; + +/// How long a flow record survives. The adapters time out after ten +/// minutes; this leaves room to read a result before the sweep. +const FLOW_TTL_MS: i64 = 15 * 60 * 1000; + +/// The account's running and finished sign-in flows. +#[derive(Default)] +pub struct Logins { + flows: Mutex>>, +} + +/// What a client sees when it polls one flow. +#[derive(Debug, Clone, Serialize)] +pub struct LoginSnapshot { + pub status: LoginPhase, + #[serde(skip_serializing_if = "Option::is_none")] + pub instruction: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub provider_id: Option, +} + +/// The phase a flow is in. The terminal phases never leave once set. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum LoginPhase { + #[default] + Starting, + Instruct, + Waiting, + Completed, + Failed, +} + +impl LoginPhase { + fn terminal(self) -> bool { + matches!(self, Self::Completed | Self::Failed) + } +} + +/// The instruction in a form the browser can render. +#[derive(Debug, Clone, Serialize)] +pub struct LoginStep { + pub text: String, + pub url: Option, + pub code: Option, +} + +/// The caller's completion hook: seal and store the credential, and +/// return the new provider id, or the reason it could not. +pub type Complete = Box Result + Send>; + +/// One flow and the last update it reported. +struct LoginFlow { + account_id: String, + created_at: i64, + inner: Mutex, + task: Mutex>>, +} + +#[derive(Default)] +struct Inner { + phase: LoginPhase, + instruction: Option, + message: Option, + provider_id: Option, +} + +impl LoginFlow { + fn new(account_id: String) -> Self { + Self { + account_id, + created_at: crate::util::now_ms(), + inner: Mutex::new(Inner::default()), + task: Mutex::new(None), + } + } + + fn snapshot(&self) -> LoginSnapshot { + let inner = self.inner.lock().unwrap_or_else(|err| err.into_inner()); + LoginSnapshot { + status: inner.phase, + instruction: inner.instruction.clone(), + message: inner.message.clone(), + provider_id: inner.provider_id.clone(), + } + } + + fn set_task(&self, handle: JoinHandle<()>) { + *self.task.lock().unwrap_or_else(|err| err.into_inner()) = Some(handle); + } + + fn terminal(&self) -> bool { + self.inner + .lock() + .unwrap_or_else(|err| err.into_inner()) + .phase + .terminal() + } + + fn instruct(&self, step: LoginStep) { + let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner()); + if inner.phase.terminal() { + return; + } + inner.phase = LoginPhase::Instruct; + inner.instruction = Some(step); + inner.message = None; + } + + fn waiting(&self, text: String) { + let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner()); + if inner.phase.terminal() { + return; + } + inner.phase = LoginPhase::Waiting; + inner.message = Some(text); + } + + fn completed(&self, provider_id: String) { + let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner()); + if inner.phase.terminal() { + return; + } + inner.phase = LoginPhase::Completed; + inner.message = None; + inner.provider_id = Some(provider_id); + } + + fn failed(&self, message: String) { + let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner()); + if inner.phase.terminal() { + return; + } + inner.phase = LoginPhase::Failed; + inner.message = Some(message); + } + + /// A flow that returns without a terminal update leaves a record + /// stuck in `waiting`; this closes it. + fn finish_if_running(&self) { + let mut inner = self.inner.lock().unwrap_or_else(|err| err.into_inner()); + if inner.phase.terminal() { + return; + } + inner.phase = LoginPhase::Failed; + inner.message = Some("the sign-in ended without a result".to_owned()); + } + + fn cancel(&self, message: &str) { + // Mark the record first: a completion that lands while the task + // unwinds sees a terminal phase and skips the credential. + self.failed(message.to_owned()); + if let Some(task) = self + .task + .lock() + .unwrap_or_else(|err| err.into_inner()) + .take() + { + task.abort(); + } + } +} + +/// The sink that writes a flow's updates into its record, and stores +/// the credential when the adapter completes. +struct FlowSink { + flow: Arc, + complete: Option, +} + +impl LoginSink for FlowSink { + fn update(&mut self, update: LoginUpdate) { + match update { + LoginUpdate::Instruct(LoginInstruction { text, url, code }) => { + self.flow.instruct(LoginStep { text, url, code }); + } + LoginUpdate::Waiting(text) => self.flow.waiting(text), + LoginUpdate::Failed(message) => self.flow.failed(message), + LoginUpdate::Completed(token) => { + let Some(complete) = self.complete.take() else { + return; + }; + // A canceled flow was removed from the map; the adapter + // may still report completion before its task unwinds. + if self.flow.terminal() { + return; + } + match complete(&token) { + Ok(provider_id) => self.flow.completed(provider_id), + Err(message) => self.flow.failed(message), + } + } + } + } +} + +impl Logins { + /// Starts `flow` for `account_id`. `complete` runs once, on the + /// flow's credential, and its result is what the browser sees. + pub fn start( + &self, + account_id: &str, + flow: Box, + complete: Complete, + ) -> String { + self.sweep(); + let id = crate::util::random_id(12); + let record = Arc::new(LoginFlow::new(account_id.to_owned())); + self.flows + .lock() + .unwrap_or_else(|err| err.into_inner()) + .insert(id.clone(), record.clone()); + let task_record = record.clone(); + let handle = tokio::spawn(async move { + let mut sink = FlowSink { + flow: task_record.clone(), + complete: Some(complete), + }; + flow.run(&mut sink).await; + task_record.finish_if_running(); + }); + record.set_task(handle); + id + } + + /// The flow's last update, when it belongs to `account_id`. + pub fn snapshot(&self, account_id: &str, id: &str) -> Option { + let flow = self + .flows + .lock() + .unwrap_or_else(|err| err.into_inner()) + .get(id) + .cloned()?; + (flow.account_id == account_id).then(|| flow.snapshot()) + } + + /// Ends and forgets a flow. Only its owner can do it. + pub fn cancel(&self, account_id: &str, id: &str) -> bool { + let flow = self + .flows + .lock() + .unwrap_or_else(|err| err.into_inner()) + .get(id) + .cloned(); + let Some(flow) = flow else { + return false; + }; + if flow.account_id != account_id { + return false; + } + self.flows + .lock() + .unwrap_or_else(|err| err.into_inner()) + .remove(id); + flow.cancel("the sign-in was canceled"); + true + } + + /// Drops records that outlived the adapters' own timeouts. + fn sweep(&self) { + let now = crate::util::now_ms(); + let stale: Vec<(String, Arc)> = self + .flows + .lock() + .unwrap_or_else(|err| err.into_inner()) + .iter() + .filter(|(_, flow)| now - flow.created_at > FLOW_TTL_MS) + .map(|(id, flow)| (id.clone(), flow.clone())) + .collect(); + if stale.is_empty() { + return; + } + let mut flows = self.flows.lock().unwrap_or_else(|err| err.into_inner()); + for (id, flow) in stale { + flows.remove(&id); + flow.cancel("the sign-in expired"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn step() -> LoginStep { + LoginStep { + text: "open the page".to_owned(), + url: Some("https://example.com/device".to_owned()), + code: Some("ABCD-1234".to_owned()), + } + } + + #[test] + fn waiting_keeps_the_instruction_visible() { + let flow = LoginFlow::new("acct".to_owned()); + flow.instruct(step()); + flow.waiting("waiting for the browser".to_owned()); + let snapshot = flow.snapshot(); + assert_eq!(snapshot.status, LoginPhase::Waiting); + assert_eq!( + snapshot.instruction.expect("instruction").code.as_deref(), + Some("ABCD-1234") + ); + assert_eq!(snapshot.message.as_deref(), Some("waiting for the browser")); + } + + #[test] + fn a_terminal_phase_never_moves_again() { + let flow = LoginFlow::new("acct".to_owned()); + flow.completed("provider".to_owned()); + flow.failed("too late".to_owned()); + flow.waiting("too late".to_owned()); + let snapshot = flow.snapshot(); + assert_eq!(snapshot.status, LoginPhase::Completed); + assert_eq!(snapshot.provider_id.as_deref(), Some("provider")); + assert_eq!(snapshot.message, None); + } + + #[test] + fn a_flow_that_returns_early_is_closed() { + let flow = LoginFlow::new("acct".to_owned()); + flow.instruct(step()); + flow.finish_if_running(); + let snapshot = flow.snapshot(); + assert_eq!(snapshot.status, LoginPhase::Failed); + assert_eq!( + snapshot.message.as_deref(), + Some("the sign-in ended without a result") + ); + } + + #[tokio::test] + async fn another_account_cannot_read_or_cancel_the_flow() { + let logins = Logins::default(); + let flow: Box = Box::new(Immediate); + let id = logins.start("owner", flow, Box::new(|_| Ok("provider".to_owned()))); + assert!(logins.snapshot("other", &id).is_none()); + assert!(!logins.cancel("other", &id)); + assert!(logins.snapshot("owner", &id).is_some()); + } + + struct Immediate; + + #[async_trait::async_trait] + impl InteractiveLogin for Immediate { + async fn run(&self, _sink: &mut dyn LoginSink) {} + } + + struct Completes; + + #[async_trait::async_trait] + impl InteractiveLogin for Completes { + async fn run(&self, sink: &mut dyn LoginSink) { + sink.update(LoginUpdate::Completed("the-token".to_owned())); + } + } + + #[tokio::test] + async fn the_completion_hook_stores_the_credential_and_names_the_provider() { + let logins = Logins::default(); + let id = logins.start( + "owner", + Box::new(Completes), + Box::new(|token| { + assert_eq!(token, "the-token"); + Ok("provider".to_owned()) + }), + ); + for _ in 0..10 { + if logins + .snapshot("owner", &id) + .is_some_and(|snapshot| snapshot.status == LoginPhase::Completed) + { + break; + } + tokio::task::yield_now().await; + } + let snapshot = logins.snapshot("owner", &id).expect("snapshot"); + assert_eq!(snapshot.status, LoginPhase::Completed); + assert_eq!(snapshot.provider_id.as_deref(), Some("provider")); + } +} diff --git a/src/main.rs b/src/main.rs index 361df63..4af5981 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ mod config; mod crypto; mod db; mod error; +mod login; mod models; mod presence; mod preview; @@ -45,6 +46,7 @@ async fn main() -> anyhow::Result<()> { rooms: Default::default(), previews: Default::default(), presence: Default::default(), + logins: Default::default(), }); let app = api::router(state).layer(TraceLayer::new_for_http()); let listener = tokio::net::TcpListener::bind(&config.listen).await?; diff --git a/src/state.rs b/src/state.rs index 78824fc..0a21c20 100644 --- a/src/state.rs +++ b/src/state.rs @@ -127,6 +127,7 @@ pub struct AppState { pub rooms: RoomRunner, pub previews: PreviewTunnels, pub presence: crate::presence::Presence, + pub logins: crate::login::Logins, } /// The state behind an `Arc`. diff --git a/web/app/assets/css/main.css b/web/app/assets/css/main.css index 265f0e8..ab5f280 100644 --- a/web/app/assets/css/main.css +++ b/web/app/assets/css/main.css @@ -464,6 +464,44 @@ button { line-height: var(--lh-body); } +.signin { + display: flex; + flex-direction: column; + gap: var(--sp-4); +} + +.signin .dialog-actions { + margin-top: 0; +} + +.signin-actions { + display: flex; + flex-wrap: wrap; + gap: var(--sp-2); +} + +.signin-link:hover { + text-decoration: none; +} + +.signin-code { + display: flex; + flex-direction: column; + gap: var(--sp-1); +} + +.signin-code-value { + align-self: flex-start; + padding: var(--sp-2) var(--sp-3); + border: 1px solid var(--border); + border-radius: var(--r-control); + background: var(--surface-2); + font-family: var(--font-mono); + font-size: var(--fs-code); + letter-spacing: 0.08em; + white-space: pre; +} + .form-note { color: var(--muted); font-size: var(--fs-meta); diff --git a/web/app/pages/settings.vue b/web/app/pages/settings.vue index d9e88a0..9944074 100644 --- a/web/app/pages/settings.vue +++ b/web/app/pages/settings.vue @@ -1,15 +1,17 @@