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.

auth: let a new browser in from a signed-in device

Lin (kwant bot)e40d12ffc336
diff --git a/docs/llm-profiles.md b/docs/llm-profiles.md
index e6587a7d..ce51eb38 100644
--- a/docs/llm-profiles.md
+++ b/docs/llm-profiles.md
@@ -79,6 +79,17 @@ the server only as a SHA-256 hash in `<data_dir>/sessions.json` (0600). Signing
(`DELETE /api/auth/session`) ends that session on the server. The cookie never holds the API token;
browsers that signed in before sessions keep working with the token cookie they have.
+A new browser can also be let in from one that is already signed in, with nothing to copy: it
+calls `POST /api/auth/device` and gets a secret `device_code` (kept by that browser) and a short
+`user_code` such as `BCDF-2345`, which it shows. A signed-in device lists waiting requests
+(`GET /api/signin/requests`: code, browser, address, time) and approves or denies one by its code
+(`POST /api/signin/requests/approve` or `/deny` with `{user_code}`). The new browser polls
+`POST /api/auth/device/poll {device_code}` and gets its session cookie once approved. Requests last
+10 minutes and every code works once. One address may ask 5 times a minute (30 a minute from
+everyone, at most 10 waiting); more get `429`. Only approve a code you see on the device you are
+signing in: someone else can make a request show up too. `GET /api/signin/sessions` lists signed-in
+browsers and `DELETE /api/signin/sessions/<id>` signs one out.
+
`kwnt token` prints a new one-time link, like `kwnt signin-link`, and says where the token is for
typing by hand; it never prints the token. `kwnt token --raw` prints just the token, for scripts, which send `Authorization: Bearer <token>`. The token
lives in `<data_dir>/api-token` (mode 0600), or set `KWNT_API_TOKEN` (16+ characters). Run `kwnt token` as the
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 56b0cb0b..d8ca3df2 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -6,7 +6,7 @@
//! "From this machine" means a loopback peer, a loopback `Host` and no proxy forwarding headers.
//! The `Host` check is what keeps a DNS-rebinding page (same peer, foreign host) out.
-use super::signin::{self, Redeem, Via};
+use super::signin::{self, Poll, Redeem, Via};
use super::AppState;
use crate::config::Config;
use axum::{
@@ -356,7 +356,7 @@ pub fn is_local(headers: &HeaderMap, peer: Option<IpAddr>) -> bool {
&& host_ok
}
-fn cookie_token(headers: &HeaderMap) -> Option<&str> {
+pub(super) fn cookie_token(headers: &HeaderMap) -> Option<&str> {
headers
.get_all(header::COOKIE)
.iter()
@@ -508,6 +508,8 @@ pub async fn status(State(state): State<AppState>, req: Request) -> Response {
"authenticated": authenticated,
"person_auth_required": person_required,
"person_authenticated": !person_required || has_token,
+ // This server can let a new browser in from a signed-in device (`/api/auth/device`)
+ "device_login": true,
}))
.into_response()
}
@@ -612,6 +614,125 @@ pub async fn create_link(State(state): State<AppState>) -> Response {
resp
}
+/// `POST /api/auth/device {}` (open to anyone): a new browser asks to be let in.
+/// `{device_code, user_code, expires_in, interval}`; the browser keeps `device_code` to itself,
+/// shows `user_code`, and polls. 429 `{error, retry_after}` (and `Retry-After`) when this address
+/// asked too often or too many requests are waiting.
+pub async fn device_start(
+ State(state): State<AppState>,
+ peer: Option<ConnectInfo<SocketAddr>>,
+ headers: HeaderMap,
+) -> Response {
+ let client = signin::client(&headers, peer_ip(&peer));
+ match state.api_token.signin.start_device(&client) {
+ Ok((device_code, user_code)) => {
+ let mut resp = Json(json!({
+ "device_code": device_code,
+ "user_code": user_code,
+ "expires_in": signin::DEVICE_TTL.as_secs(),
+ "interval": signin::DEVICE_INTERVAL_SECS,
+ }))
+ .into_response();
+ resp.headers_mut()
+ .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
+ resp
+ }
+ Err(wait) => {
+ let mut resp = (
+ StatusCode::TOO_MANY_REQUESTS,
+ Json(json!({ "error": "too many sign-in requests; try again shortly", "retry_after": wait })),
+ )
+ .into_response();
+ if let Ok(v) = HeaderValue::from_str(&wait.to_string()) {
+ resp.headers_mut().insert(header::RETRY_AFTER, v);
+ }
+ resp
+ }
+ }
+}
+
+#[derive(Deserialize)]
+pub struct DevicePollBody {
+ device_code: String,
+}
+
+/// `POST /api/auth/device/poll {device_code}`: 200 `{status: "pending"}`; 200
+/// `{status: "approved"}` with the session cookie (once); 403 `{status: "denied"}` (once); 410
+/// `{status: "expired"}` for one that ran out, was collected, or never existed.
+pub async fn device_poll(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Json(body): Json<DevicePollBody>,
+) -> Response {
+ match state.api_token.signin.poll_device(body.device_code.trim()) {
+ Poll::Pending => Json(json!({ "status": "pending" })).into_response(),
+ Poll::Approved(secret) => with_session_cookie(Json(json!({ "status": "approved" })).into_response(), &secret, &headers),
+ Poll::Denied => (StatusCode::FORBIDDEN, Json(json!({ "status": "denied" }))).into_response(),
+ Poll::Expired => (StatusCode::GONE, Json(json!({ "status": "expired" }))).into_response(),
+ }
+}
+
+/// `GET /api/signin/requests` (person only): devices waiting to be let in, oldest first.
+pub async fn device_requests(State(state): State<AppState>) -> Response {
+ Json(state.api_token.signin.pending_devices()).into_response()
+}
+
+#[derive(Deserialize)]
+pub struct UserCodeBody {
+ user_code: String,
+}
+
+async fn decide(state: &AppState, body: UserCodeBody, approve: bool) -> Response {
+ if state.api_token.signin.decide_device(&body.user_code, approve) {
+ StatusCode::NO_CONTENT.into_response()
+ } else {
+ deny(StatusCode::NOT_FOUND, "no waiting sign-in request with that code (it may have expired)")
+ }
+}
+
+/// `POST /api/signin/requests/approve {user_code}` (person only): lets that device in. 404 when no
+/// request with that code is waiting.
+pub async fn device_approve(State(state): State<AppState>, Json(body): Json<UserCodeBody>) -> Response {
+ decide(&state, body, true).await
+}
+
+/// `POST /api/signin/requests/deny {user_code}` (person only).
+pub async fn device_deny(State(state): State<AppState>, Json(body): Json<UserCodeBody>) -> Response {
+ decide(&state, body, false).await
+}
+
+/// `GET /api/signin/sessions` (person only): signed-in browsers, newest first, `current` for this one.
+pub async fn sessions(State(state): State<AppState>, headers: HeaderMap) -> Response {
+ let current = cookie_token(&headers).and_then(|c| state.api_token.signin.session_id(c));
+ let list: Vec<_> = state
+ .api_token
+ .signin
+ .sessions()
+ .into_iter()
+ .map(|s| {
+ json!({
+ "id": s.id,
+ "browser": s.browser,
+ "ip": s.ip,
+ "via": s.via,
+ "created_at": s.created_at,
+ "last_seen": s.last_seen,
+ "current": current.as_deref() == Some(s.id.as_str()),
+ })
+ })
+ .collect();
+ Json(list).into_response()
+}
+
+/// `DELETE /api/signin/sessions/:id` (person only): signs that browser out. 404 when unknown.
+pub async fn revoke_session(State(state): State<AppState>, axum::extract::Path(id): axum::extract::Path<String>) -> Response {
+ if state.api_token.signin.revoke(&id) {
+ StatusCode::NO_CONTENT.into_response()
+ } else {
+ deny(StatusCode::NOT_FOUND, "no such session")
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 6a16befe..feb9f016 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -165,6 +165,13 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/spaces/:id", get(spaces::get).patch(spaces::update))
.route("/api/auth/session", post(auth::create_session).delete(auth::delete_session))
.route("/api/signin/links", post(auth::create_link))
+ .route("/api/auth/device", post(auth::device_start))
+ .route("/api/auth/device/poll", post(auth::device_poll))
+ .route("/api/signin/requests", get(auth::device_requests))
+ .route("/api/signin/requests/approve", post(auth::device_approve))
+ .route("/api/signin/requests/deny", post(auth::device_deny))
+ .route("/api/signin/sessions", get(auth::sessions))
+ .route("/api/signin/sessions/:id", delete(auth::revoke_session))
.route("/api/profiles", get(profile_routes::list).post(profile_routes::create))
.route("/api/profiles/:id", axum::routing::patch(profile_routes::update).delete(profile_routes::remove))
.route("/api/profiles/:id/key", put(profile_routes::set_key).delete(profile_routes::delete_key))
diff --git a/src/server/signin.rs b/src/server/signin.rs
index 82b52741..1680c9f7 100644
--- a/src/server/signin.rs
+++ b/src/server/signin.rs
@@ -3,6 +3,10 @@
//! secret in the `kwnt_token` cookie. The server keeps only its SHA-256 hash, in
//! `<data_dir>/sessions.json` (0600), so a signed-in browser never holds the API token and can be
//! listed and signed out on its own. The API token itself still works everywhere, as the fallback.
+//!
+//! A new browser can also ask to be let in (`POST /api/auth/device`): it keeps a secret
+//! `device_code` and shows a short `user_code`; the person approves that code from a device that
+//! is already signed in, and the new browser's next poll gets its session.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
@@ -26,6 +30,18 @@ const LAST_SEEN_PERSIST: chrono::TimeDelta = chrono::TimeDelta::hours(1);
pub const LINK_PREFIX: &str = "kl1.";
const SESSION_PREFIX: &str = "ks1.";
const SESSIONS_FILE: &str = "sessions.json";
+/// How long a device request waits for approval.
+pub const DEVICE_TTL: Duration = Duration::from_secs(10 * 60);
+/// How often the waiting browser should poll.
+pub const DEVICE_INTERVAL_SECS: u64 = 2;
+/// Device requests waiting at once, from everyone.
+const MAX_PENDING: usize = 10;
+/// New device requests per minute from one address, and from everyone.
+const PER_IP_PER_MIN: usize = 5;
+const ALL_PER_MIN: usize = 30;
+const DEVICE_PREFIX: &str = "kd1.";
+/// User codes: no vowels (no words), no 0/O/1/I; 28^8, about 38 bits.
+const USER_CODE_ALPHABET: &[u8] = b"BCDFGHJKLMNPQRSTVWXZ23456789";
/// How a session was made.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -83,10 +99,56 @@ enum LinkState {
Spent(Instant),
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum DeviceState {
+ Pending,
+ Approved,
+ Denied,
+}
+
+struct DeviceRequest {
+ device_hash: String,
+ /// Eight characters, no dash.
+ user_code: String,
+ client: Client,
+ created_at: DateTime<Utc>,
+ expires: Instant,
+ state: DeviceState,
+}
+
+/// A device request the person can approve.
+#[derive(Debug, Clone, Serialize)]
+pub struct PendingDevice {
+ pub user_code: String,
+ pub browser: String,
+ pub ip: String,
+ pub created_at: DateTime<Utc>,
+ pub expires_at: DateTime<Utc>,
+}
+
+/// What a waiting browser's poll finds.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Poll {
+ Pending,
+ /// Approved: the new session's cookie secret. The request is gone now.
+ Approved(String),
+ Denied,
+ /// Ran out, already collected, or never made.
+ Expired,
+}
+
+#[derive(Default)]
+struct Starts {
+ by_ip: HashMap<String, Vec<Instant>>,
+ all: Vec<Instant>,
+}
+
pub struct SignIn {
path: Option<PathBuf>,
sessions: Mutex<Vec<Session>>,
links: Mutex<HashMap<String, LinkState>>,
+ devices: Mutex<Vec<DeviceRequest>>,
+ starts: Mutex<Starts>,
}
impl std::fmt::Debug for SignIn {
@@ -130,6 +192,8 @@ impl SignIn {
path: Some(path),
sessions: Mutex::new(sessions),
links: Mutex::new(HashMap::new()),
+ devices: Mutex::new(Vec::new()),
+ starts: Mutex::new(Starts::default()),
}
}
@@ -139,6 +203,8 @@ impl SignIn {
path: None,
sessions: Mutex::new(Vec::new()),
links: Mutex::new(HashMap::new()),
+ devices: Mutex::new(Vec::new()),
+ starts: Mutex::new(Starts::default()),
}
}
@@ -274,6 +340,144 @@ impl SignIn {
}
}
+impl SignIn {
+ /// A new browser asks to be let in: `(device_code, user_code)`, or the seconds to wait when
+ /// this address (or everyone) asked too often, or too many requests are already waiting.
+ pub fn start_device(&self, client: &Client) -> Result<(String, String), u64> {
+ self.start_device_for(client, DEVICE_TTL)
+ }
+
+ /// [`Self::start_device`] with another wait (tests).
+ pub fn start_device_for(&self, client: &Client, ttl: Duration) -> Result<(String, String), u64> {
+ let now = Instant::now();
+ {
+ let mut starts = self.starts.lock().unwrap_or_else(|e| e.into_inner());
+ let minute = Duration::from_secs(60);
+ starts.all.retain(|t| now.duration_since(*t) < minute);
+ starts.by_ip.retain(|_, v| {
+ v.retain(|t| now.duration_since(*t) < minute);
+ !v.is_empty()
+ });
+ let mine = starts.by_ip.get(&client.ip).map_or(0, Vec::len);
+ if mine >= PER_IP_PER_MIN || starts.all.len() >= ALL_PER_MIN {
+ let oldest = starts.by_ip.get(&client.ip).and_then(|v| v.first()).copied().unwrap_or(now);
+ return Err(60u64.saturating_sub(now.duration_since(oldest).as_secs()).max(1));
+ }
+ starts.all.push(now);
+ starts.by_ip.entry(client.ip.clone()).or_default().push(now);
+ }
+ let mut devices = self.devices.lock().unwrap_or_else(|e| e.into_inner());
+ devices.retain(|d| d.expires > now);
+ if devices.iter().filter(|d| d.state == DeviceState::Pending).count() >= MAX_PENDING {
+ return Err(30);
+ }
+ let device_code = format!("{DEVICE_PREFIX}{}", random_secret());
+ let user_code = loop {
+ let c = random_user_code();
+ if !devices.iter().any(|d| d.user_code == c) {
+ break c;
+ }
+ };
+ devices.push(DeviceRequest {
+ device_hash: hash(&device_code),
+ user_code: user_code.clone(),
+ client: client.clone(),
+ created_at: Utc::now(),
+ expires: now + ttl,
+ state: DeviceState::Pending,
+ });
+ Ok((device_code, format_user_code(&user_code)))
+ }
+
+ /// The waiting browser's poll. An approved or denied answer is given once.
+ pub fn poll_device(&self, device_code: &str) -> Poll {
+ if !device_code.starts_with(DEVICE_PREFIX) {
+ return Poll::Expired;
+ }
+ let h = hash(device_code);
+ let now = Instant::now();
+ let mut devices = self.devices.lock().unwrap_or_else(|e| e.into_inner());
+ devices.retain(|d| d.expires > now);
+ let Some(i) = devices.iter().position(|d| d.device_hash == h) else {
+ return Poll::Expired;
+ };
+ match devices[i].state {
+ DeviceState::Pending => Poll::Pending,
+ DeviceState::Denied => {
+ devices.remove(i);
+ Poll::Denied
+ }
+ DeviceState::Approved => {
+ let d = devices.remove(i);
+ drop(devices);
+ Poll::Approved(self.create_session(Via::Device, &d.client))
+ }
+ }
+ }
+
+ /// Requests waiting for the person, oldest first.
+ pub fn pending_devices(&self) -> Vec<PendingDevice> {
+ let now = Instant::now();
+ let wall = Utc::now();
+ let mut devices = self.devices.lock().unwrap_or_else(|e| e.into_inner());
+ devices.retain(|d| d.expires > now);
+ devices
+ .iter()
+ .filter(|d| d.state == DeviceState::Pending)
+ .map(|d| PendingDevice {
+ user_code: format_user_code(&d.user_code),
+ browser: d.client.browser.clone(),
+ ip: d.client.ip.clone(),
+ created_at: d.created_at,
+ expires_at: wall + chrono::TimeDelta::from_std(d.expires - now).unwrap_or_default(),
+ })
+ .collect()
+ }
+
+ /// Approves (or denies) the waiting request with this user code; false when there is none.
+ pub fn decide_device(&self, user_code: &str, approve: bool) -> bool {
+ let code = normalize_user_code(user_code);
+ let now = Instant::now();
+ let mut devices = self.devices.lock().unwrap_or_else(|e| e.into_inner());
+ devices.retain(|d| d.expires > now);
+ match devices
+ .iter_mut()
+ .find(|d| d.state == DeviceState::Pending && !code.is_empty() && d.user_code == code)
+ {
+ Some(d) => {
+ d.state = if approve { DeviceState::Approved } else { DeviceState::Denied };
+ true
+ }
+ None => false,
+ }
+ }
+}
+
+fn random_user_code() -> String {
+ let mut n = uuid::Uuid::new_v4().as_u128();
+ let base = USER_CODE_ALPHABET.len() as u128;
+ (0..8)
+ .map(|_| {
+ let c = USER_CODE_ALPHABET[(n % base) as usize] as char;
+ n /= base;
+ c
+ })
+ .collect()
+}
+
+/// `BCDF2345` → `BCDF-2345`.
+fn format_user_code(code: &str) -> String {
+ format!("{}-{}", &code[..4], &code[4..])
+}
+
+/// What the person typed or tapped, as stored: upper case, without dashes or spaces.
+fn normalize_user_code(code: &str) -> String {
+ code.chars()
+ .filter(|c| c.is_ascii_alphanumeric())
+ .map(|c| c.to_ascii_uppercase())
+ .collect()
+}
+
/// Expired live links become spent; spent ones are forgotten after an hour.
fn sweep(links: &mut HashMap<String, LinkState>, now: Instant) {
links.retain(|_, s| !matches!(s, LinkState::Spent(forget) if *forget <= now));
@@ -517,6 +721,99 @@ mod tests {
assert!(SignIn::load(dir.path()).sessions().is_empty());
}
+ #[test]
+ fn a_device_is_let_in_once_after_approval() {
+ let s = SignIn::in_memory();
+ let (device, user) = s.start_device(&me()).unwrap();
+ assert!(device.starts_with(DEVICE_PREFIX));
+ assert_eq!(user.len(), 9);
+ assert_eq!(&user[4..5], "-");
+ assert_eq!(s.poll_device(&device), Poll::Pending);
+ let pending = s.pending_devices();
+ assert_eq!(pending.len(), 1);
+ assert_eq!(pending[0].user_code, user);
+ assert_eq!(pending[0].browser, "Chrome on Android");
+ // Typed in lower case without the dash still matches
+ assert!(s.decide_device(&user.replace('-', "").to_lowercase(), true));
+ assert!(s.pending_devices().is_empty());
+ let Poll::Approved(secret) = s.poll_device(&device) else { panic!("approved") };
+ assert!(s.session_ok(&secret));
+ assert_eq!(s.sessions()[0].via, Via::Device);
+ // Single use: the device code and the user code are spent
+ assert_eq!(s.poll_device(&device), Poll::Expired);
+ assert!(!s.decide_device(&user, true));
+ assert_eq!(s.sessions().len(), 1);
+ }
+
+ #[test]
+ fn a_denied_device_gets_nothing() {
+ let s = SignIn::in_memory();
+ let (device, user) = s.start_device(&me()).unwrap();
+ assert!(s.decide_device(&user, false));
+ assert!(!s.decide_device(&user, true), "a decision is final");
+ assert_eq!(s.poll_device(&device), Poll::Denied);
+ assert_eq!(s.poll_device(&device), Poll::Expired);
+ assert!(s.sessions().is_empty());
+ }
+
+ #[test]
+ fn an_expired_device_request_cannot_be_approved() {
+ let s = SignIn::in_memory();
+ let (device, user) = s.start_device_for(&me(), Duration::from_millis(1)).unwrap();
+ std::thread::sleep(Duration::from_millis(5));
+ assert!(s.pending_devices().is_empty());
+ assert!(!s.decide_device(&user, true));
+ assert_eq!(s.poll_device(&device), Poll::Expired);
+ assert!(s.sessions().is_empty());
+ }
+
+ #[test]
+ fn unknown_codes_match_nothing() {
+ let s = SignIn::in_memory();
+ let (device, _) = s.start_device(&me()).unwrap();
+ assert!(!s.decide_device("BCDF-2345", true));
+ assert!(!s.decide_device("", true));
+ assert!(!s.decide_device("----", true));
+ assert_eq!(s.poll_device("kd1.nope"), Poll::Expired);
+ assert_eq!(s.poll_device(&format!("{device}x")), Poll::Expired);
+ assert_eq!(s.poll_device(&device), Poll::Pending);
+ }
+
+ #[test]
+ fn device_requests_are_rate_limited_and_capped() {
+ let s = SignIn::in_memory();
+ for _ in 0..PER_IP_PER_MIN {
+ s.start_device(&me()).unwrap();
+ }
+ let wait = s.start_device(&me()).unwrap_err();
+ assert!((1..=60).contains(&wait), "{wait}");
+ // Another address still may, until MAX_PENDING are waiting
+ let mut n = PER_IP_PER_MIN;
+ let mut ip = 0;
+ while n < MAX_PENDING {
+ ip += 1;
+ let c = Client { browser: "x".into(), ip: format!("198.51.100.{ip}") };
+ if s.start_device(&c).is_ok() {
+ n += 1;
+ }
+ }
+ let other = Client { browser: "x".into(), ip: "192.0.2.1".into() };
+ assert!(s.start_device(&other).is_err(), "cap on waiting requests");
+ // Deciding one frees a slot
+ let code = s.pending_devices()[0].user_code.clone();
+ assert!(s.decide_device(&code, false));
+ assert!(s.start_device(&other).is_ok());
+ }
+
+ #[test]
+ fn user_codes_avoid_lookalikes() {
+ for _ in 0..200 {
+ let c = random_user_code();
+ assert_eq!(c.len(), 8);
+ assert!(c.bytes().all(|b| USER_CODE_ALPHABET.contains(&b)), "{c}");
+ }
+ }
+
#[test]
fn labels() {
let android = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0 Mobile Safari/537.36";
diff --git a/tests/device_signin_test.rs b/tests/device_signin_test.rs
new file mode 100644
index 00000000..c2bfd6e4
--- /dev/null
+++ b/tests/device_signin_test.rs
@@ -0,0 +1,240 @@
+//! Letting a new browser in from a signed-in device (2026-10-25): the new browser gets a secret
+//! device code and a short user code, and is let in once the person approves that code from a
+//! signed-in session. Approving needs a sign-in (never a bot's turn token), codes are single use,
+//! requests are rate limited, and signed-in browsers can be listed and signed out.
+
+use axum::{
+ body::{to_bytes, Body},
+ extract::ConnectInfo,
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{spaces::SpaceId, Database},
+ router::LayaRouter,
+ server::{
+ auth::{ApiToken, Require},
+ continuity::SelfScope,
+ create_router, mcp_runtime, AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::net::SocketAddr;
+use std::sync::Arc;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const TOKEN: &str = "test-api-token-0123456789";
+const REMOTE: &str = "203.0.113.9:40000";
+const HOST: &str = "kwnt.example.com";
+
+async fn setup() -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let mut state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ state.api_token = Arc::new(ApiToken::for_tests(TOKEN, Require::Auto, config.port));
+ (create_router(state.clone()), state, tmp)
+}
+
+struct Resp {
+ status: StatusCode,
+ body: Value,
+ cookie: Option<String>,
+}
+
+/// A request from another machine, with an optional bearer and cookie.
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>, bearer: Option<&str>, cookie: Option<&str>) -> Resp {
+ call_from(app, REMOTE, HOST, method, uri, body, bearer, cookie).await
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn call_from(
+ app: &Router,
+ peer: &str,
+ host: &str,
+ method: &str,
+ uri: &str,
+ body: Option<Value>,
+ bearer: Option<&str>,
+ cookie: Option<&str>,
+) -> Resp {
+ let mut req = Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("host", host)
+ .header("user-agent", "Mozilla/5.0 (Linux; Android 14) Chrome/129.0 Mobile Safari/537.36");
+ if let Some(t) = bearer {
+ req = req.header("authorization", format!("Bearer {t}"));
+ }
+ if let Some(c) = cookie {
+ req = req.header("cookie", c);
+ }
+ let mut req = match body {
+ Some(b) => req.header("content-type", "application/json").body(Body::from(b.to_string())).unwrap(),
+ None => req.body(Body::empty()).unwrap(),
+ };
+ req.extensions_mut().insert(ConnectInfo(peer.parse::<SocketAddr>().unwrap()));
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let cookie = resp
+ .headers()
+ .get("set-cookie")
+ .and_then(|v| v.to_str().ok())
+ .map(|c| c.split(';').next().unwrap().to_string());
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ Resp { status, body: serde_json::from_slice(&bytes).unwrap_or(Value::Null), cookie }
+}
+
+
+async fn sign_in_with_token(app: &Router) -> String {
+ let r = call(app, "POST", "/api/auth/session", Some(json!({ "token": TOKEN })), None, None).await;
+ assert_eq!(r.status, StatusCode::NO_CONTENT);
+ r.cookie.unwrap()
+}
+
+async fn ask(app: &Router) -> (String, String) {
+ let r = call(app, "POST", "/api/auth/device", Some(json!({})), None, None).await;
+ assert_eq!(r.status, StatusCode::OK, "{}", r.body);
+ assert_eq!(r.body["expires_in"], 600);
+ assert_eq!(r.body["interval"], 2);
+ (r.body["device_code"].as_str().unwrap().into(), r.body["user_code"].as_str().unwrap().into())
+}
+
+async fn poll(app: &Router, device: &str) -> Resp {
+ call(app, "POST", "/api/auth/device/poll", Some(json!({ "device_code": device })), None, None).await
+}
+
+#[tokio::test]
+async fn a_signed_in_device_lets_a_new_one_in_once() {
+ let (app, _state, _tmp) = setup().await;
+ let status = call(&app, "GET", "/api/auth/status", None, None, None).await;
+ assert_eq!(status.body["device_login"], true);
+
+ let (device, user) = ask(&app).await;
+ let p = poll(&app, &device).await;
+ assert_eq!((p.status, p.body["status"].as_str()), (StatusCode::OK, Some("pending")));
+ assert!(p.cookie.is_none());
+
+ // The person, signed in elsewhere, sees the request and approves it
+ let mine = sign_in_with_token(&app).await;
+ let list = call(&app, "GET", "/api/signin/requests", None, None, Some(&mine)).await;
+ assert_eq!(list.status, StatusCode::OK);
+ assert_eq!(list.body[0]["user_code"], user.as_str());
+ assert_eq!(list.body[0]["browser"], "Chrome on Android");
+ assert_eq!(list.body[0]["ip"], "203.0.113.9");
+ let ok = call(&app, "POST", "/api/signin/requests/approve", Some(json!({ "user_code": user })), None, Some(&mine)).await;
+ assert_eq!(ok.status, StatusCode::NO_CONTENT, "{}", ok.body);
+
+ let p = poll(&app, &device).await;
+ assert_eq!((p.status, p.body["status"].as_str()), (StatusCode::OK, Some("approved")));
+ let theirs = p.cookie.unwrap();
+ assert!(theirs.starts_with("kwnt_token=ks1.") && theirs != mine);
+ assert_eq!(call(&app, "GET", "/api/kwants", None, None, Some(&theirs)).await.status, StatusCode::OK);
+
+ // Single use: the device code is spent, and the user code can't be approved again
+ let again = poll(&app, &device).await;
+ assert_eq!((again.status, again.body["status"].as_str()), (StatusCode::GONE, Some("expired")));
+ assert!(again.cookie.is_none());
+ let twice = call(&app, "POST", "/api/signin/requests/approve", Some(json!({ "user_code": user })), None, Some(&mine)).await;
+ assert_eq!(twice.status, StatusCode::NOT_FOUND);
+}
+
+#[tokio::test]
+async fn approving_needs_a_sign_in() {
+ let (app, state, _tmp) = setup().await;
+ let (device, user) = ask(&app).await;
+ let code = json!({ "user_code": user });
+
+ // Nobody signed in, a made-up session, the new browser itself
+ let none = call(&app, "POST", "/api/signin/requests/approve", Some(code.clone()), None, None).await;
+ assert_eq!(none.status, StatusCode::UNAUTHORIZED);
+ let forged = call(&app, "POST", "/api/signin/requests/approve", Some(code.clone()), None, Some("kwnt_token=ks1.forged")).await;
+ assert_eq!(forged.status, StatusCode::UNAUTHORIZED);
+ let own = call(&app, "POST", "/api/signin/requests/approve", Some(code.clone()), Some(&device), None).await;
+ assert_eq!(own.status, StatusCode::UNAUTHORIZED);
+ assert_eq!(call(&app, "GET", "/api/signin/requests", None, None, None).await.status, StatusCode::UNAUTHORIZED);
+
+ // A bot's turn token, even on this machine where no token is needed
+ let folder = tempdir().unwrap();
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ let (_, turn) = mcp_runtime::prepare_turn_with_self(&state, &bot, None, Some(folder.path().to_path_buf()), Some(scope))
+ .await
+ .unwrap();
+ let r = call_from(&app, "127.0.0.1:50000", "127.0.0.1:8799", "POST", "/api/signin/requests/approve", Some(code.clone()), Some(&turn), None).await;
+ assert_eq!(r.status, StatusCode::FORBIDDEN, "{}", r.body);
+
+ // Still waiting: none of that let it in
+ assert_eq!(poll(&app, &device).await.body["status"], "pending");
+ assert!(state.api_token.signin.sessions().is_empty());
+}
+
+#[tokio::test]
+async fn a_denied_device_is_told_once() {
+ let (app, _state, _tmp) = setup().await;
+ let (device, user) = ask(&app).await;
+ let mine = sign_in_with_token(&app).await;
+ let r = call(&app, "POST", "/api/signin/requests/deny", Some(json!({ "user_code": user })), None, Some(&mine)).await;
+ assert_eq!(r.status, StatusCode::NO_CONTENT);
+ let p = poll(&app, &device).await;
+ assert_eq!((p.status, p.body["status"].as_str()), (StatusCode::FORBIDDEN, Some("denied")));
+ assert!(p.cookie.is_none());
+ assert_eq!(poll(&app, &device).await.status, StatusCode::GONE);
+}
+
+#[tokio::test]
+async fn an_expired_request_cannot_be_approved() {
+ let (app, state, _tmp) = setup().await;
+ let client = kwnt::server::signin::Client { browser: "x".into(), ip: "198.51.100.7".into() };
+ let (device, user) = state.api_token.signin.start_device_for(&client, std::time::Duration::from_millis(1)).unwrap();
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ let mine = sign_in_with_token(&app).await;
+ let r = call(&app, "POST", "/api/signin/requests/approve", Some(json!({ "user_code": user })), None, Some(&mine)).await;
+ assert_eq!(r.status, StatusCode::NOT_FOUND);
+ assert_eq!(poll(&app, &device).await.status, StatusCode::GONE);
+ assert_eq!(poll(&app, "kd1.made-up").await.status, StatusCode::GONE);
+}
+
+#[tokio::test]
+async fn one_address_is_rate_limited() {
+ let (app, _state, _tmp) = setup().await;
+ for _ in 0..5 {
+ ask(&app).await;
+ }
+ let r = call(&app, "POST", "/api/auth/device", Some(json!({})), None, None).await;
+ assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS);
+ assert!(r.body["retry_after"].as_u64().is_some_and(|s| (1..=60).contains(&s)), "{}", r.body);
+}
+
+#[tokio::test]
+async fn sessions_are_listed_and_signed_out() {
+ let (app, _state, _tmp) = setup().await;
+ let a = sign_in_with_token(&app).await;
+ let b = sign_in_with_token(&app).await;
+ let list = call(&app, "GET", "/api/signin/sessions", None, None, Some(&a)).await;
+ assert_eq!(list.status, StatusCode::OK);
+ let rows = list.body.as_array().unwrap();
+ assert_eq!(rows.len(), 2);
+ assert_eq!(rows.iter().filter(|r| r["current"] == true).count(), 1);
+ assert!(rows.iter().all(|r| r["via"] == "token" && r["browser"] == "Chrome on Android"));
+ assert!(!list.body.to_string().contains("ks1."), "no secrets in the list");
+
+ let other = rows.iter().find(|r| r["current"] == false).unwrap()["id"].as_str().unwrap().to_string();
+ assert_eq!(call(&app, "DELETE", &format!("/api/signin/sessions/{other}"), None, None, Some(&a)).await.status, StatusCode::NO_CONTENT);
+ assert_eq!(call(&app, "GET", "/api/kwants", None, None, Some(&b)).await.status, StatusCode::UNAUTHORIZED);
+ assert_eq!(call(&app, "GET", "/api/kwants", None, None, Some(&a)).await.status, StatusCode::OK);
+ assert_eq!(call(&app, "DELETE", &format!("/api/signin/sessions/{other}"), None, None, Some(&a)).await.status, StatusCode::NOT_FOUND);
+ // Signed out browsers can't list or revoke
+ assert_eq!(call(&app, "GET", "/api/signin/sessions", None, None, Some(&b)).await.status, StatusCode::UNAUTHORIZED);
+}