Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Batch 9 backend: "Sign in with Claude" for the Claude engine

Lin (kwant bot)904747fced6c
diff --git a/src/drivers/engines.rs b/src/drivers/engines.rs
index a21e32ce..20be8bca 100644
--- a/src/drivers/engines.rs
+++ b/src/drivers/engines.rs
@@ -270,6 +270,9 @@ impl Probe {
#[derive(Debug, Clone, Default)]
pub struct ProbeEnv {
pub claude_bin: Option<String>,
+ /// Set only when kwnt points Claude Code at a config dir of its own (tests, isolated
+ /// sign-in); otherwise the CLI uses its env's `CLAUDE_CONFIG_DIR` or `~/.claude`.
+ pub claude_config_dir: Option<std::path::PathBuf>,
pub codex_bin: Option<String>,
pub grok_bin: Option<String>,
pub anthropic_key: Option<String>,
@@ -297,6 +300,7 @@ impl ProbeEnv {
let ollama_url = db.get_setting("ollama_url").await.ok().flatten();
Self {
claude_bin: super::find_cli_binary("claude"),
+ claude_config_dir: None,
codex_bin: super::find_cli_binary("codex"),
grok_bin: super::find_cli_binary("grok"),
anthropic_key: key(db, "anthropic_api_key", "ANTHROPIC_API_KEY").await,
@@ -319,7 +323,7 @@ pub async fn probe(id: EngineId, env: &ProbeEnv) -> Probe {
pub async fn probe_within(id: EngineId, env: &ProbeEnv, limit: Duration) -> Probe {
let check = async {
match id {
- EngineId::Claude => probe_claude(env.claude_bin.as_deref()).await,
+ EngineId::Claude => probe_claude(env.claude_bin.as_deref(), env.claude_config_dir.as_deref()).await,
EngineId::Codex => probe_codex(env.codex_bin.as_deref()).await,
EngineId::Grok => probe_grok(env.grok_bin.as_deref()).await,
EngineId::AnthropicApi | EngineId::OpenaiApi | EngineId::XaiApi => probe_api(id, env).await,
@@ -339,7 +343,16 @@ struct CmdOut {
}
async fn run(bin: &str, args: &[&str]) -> Result<CmdOut, String> {
- let out = tokio::process::Command::new(bin)
+ run_in(bin, args, None).await
+}
+
+/// [`run`], with Claude Code pointed at `claude_home` when one is given.
+async fn run_in(bin: &str, args: &[&str], claude_home: Option<&std::path::Path>) -> Result<CmdOut, String> {
+ let mut cmd = tokio::process::Command::new(bin);
+ if let Some(home) = claude_home {
+ crate::profiles::CliEnv::for_home(crate::profiles::Engine::Claude, home).apply(&mut cmd);
+ }
+ let out = cmd
.args(args)
.env("NO_COLOR", "1")
.stdin(Stdio::null())
@@ -394,13 +407,13 @@ pub fn claude_cli_models() -> Vec<EngineModel> {
.collect()
}
-async fn probe_claude(bin: Option<&str>) -> Probe {
+async fn probe_claude(bin: Option<&str>, home: Option<&std::path::Path>) -> Probe {
let Some(bin) = bin else {
return Probe::not_installed("Claude Code isn't installed");
};
let version = version_of(bin).await;
// `auth status` asks Claude Code itself, so a login kept in the macOS Keychain counts.
- let out = match run(bin, &["auth", "status", "--json"]).await {
+ let out = match run_in(bin, &["auth", "status", "--json"], home).await {
Ok(o) => o,
Err(e) => return Probe::error(e).with_version(version),
};
diff --git a/src/profiles/login.rs b/src/profiles/login.rs
index 9365dad8..e786a4ba 100644
--- a/src/profiles/login.rs
+++ b/src/profiles/login.rs
@@ -59,6 +59,8 @@ pub struct LoginView {
pub user_code: Option<String>,
/// Whether the user must paste a code back (Claude).
pub needs_code: bool,
+ /// The pasted code went to the CLI, which is now checking it.
+ pub code_sent: bool,
pub error: Option<String>,
pub expires_at: chrono::DateTime<chrono::Utc>,
}
@@ -71,15 +73,41 @@ struct Flow {
}
/// Login flows by id, at most one active per profile home.
-#[derive(Default, Clone)]
+#[derive(Clone)]
pub struct LoginManager {
flows: Arc<Mutex<HashMap<String, Arc<Flow>>>>,
+ /// Held while a login starts, so two starts for one home can't both spawn a CLI.
+ starting: Arc<tokio::sync::Mutex<()>>,
+ timeout: Duration,
}
-/// Called with the profile id when a login succeeds.
-pub type OnSuccess = Arc<dyn Fn(String) + Send + Sync>;
+impl Default for LoginManager {
+ fn default() -> Self {
+ Self::with_timeout(LOGIN_TIMEOUT)
+ }
+}
+
+/// Called with the finished login (its `profile_id` and `flow_id`) when it succeeds.
+pub type OnSuccess = Arc<dyn Fn(LoginView) + Send + Sync>;
+
+/// Why [`LoginManager::start_exclusive`] didn't start a login.
+#[derive(Debug)]
+pub enum StartError {
+ /// A login for this home is already running.
+ Busy(Box<LoginView>),
+ Failed(String),
+}
impl LoginManager {
+ /// A manager whose logins are killed after `timeout` instead of [`LOGIN_TIMEOUT`].
+ pub fn with_timeout(timeout: Duration) -> Self {
+ Self {
+ flows: Default::default(),
+ starting: Default::default(),
+ timeout,
+ }
+ }
+
/// Starts a login, or returns the active one for this home.
pub async fn start(
&self,
@@ -89,6 +117,29 @@ impl LoginManager {
home: &Path,
on_success: OnSuccess,
) -> Result<LoginView, String> {
+ let env = CliEnv::for_home(engine, home);
+ match self
+ .start_exclusive(engine, bin, profile_id, home, &env, on_success)
+ .await
+ {
+ Ok(view) => Ok(view),
+ Err(StartError::Busy(view)) => Ok(*view),
+ Err(StartError::Failed(e)) => Err(e),
+ }
+ }
+
+ /// Starts a login with `env` applied to the CLI. `home` is the config dir it writes to: only
+ /// one login per home runs at a time.
+ pub async fn start_exclusive(
+ &self,
+ engine: Engine,
+ bin: &str,
+ profile_id: &str,
+ home: &Path,
+ env: &CliEnv,
+ on_success: OnSuccess,
+ ) -> Result<LoginView, StartError> {
+ let _one_start = self.starting.lock().await;
{
let mut flows = self.flows.lock().unwrap();
flows.retain(|_, f| f.view.lock().unwrap().status.is_active() || !expired_long_ago(f));
@@ -96,7 +147,7 @@ impl LoginManager {
.values()
.find(|f| f.home == home && f.view.lock().unwrap().status.is_active())
{
- return Ok(f.view.lock().unwrap().clone());
+ return Err(StartError::Busy(Box::new(f.view.lock().unwrap().clone())));
}
}
let mut cmd = tokio::process::Command::new(bin);
@@ -105,20 +156,23 @@ impl LoginManager {
Engine::Codex => cmd.args(["login", "--device-auth"]),
Engine::Grok => cmd.args(["login", "--device-auth"]),
};
- CliEnv::for_home(engine, home).apply(&mut cmd);
+ env.apply(&mut cmd);
+ if home.is_dir() {
+ cmd.current_dir(home);
+ }
// CLIs print plain links without a terminal; keep them from opening a host browser
cmd.env("BROWSER", "true")
.env("NO_COLOR", "1")
.env_remove("DISPLAY")
.env_remove("WAYLAND_DISPLAY")
- .current_dir(home)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
- let mut child = cmd
- .spawn()
- .map_err(|e| format!("could not start {} login: {e}", engine.as_str()))?;
+ let mut child = cmd.spawn().map_err(|e| {
+ StartError::Failed(format!("could not start {} login: {e}", engine.as_str()))
+ })?;
+ let timeout = self.timeout;
let flow_id = format!("login_{}", uuid::Uuid::new_v4().simple());
let flow = Arc::new(Flow {
view: Mutex::new(LoginView {
@@ -128,8 +182,9 @@ impl LoginManager {
url: None,
user_code: None,
needs_code: engine == Engine::Claude,
+ code_sent: false,
error: None,
- expires_at: chrono::Utc::now() + chrono::Duration::from_std(LOGIN_TIMEOUT).unwrap(),
+ expires_at: chrono::Utc::now() + chrono::Duration::from_std(timeout).unwrap(),
}),
home: home.to_path_buf(),
stdin: tokio::sync::Mutex::new(child.stdin.take()),
@@ -147,9 +202,8 @@ impl LoginManager {
if let Some(err) = child.stderr.take() {
tokio::spawn(read_lines(BufReader::new(err), line_tx));
}
- let profile_id = profile_id.to_string();
tokio::spawn(async move {
- let deadline = tokio::time::sleep(LOGIN_TIMEOUT);
+ let deadline = tokio::time::sleep(timeout);
tokio::pin!(deadline);
let mut lines_open = true;
let end = loop {
@@ -179,13 +233,14 @@ impl LoginManager {
};
let _ = child.kill().await;
flow.stdin.lock().await.take();
- {
+ let finished = {
let mut view = flow.view.lock().unwrap();
view.status = end.0;
view.error = end.1;
- }
+ view.clone()
+ };
if end.0 == LoginStatus::Succeeded {
- on_success(profile_id);
+ on_success(finished);
}
});
// Give the CLI a moment to print its link so the first response usually has it
@@ -198,7 +253,7 @@ impl LoginManager {
tokio::time::sleep(Duration::from_millis(100)).await;
}
self.get(&flow_id)
- .ok_or_else(|| "sign-in vanished".to_string())
+ .ok_or_else(|| StartError::Failed("sign-in vanished".to_string()))
}
pub fn get(&self, flow_id: &str) -> Option<LoginView> {
@@ -234,6 +289,8 @@ impl LoginManager {
}
let mut stdin = flow.stdin.lock().await;
let pipe = stdin.as_mut().ok_or("a code was already sent")?;
+ // Marked first: a CLI that rejects the code may exit before the write returns
+ flow.view.lock().unwrap().code_sent = true;
pipe.write_all(format!("{code}\n").as_bytes())
.await
.map_err(|_| "sign-in process is gone")?;
@@ -478,7 +535,7 @@ echo "$CLAUDE_CONFIG_DIR" > "$CLAUDE_CONFIG_DIR/seen-home"
&bin,
"prf_x",
&home,
- Arc::new(move |id| *done2.lock().unwrap() = Some(id)),
+ Arc::new(move |v: LoginView| *done2.lock().unwrap() = Some(v.profile_id)),
)
.await
.unwrap();
diff --git a/src/server/engine_login.rs b/src/server/engine_login.rs
new file mode 100644
index 00000000..536e4093
--- /dev/null
+++ b/src/server/engine_login.rs
@@ -0,0 +1,264 @@
+//! "Sign in with Claude" for the Claude engine: `POST /api/engines/claude/login` runs Claude
+//! Code's own `auth login --claudeai` on the config dir the engine itself uses. The CLI prints a
+//! claude.ai link; claude.ai then shows a code the user pastes back, and the CLI keeps the login.
+//! kwnt never reads, stores or logs the token, the code or the link's state.
+//!
+//! Also `GET`/`DELETE /api/engines/claude/login/:sid`, `POST .../:sid/code` and
+//! `POST /api/engines/claude/logout`.
+
+use super::engine_routes::EnginesResponse;
+use super::AppState;
+use crate::drivers::engines::{EngineId, ProbeEnv};
+use crate::profiles::login::{LoginManager, LoginStatus, LoginView, OnSuccess, StartError};
+use crate::profiles::{create_private_dir, CliEnv, Engine};
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use std::collections::HashSet;
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+/// Owner recorded on engine sign-ins, so profile routes never see them (profile ids are `prf_…`).
+pub const OWNER: &str = "engine:claude";
+
+/// How long `auth logout` may take.
+const LOGOUT_TIMEOUT: Duration = Duration::from_secs(30);
+
+pub struct ClaudeLogin {
+ pub logins: LoginManager,
+ /// `None`: `claude` on PATH.
+ bin: Option<String>,
+ /// `None` (always, outside tests): the CLI's env as turns see it, so `CLAUDE_CONFIG_DIR` on
+ /// kwnt's process, else `~/.claude`. Set, sign-in, sign-out and the Claude check use this dir.
+ config_dir: Option<PathBuf>,
+ /// Successful sign-ins the engine registry has re-checked Claude for.
+ rechecked: Mutex<HashSet<String>>,
+}
+
+impl Default for ClaudeLogin {
+ fn default() -> Self {
+ Self::new(None, None, LoginManager::default())
+ }
+}
+
+impl ClaudeLogin {
+ pub fn new(bin: Option<String>, config_dir: Option<PathBuf>, logins: LoginManager) -> Self {
+ Self { logins, bin, config_dir, rechecked: Default::default() }
+ }
+
+ fn bin(&self) -> Option<String> {
+ self.bin.clone().or_else(|| crate::drivers::find_cli_binary("claude"))
+ }
+
+ /// The config dir the CLI will write the login to.
+ fn home(&self) -> Option<PathBuf> {
+ self.config_dir.clone().or_else(|| Engine::Claude.system_home())
+ }
+
+ fn cli_env(&self) -> CliEnv {
+ match &self.config_dir {
+ Some(dir) => CliEnv::for_home(Engine::Claude, dir),
+ None => CliEnv::default(),
+ }
+ }
+
+ /// The engine checks, pointed at the same CLI and config dir as sign-in.
+ pub fn probe_env(&self, mut env: ProbeEnv) -> ProbeEnv {
+ if let Some(bin) = &self.bin {
+ env.claude_bin = Some(bin.clone());
+ }
+ env.claude_config_dir = self.config_dir.clone();
+ env
+ }
+
+ fn view(&self, v: &LoginView) -> SessionView {
+ let rechecked = self.rechecked.lock().unwrap().contains(&v.flow_id);
+ let (state, detail) = match v.status {
+ LoginStatus::Starting => ("starting", None),
+ LoginStatus::Waiting if v.code_sent => ("verifying", None),
+ LoginStatus::Waiting => ("waiting_for_code", None),
+ // Done only once GET /api/engines shows the new status
+ LoginStatus::Succeeded if !rechecked => ("verifying", None),
+ LoginStatus::Succeeded => ("done", None),
+ // The CLI's own output is never shown: it can carry the code
+ LoginStatus::Failed if v.code_sent => {
+ ("failed", Some("Claude didn't accept that code. Start sign-in again.".to_string()))
+ }
+ LoginStatus::Failed => ("failed", v.error.clone()),
+ LoginStatus::Expired => ("expired", Some("Sign-in timed out. Start it again.".to_string())),
+ LoginStatus::Cancelled => ("cancelled", None),
+ };
+ // A finished sign-in's link is dead: don't offer it
+ let url = matches!(state, "starting" | "waiting_for_code" | "verifying").then(|| v.url.clone()).flatten();
+ SessionView {
+ session_id: v.flow_id.clone(),
+ state,
+ detail,
+ url,
+ expires_at: v.expires_at,
+ }
+ }
+
+ fn find(&self, sid: &str) -> Option<LoginView> {
+ self.logins.get(sid).filter(|v| v.profile_id == OWNER)
+ }
+}
+
+/// What the UI gets for a sign-in. `url` is the claude.ai link meant for the user.
+#[derive(Debug, Serialize)]
+pub struct SessionView {
+ pub session_id: String,
+ /// `starting`, `waiting_for_code`, `verifying`, `done`, `failed`, `expired` or `cancelled`.
+ pub state: &'static str,
+ pub detail: Option<String>,
+ pub url: Option<String>,
+ pub expires_at: chrono::DateTime<chrono::Utc>,
+}
+
+impl SessionView {
+ fn settling(&self) -> bool {
+ matches!(self.state, "starting" | "verifying")
+ }
+}
+
+fn err(status: StatusCode, msg: impl Into<String>) -> Response {
+ (status, Json(json!({ "error": msg.into() }))).into_response()
+}
+
+async fn recheck_claude(state: &AppState) {
+ let env = super::engine_routes::probe_env(state).await;
+ state.engines.recheck_one(EngineId::Claude, &env).await;
+}
+
+/// `POST /api/engines/claude/login`: starts Claude Code's sign-in. 409 while one is running.
+pub async fn start(State(state): State<AppState>) -> Response {
+ let login = &state.claude_login;
+ let Some(bin) = login.bin() else {
+ return err(StatusCode::BAD_REQUEST, "Claude Code isn't installed");
+ };
+ let Some(home) = login.home() else {
+ return err(StatusCode::INTERNAL_SERVER_ERROR, "couldn't find Claude Code's config dir");
+ };
+ if login.config_dir.is_some() {
+ if let Err(e) = create_private_dir(&home) {
+ tracing::warn!(error = %e, "could not create the Claude config dir");
+ return err(StatusCode::INTERNAL_SERVER_ERROR, "couldn't create Claude Code's config dir");
+ }
+ }
+ let done_state = state.clone();
+ let on_success: OnSuccess = Arc::new(move |view: LoginView| {
+ let state = done_state.clone();
+ tokio::spawn(async move {
+ recheck_claude(&state).await;
+ state.claude_login.rechecked.lock().unwrap().insert(view.flow_id);
+ tracing::info!("claude engine sign-in finished");
+ });
+ });
+ match login
+ .logins
+ .start_exclusive(Engine::Claude, &bin, OWNER, &home, &login.cli_env(), on_success)
+ .await
+ {
+ Ok(v) => {
+ tracing::info!("claude engine sign-in started");
+ Json(login.view(&v)).into_response()
+ }
+ Err(StartError::Busy(v)) => (
+ StatusCode::CONFLICT,
+ Json(json!({ "error": "a Claude sign-in is already running", "session_id": v.flow_id })),
+ )
+ .into_response(),
+ Err(StartError::Failed(e)) => err(StatusCode::BAD_GATEWAY, e),
+ }
+}
+
+/// `GET /api/engines/claude/login/:sid`
+pub async fn get(State(state): State<AppState>, Path(sid): Path<String>) -> Response {
+ match state.claude_login.find(&sid) {
+ Some(v) => Json(state.claude_login.view(&v)).into_response(),
+ None => err(StatusCode::NOT_FOUND, "no such sign-in"),
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct CodeBody {
+ code: String,
+}
+
+/// `POST /api/engines/claude/login/:sid/code`: the code claude.ai showed. Answers once Claude Code
+/// has accepted or refused it (or after 20s, still `verifying`).
+pub async fn submit_code(
+ State(state): State<AppState>,
+ Path(sid): Path<String>,
+ Json(body): Json<CodeBody>,
+) -> Response {
+ let login = &state.claude_login;
+ if login.find(&sid).is_none() {
+ return err(StatusCode::NOT_FOUND, "no such sign-in");
+ }
+ if let Err(e) = login.logins.submit_code(&sid, &body.code).await {
+ return err(StatusCode::BAD_REQUEST, e);
+ }
+ let mut view = login.view(&login.find(&sid).unwrap());
+ for _ in 0..200 {
+ if !view.settling() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ view = login.view(&login.find(&sid).unwrap());
+ }
+ Json(view).into_response()
+}
+
+/// `DELETE /api/engines/claude/login/:sid`: stops the sign-in and kills the CLI.
+pub async fn cancel(State(state): State<AppState>, Path(sid): Path<String>) -> Response {
+ let login = &state.claude_login;
+ if login.find(&sid).is_none() {
+ return err(StatusCode::NOT_FOUND, "no such sign-in");
+ }
+ if login.logins.cancel(&sid) {
+ // Answer once the process is gone
+ for _ in 0..50 {
+ if login.find(&sid).is_some_and(|v| !v.status.is_active()) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ }
+ StatusCode::NO_CONTENT.into_response()
+}
+
+/// `POST /api/engines/claude/logout`: Claude Code's own `auth logout` on the engine's config dir.
+/// Answers with every engine, as `GET /api/engines` does.
+pub async fn logout(State(state): State<AppState>) -> Response {
+ let login = &state.claude_login;
+ let Some(bin) = login.bin() else {
+ return err(StatusCode::BAD_REQUEST, "Claude Code isn't installed");
+ };
+ login.logins.cancel_profile(OWNER);
+ let mut cmd = tokio::process::Command::new(&bin);
+ cmd.args(["auth", "logout"]);
+ login.cli_env().apply(&mut cmd);
+ cmd.env("NO_COLOR", "1")
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .kill_on_drop(true);
+ let ok = matches!(
+ tokio::time::timeout(LOGOUT_TIMEOUT, cmd.status()).await,
+ Ok(Ok(s)) if s.success()
+ );
+ recheck_claude(&state).await;
+ if !ok {
+ return err(StatusCode::BAD_GATEWAY, "Claude Code couldn't sign out");
+ }
+ tracing::info!("claude engine signed out");
+ Json(EnginesResponse { engines: state.engines.snapshot() }).into_response()
+}
diff --git a/src/server/engine_routes.rs b/src/server/engine_routes.rs
index aad26218..e0d2e3bc 100644
--- a/src/server/engine_routes.rs
+++ b/src/server/engine_routes.rs
@@ -27,10 +27,15 @@ pub async fn recheck(State(state): State<AppState>) -> Json<EnginesResponse> {
pub async fn recheck_all(state: &AppState) -> Vec<EngineReport> {
load_disabled(state).await;
- let env = ProbeEnv::from_settings(&state.db).await;
+ let env = probe_env(state).await;
state.engines.recheck(&env).await
}
+/// What the checks run with: Settings and the env, and Claude's sign-in config dir.
+pub async fn probe_env(state: &AppState) -> ProbeEnv {
+ state.claude_login.probe_env(ProbeEnv::from_settings(&state.db).await)
+}
+
/// Reads which engines are off from Settings into the registry.
pub async fn load_disabled(state: &AppState) {
let stored = state.db.get_setting(DISABLED_SETTING).await.ok().flatten();
@@ -66,7 +71,7 @@ pub async fn set_enabled(
}
tracing::info!(engine = id.as_str(), enabled = body.enabled, "engine switched");
if body.enabled {
- let env = ProbeEnv::from_settings(&state.db).await;
+ let env = probe_env(&state).await;
state.engines.recheck_one(id, &env).await;
}
Ok(Json(EnginesResponse { engines: state.engines.snapshot() }))
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 3b60b1bc..35de7655 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -8,6 +8,7 @@ pub mod mcp_runtime;
pub mod profile_routes;
pub mod profile_turn;
pub mod engine_routes;
+pub mod engine_login;
pub mod auth;
pub mod continuity;
pub mod scheduler;
@@ -64,6 +65,8 @@ pub struct AppState {
pub scheduler_wake: Arc<tokio::sync::Notify>,
/// `ask_user` calls waiting for the user's answer.
pub questions: Arc<questions::QuestionHub>,
+ /// "Sign in with Claude" for the Claude engine.
+ pub claude_login: Arc<engine_login::ClaudeLogin>,
}
impl AppState {
@@ -100,6 +103,7 @@ impl AppState {
running_routines: Default::default(),
scheduler_wake: Default::default(),
questions: Default::default(),
+ claude_login: Default::default(),
}
}
@@ -127,6 +131,13 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/profiles/:id/logout", post(profile_routes::logout))
.route("/api/engines", get(engine_routes::list))
.route("/api/engines/recheck", post(engine_routes::recheck))
+ .route("/api/engines/claude/login", post(engine_login::start))
+ .route(
+ "/api/engines/claude/login/:sid",
+ get(engine_login::get).delete(engine_login::cancel),
+ )
+ .route("/api/engines/claude/login/:sid/code", post(engine_login::submit_code))
+ .route("/api/engines/claude/logout", post(engine_login::logout))
.route("/api/engines/:id", post(engine_routes::set_enabled).put(engine_routes::set_enabled))
.route("/api/laya/status", get(routes::laya_status))
.route("/api/kwants", get(routes::list_kwants).post(routes::create_kwant))
diff --git a/src/server/profile_routes.rs b/src/server/profile_routes.rs
index fb1ea984..6c749650 100644
--- a/src/server/profile_routes.rs
+++ b/src/server/profile_routes.rs
@@ -405,7 +405,8 @@ pub async fn start_login(State(state): State<AppState>, Path(id): Path<String>)
let db = state.db.clone();
let manager = state.profiles.clone();
let on_success: crate::profiles::login::OnSuccess =
- std::sync::Arc::new(move |profile_id: String| {
+ std::sync::Arc::new(move |view: LoginView| {
+ let profile_id = view.profile_id;
let db = db.clone();
let manager = manager.clone();
tokio::spawn(async move {
diff --git a/tests/engine_login_test.rs b/tests/engine_login_test.rs
new file mode 100644
index 00000000..adf539b0
--- /dev/null
+++ b/tests/engine_login_test.rs
@@ -0,0 +1,317 @@
+//! "Sign in with Claude" for the Claude engine (`/api/engines/claude/login…` and `/logout`),
+//! against a fake `claude` that prints a sign-in link and waits for the pasted code.
+#![cfg(unix)]
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ profiles::login::LoginManager,
+ router::LayaRouter,
+ server::{
+ auth::{ApiToken, Require},
+ create_router,
+ engine_login::ClaudeLogin,
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const TOKEN: &str = "engine-login-test-token-0123456789";
+const GOOD: &str = "GOODCODE123#STATE987";
+
+/// Prints a link, writes its pid, and signs in (writes `.credentials.json`) only for [`GOOD`].
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1 $2" in
+ "--version "*) echo "9.9.9 (Claude Code)" ;;
+ "auth status")
+ if [ -f "$CLAUDE_CONFIG_DIR/.credentials.json" ]; then echo '{"loggedIn":true,"authMethod":"claude.ai"}'
+ else echo '{"loggedIn":false,"authMethod":"none"}'; exit 1; fi ;;
+ "auth login")
+ echo $$ > "$CLAUDE_CONFIG_DIR/login.pid"
+ echo "Opening browser to sign in…"
+ echo "If the browser didn't open, visit: https://claude.com/cai/oauth/authorize?code=true&client_id=x&code_challenge=CHALLENGE987&state=STATE987"
+ printf 'Paste code here if prompted > '
+ read code
+ if [ "$code" = "GOODCODE123#STATE987" ]; then echo '{}' > "$CLAUDE_CONFIG_DIR/.credentials.json"; echo "Login successful."
+ else echo "Login failed: Request failed with status code 400 for $code"; exit 1; fi ;;
+ "auth logout") rm -f "$CLAUDE_CONFIG_DIR/.credentials.json"; echo "Successfully logged out" ;;
+esac
+"#;
+
+struct Env {
+ app: Router,
+ home: PathBuf,
+ _tmp: TempDir,
+}
+
+async fn setup_with(timeout: Duration) -> Env {
+ use std::os::unix::fs::PermissionsExt;
+ logs();
+ let tmp = tempdir().unwrap();
+ let bin = tmp.path().join("claude");
+ std::fs::write(&bin, FAKE_CLAUDE).unwrap();
+ std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let home = tmp.path().join("claude-home");
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let mut state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ state.api_token = Arc::new(ApiToken::for_tests(TOKEN, Require::Auto, config.port));
+ state.claude_login = Arc::new(ClaudeLogin::new(
+ Some(bin.to_string_lossy().into_owned()),
+ Some(home.clone()),
+ LoginManager::with_timeout(timeout),
+ ));
+ Env { app: create_router(state), home, _tmp: tmp }
+}
+
+async fn setup() -> Env {
+ setup_with(Duration::from_secs(600)).await
+}
+
+async fn req(app: &Router, method: &str, uri: &str, body: Option<Value>, headers: &[(&str, &str)]) -> (StatusCode, Value) {
+ let mut b = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ for (k, v) in headers {
+ b = b.header(*k, *v);
+ }
+ let resp = app
+ .clone()
+ .oneshot(b.body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty)).unwrap())
+ .await
+ .unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ req(app, method, uri, body, &[]).await
+}
+
+fn claude_status(engines: &Value) -> String {
+ engines["engines"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|e| e["id"] == "claude")
+ .map(|e| e["status"].as_str().unwrap_or_default().to_string())
+ .unwrap()
+}
+
+fn login_pid(home: &Path) -> String {
+ std::fs::read_to_string(home.join("login.pid")).unwrap().trim().to_string()
+}
+
+fn alive(pid: &str) -> bool {
+ std::process::Command::new("kill").args(["-0", pid]).status().unwrap().success()
+}
+
+async fn wait_state(app: &Router, sid: &str, want: &str) -> Value {
+ let mut last = Value::Null;
+ for _ in 0..60 {
+ let (s, v) = call(app, "GET", &format!("/api/engines/claude/login/{sid}"), None).await;
+ assert_eq!(s, StatusCode::OK);
+ if v["state"] == want {
+ return v;
+ }
+ last = v;
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("never reached {want}: {last}");
+}
+
+/// Every log line any test in this file writes. Installed globally before the first test runs
+/// kwnt code, so no callsite caches "nobody listens".
+fn logs() -> Arc<Mutex<Vec<u8>>> {
+ static LOGS: std::sync::OnceLock<Arc<Mutex<Vec<u8>>>> = std::sync::OnceLock::new();
+ LOGS.get_or_init(install_log_capture).clone()
+}
+
+fn install_log_capture() -> Arc<Mutex<Vec<u8>>> {
+ #[derive(Clone)]
+ struct W(Arc<Mutex<Vec<u8>>>);
+ impl std::io::Write for W {
+ fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(b);
+ Ok(b.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+ let buf = Arc::new(Mutex::new(Vec::new()));
+ let w = W(buf.clone());
+ let sub = tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::TRACE)
+ .with_ansi(false)
+ .with_writer(move || w.clone())
+ .finish();
+ tracing::subscriber::set_global_default(sub).unwrap();
+ buf
+}
+
+#[tokio::test]
+async fn sign_in_with_the_right_code_makes_claude_ready() {
+ let env = setup().await;
+ let app = &env.app;
+
+ let (s, v) = call(app, "POST", "/api/engines/claude/login", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["state"], "waiting_for_code", "{v}");
+ assert!(v["url"].as_str().unwrap().starts_with("https://claude.com/cai/oauth/authorize?"), "{v}");
+ let sid = v["session_id"].as_str().unwrap().to_string();
+ assert!(v["expires_at"].is_string());
+
+ let (s, v) = call(app, "POST", &format!("/api/engines/claude/login/{sid}/code"), Some(json!({ "code": GOOD }))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["state"], "done", "{v}");
+ assert!(env.home.join(".credentials.json").exists());
+
+ // Done means GET /api/engines already shows the new status
+ let (_, engines) = call(app, "GET", "/api/engines", None).await;
+ assert_eq!(claude_status(&engines), "ready", "{engines}");
+ let done = wait_state(app, &sid, "done").await;
+ assert_eq!((&done["detail"], &done["url"]), (&Value::Null, &Value::Null), "{done}");
+
+ // A second code for a finished sign-in is refused
+ let (s, _) = call(app, "POST", &format!("/api/engines/claude/login/{sid}/code"), Some(json!({ "code": GOOD }))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+
+ // Other tests in this file log here too (wrong codes, cancels, expiry)
+ let logs = String::from_utf8(logs().lock().unwrap().clone()).unwrap();
+ assert!(logs.contains("claude engine sign-in started"), "{logs}");
+ assert!(logs.contains("claude engine sign-in finished"), "{logs}");
+ for secret in ["GOODCODE123", "WRONGCODE999", "STATE987", "CHALLENGE987", "oauth/authorize"] {
+ assert!(!logs.contains(secret), "{secret} was logged:\n{logs}");
+ }
+}
+
+#[tokio::test]
+async fn a_wrong_code_fails_without_echoing_cli_output_and_allows_a_retry() {
+ let env = setup().await;
+ let app = &env.app;
+ let (_, v) = call(app, "POST", "/api/engines/claude/login", None).await;
+ let sid = v["session_id"].as_str().unwrap().to_string();
+
+ // Not code-shaped: rejected before it reaches the CLI, and the sign-in keeps waiting
+ let (s, v) = call(app, "POST", &format!("/api/engines/claude/login/{sid}/code"), Some(json!({ "code": "no way!" }))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");
+ wait_state(app, &sid, "waiting_for_code").await;
+
+ let (s, v) = call(app, "POST", &format!("/api/engines/claude/login/{sid}/code"), Some(json!({ "code": "WRONGCODE999#STATE987" }))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["state"], "failed", "{v}");
+ let detail = v["detail"].as_str().unwrap();
+ assert!(detail.contains("didn't accept that code"), "{v}");
+ assert!(!v.to_string().contains("WRONGCODE999") && !v.to_string().contains("400"), "{v}");
+ assert!(!env.home.join(".credentials.json").exists());
+ let (_, engines) = call(app, "GET", "/api/engines", None).await;
+ assert_ne!(claude_status(&engines), "ready");
+
+ // The failed one doesn't block a new one
+ let (s, v) = call(app, "POST", "/api/engines/claude/login", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_ne!(v["session_id"].as_str().unwrap(), sid);
+}
+
+#[tokio::test]
+async fn only_one_sign_in_runs_and_cancel_kills_it() {
+ let env = setup().await;
+ let app = &env.app;
+ let (_, v) = call(app, "POST", "/api/engines/claude/login", None).await;
+ let sid = v["session_id"].as_str().unwrap().to_string();
+ let pid = login_pid(&env.home);
+ assert!(alive(&pid));
+
+ let (s, busy) = call(app, "POST", "/api/engines/claude/login", None).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{busy}");
+ assert_eq!(busy["session_id"], sid.as_str());
+
+ let (s, _) = call(app, "DELETE", &format!("/api/engines/claude/login/{sid}"), None).await;
+ assert_eq!(s, StatusCode::NO_CONTENT);
+ assert_eq!(wait_state(app, &sid, "cancelled").await["url"], Value::Null);
+ assert!(!alive(&pid), "the CLI is still running after cancel");
+
+ // A cancelled sign-in takes no code, and a new one may start
+ let (s, _) = call(app, "POST", &format!("/api/engines/claude/login/{sid}/code"), Some(json!({ "code": GOOD }))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ let (s, _) = call(app, "POST", "/api/engines/claude/login", None).await;
+ assert_eq!(s, StatusCode::OK);
+}
+
+#[tokio::test]
+async fn an_unfinished_sign_in_expires_and_its_cli_is_killed() {
+ let env = setup_with(Duration::from_millis(800)).await;
+ let app = &env.app;
+ let (_, v) = call(app, "POST", "/api/engines/claude/login", None).await;
+ assert_eq!(v["state"], "waiting_for_code", "{v}");
+ let sid = v["session_id"].as_str().unwrap().to_string();
+ let pid = login_pid(&env.home);
+
+ let v = wait_state(app, &sid, "expired").await;
+ assert!(v["detail"].as_str().unwrap().contains("timed out"), "{v}");
+ assert!(!alive(&pid), "the CLI outlived its sign-in");
+ let (s, _) = call(app, "POST", &format!("/api/engines/claude/login/{sid}/code"), Some(json!({ "code": GOOD }))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+}
+
+#[tokio::test]
+async fn logout_signs_claude_out_and_answers_with_the_engines() {
+ let env = setup().await;
+ let app = &env.app;
+ std::fs::create_dir_all(&env.home).unwrap();
+ std::fs::write(env.home.join(".credentials.json"), "{}").unwrap();
+ let (_, engines) = call(app, "POST", "/api/engines/claude", Some(json!({ "enabled": true }))).await;
+ assert_eq!(claude_status(&engines), "ready", "{engines}");
+
+ let (s, engines) = call(app, "POST", "/api/engines/claude/logout", None).await;
+ assert_eq!(s, StatusCode::OK, "{engines}");
+ assert_eq!(claude_status(&engines), "signed_out", "{engines}");
+ assert!(!env.home.join(".credentials.json").exists());
+ let (_, engines) = call(app, "GET", "/api/engines", None).await;
+ assert_eq!(claude_status(&engines), "signed_out");
+}
+
+#[tokio::test]
+async fn unknown_sessions_404_and_remote_callers_need_the_token() {
+ let env = setup().await;
+ let app = &env.app;
+ for (m, uri, body) in [
+ ("GET", "/api/engines/claude/login/login_nope", None),
+ ("DELETE", "/api/engines/claude/login/login_nope", None),
+ ("POST", "/api/engines/claude/login/login_nope/code", Some(json!({ "code": GOOD }))),
+ ] {
+ assert_eq!(call(app, m, uri, body).await.0, StatusCode::NOT_FOUND, "{m} {uri}");
+ }
+
+ let remote = ("host", "kwnt.example.com");
+ for (m, uri) in [
+ ("POST", "/api/engines/claude/login"),
+ ("GET", "/api/engines/claude/login/x"),
+ ("POST", "/api/engines/claude/logout"),
+ ] {
+ let (s, _) = req(app, m, uri, None, &[remote]).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{m} {uri}");
+ }
+ assert!(!env.home.join("login.pid").exists(), "an unauthenticated call started the CLI");
+ let bearer = format!("Bearer {TOKEN}");
+ let (s, v) = req(app, "POST", "/api/engines/claude/login", None, &[remote, ("authorization", &bearer)]).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+}