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: one-time sign-in links and revocable sessions

Lin (kwant bot)078766498e5f
diff --git a/Cargo.lock b/Cargo.lock
index 7c90f742..91ec19d4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1435,6 +1435,7 @@ dependencies = [
"mime_guess",
"pdf-extract",
"percent-encoding",
+ "qrcode",
"reqwest",
"ring",
"rust-embed",
@@ -1973,6 +1974,12 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "qrcode"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
+
[[package]]
name = "quote"
version = "1.0.47"
diff --git a/Cargo.toml b/Cargo.toml
index c7227a1c..05258080 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -45,6 +45,7 @@ thiserror = "1.0"
dirs = "5.0"
tokio-tungstenite = { version = "0.24", features = ["connect"] }
sha2 = "0.10"
+qrcode = { version = "0.14", default-features = false }
ring = "0.17"
base64 = "0.22"
url = "2"
diff --git a/README.md b/README.md
index 7b6630b3..f36c45d1 100644
--- a/README.md
+++ b/README.md
@@ -109,7 +109,7 @@ scp target/release/kwnt user@your-vps:/usr/local/bin/kwnt
ssh user@your-vps "kwnt serve --host 0.0.0.0 --port 8799"
```
-On your own computer there is nothing to sign in to. From another machine, open the link `kwnt serve` prints at startup once (`http://<this-host>:8799/#kwnt_token=...`, with `<this-host>` swapped for the server's address); the browser stays signed in for a year. Lost it? On the server, as the user that runs kwnt, `cat ~/.kwnt/api-token` (or `$KWNT_DATA_DIR/api-token`, e.g. `sudo cat /var/lib/kwnt/api-token` with the systemd unit below) prints the token to paste, and `kwnt token` the link (`./target/release/kwnt token` if kwnt isn't on your PATH). Run them as the same user: as another user they fail, because that user can't read the token file (for the systemd unit use `sudo cat` as above). Each install has its own token, so one copied from your laptop won't open kwnt on the server. Or skip sign-in: `ssh -N -L 8799:127.0.0.1:8799 user@your-vps`, then open http://127.0.0.1:8799 on your computer (not with Docker, where requests always count as remote). The link signs in as you, so anyone who can read the server's output can use it. Put a TLS reverse proxy in front: see [browser service and VPS hosting](docs/browser-service.md).
+On your own computer there is nothing to sign in to. From another machine, open the one-time link `kwnt serve` prints at startup (it works once, for 15 minutes; with `KWNT_ALLOWED_ORIGINS` set it is ready to open and comes with a QR code), or make a new one with `kwnt signin-link`. The browser stays signed in for a year. Prefer the token? On the server, as the user that runs kwnt, `cat ~/.kwnt/api-token` (or `$KWNT_DATA_DIR/api-token`, e.g. `sudo cat /var/lib/kwnt/api-token` with the systemd unit below) prints the token to paste, and `kwnt token` the link (`./target/release/kwnt token` if kwnt isn't on your PATH). Run them as the same user: as another user they fail, because that user can't read the token file (for the systemd unit use `sudo cat` as above). Each install has its own token, so one copied from your laptop won't open kwnt on the server. Or skip sign-in: `ssh -N -L 8799:127.0.0.1:8799 user@your-vps`, then open http://127.0.0.1:8799 on your computer (not with Docker, where requests always count as remote). A one-time link signs in as you, so keep it private until you've used it; the token never appears in the server's output. Put a TLS reverse proxy in front: see [browser service and VPS hosting](docs/browser-service.md).
<details>
<summary>A systemd unit</summary>
@@ -149,7 +149,7 @@ git clone https://github.com/alexsergivan/kwant.git && cd kwant
KWNT_CLIS=claude,codex docker compose up -d --build # any of claude,codex,grok; leave out for none
docker compose exec kwnt kwnt doctor # what works, and the fix for what doesn't
docker compose exec kwnt claude auth login # sign a CLI in (codex login --device-auth, grok login --device-auth)
-docker compose exec kwnt kwnt token --raw # the token to paste on the sign-in screen
+docker compose exec kwnt kwnt signin-link # a one-time sign-in link and QR code (15 minutes)
```
Or skip the CLIs and add an Anthropic, OpenAI or xAI API key in the app under **Space settings → Accounts**. CLI sign-ins live in the `kwnt-home` volume and data in `kwnt-data`, so both survive rebuilds.
@@ -166,7 +166,7 @@ kwant.example.com {
echo KWNT_ALLOWED_ORIGINS=https://kwant.example.com >> .env && docker compose up -d
```
-`docker compose logs kwnt | grep kwnt_token` shows the sign-in link (open it once with your domain as the host); `docker compose exec kwnt kwnt token` prints it again.
+`docker compose exec kwnt kwnt signin-link` prints a one-time sign-in link for your domain and a QR code to scan with your phone. It works once, for 15 minutes; run it again for the next device. `docker compose exec kwnt kwnt token --raw` still prints the API token, as a fallback.
- **Image sizes** (measured): kwnt alone 0.2 GB; with `KWNT_CLIS=claude,codex,grok` 1.7 GB (the CLIs add about 0.9 GB, so they are off by default). Laya 3.2 GB, the browser 1.2 GB. Idle RAM: Laya about 1.7–2.3 GB, the browser about 0.4 GB, kwnt about 25 MB.
- **kwant's own `execute_shell` tool** runs in per-team Docker containers, so it isn't available inside this stack: that would need the host's Docker socket, which is root on the host. The CLIs' own shell tools work inside the kwnt container.
diff --git a/docs/llm-profiles.md b/docs/llm-profiles.md
index 2d292bb3..239e072c 100644
--- a/docs/llm-profiles.md
+++ b/docs/llm-profiles.md
@@ -67,14 +67,19 @@ peer, a loopback `Host` and no proxy headers (`X-Forwarded-*`, `Forwarded`, `X-R
- A VPS reached directly or through a reverse proxy, and Docker (the published port arrives from
the bridge network): open the link printed at startup once.
-On a bind other than loopback, `kwnt serve` prints a ready-to-open link on stdout (never through the
-log): `http://<host>:<port>/#kwnt_token=<token>`, with the bound host, or `<this-host>` and a note to
-swap in the server's address when it listens on `0.0.0.0`/`::`. The UI posts the token to
-`/api/auth/session`, which sets an HttpOnly, SameSite=Strict cookie for a year, and clears the
-address bar. The link signs in as you: anyone who can read the server's output (`docker compose logs`
-with Docker) can use it.
-
-`kwnt token` prints the same link again (Docker: `docker compose exec kwnt kwnt token`), and
+On a bind other than loopback, `kwnt serve` prints a one-time sign-in link on stdout (never through
+the log): `<address>/#kwnt_token=kl1.<code>`. The address is the first `KWNT_ALLOWED_ORIGINS` entry
+(then a QR code follows for a phone), else the bound host, or `<this-host>` with a note to swap in the
+server's address when it listens on `0.0.0.0`/`::`. The link works once, for 15 minutes; `kwnt
+signin-link` (Docker: `docker compose exec kwnt kwnt signin-link`) asks the running server for a new
+one, and a signed-in browser can make one with `POST /api/signin/links`. The code sits in the URL
+fragment, so it never reaches access logs or a `Referer`. The UI posts it to `/api/auth/session`,
+which starts a session: a random secret in an HttpOnly, SameSite=Strict cookie for a year, stored on
+the server only as a SHA-256 hash in `<data_dir>/sessions.json` (0600). Signing out
+(`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.
+
+`kwnt token` prints a link that carries the API token itself (reusable, so keep it to yourself), and
`kwnt token --raw` 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
user that runs `kwnt serve` (`./target/release/kwnt` from a source build without kwnt on the `PATH`):
@@ -83,7 +88,7 @@ systemd unit, `sudo cat /var/lib/kwnt/api-token`). Each
install has its own token, so a token from another computer won't work either. The
sign-in screen asks where kwant runs (a server, Docker, or this computer) and shows the matching steps.
-Person-only routes (saved passwords and the vault, answering approval cards, the approvals switch,
+Person-only routes (sign-in links, saved passwords and the vault, answering approval cards, the approvals switch,
deleting a bot or team, undo, Loose ends, Parallel Universe, letters) refuse a bot's turn token, or
any bearer that isn't the API token, with 403 from anywhere. From another machine they need the API
token (401 `{person_only:true}`); from this machine they don't, so the person on it is never asked.
diff --git a/src/main.rs b/src/main.rs
index 79556bbb..207dd7bc 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -78,6 +78,19 @@ pub enum Commands {
raw: bool,
},
+ /// Print a new one-time sign-in link and QR code for another device (works once, for 15
+ /// minutes). Asks the running server, so run it where `kwnt serve` runs (Docker:
+ /// `docker compose exec kwnt kwnt signin-link`)
+ SigninLink {
+ /// kwnt's address as browsers open it (e.g. https://kwant.example.com); defaults to the
+ /// first KWNT_ALLOWED_ORIGINS entry
+ #[arg(long)]
+ url: Option<String>,
+ /// Leave out the QR code
+ #[arg(long)]
+ no_qr: bool,
+ },
+
/// Run a tiny MCP test server on stdin/stdout (for tests and smoke checks)
#[command(hide = true)]
McpEchoServer,
@@ -196,6 +209,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("{}", kwnt::server::auth::token_command_link(&config.host, config.port, &token));
}
}
+ Some(Commands::SigninLink { url, no_qr }) => {
+ if let Err(e) = kwnt::server::signin::cli_link(&config, url.as_deref(), !no_qr).await {
+ eprintln!("kwnt signin-link: {e}");
+ std::process::exit(1);
+ }
+ }
Some(Commands::McpEchoServer) => unreachable!("handled before config loading"),
Some(Commands::McpOauthMockServer { .. }) => unreachable!("handled before config loading"),
None => {
diff --git a/src/sandbox/credentials.rs b/src/sandbox/credentials.rs
index 3155670c..641ba57d 100644
--- a/src/sandbox/credentials.rs
+++ b/src/sandbox/credentials.rs
@@ -90,10 +90,16 @@ pub fn normalize_origin(input: &str) -> Result<String, StoreError> {
Ok(url.origin().ascii_serialization())
}
-/// Whether a tool call's text names kwnt's own secret files (the vault, its key, the API token).
+/// Whether a tool call's text names kwnt's own secret files (the vault, its key, the API token)
+/// or the ways to mint a sign-in (`kwnt signin-link`, `/api/signin`).
pub fn mentions_kwnt_secrets(text: &str) -> bool {
let t = text.to_ascii_lowercase();
- t.contains(VAULT_DIR) || t.contains("api-token") || t.contains(LEGACY_FILE) || t.contains("kwnt token")
+ t.contains(VAULT_DIR)
+ || t.contains("api-token")
+ || t.contains(LEGACY_FILE)
+ || t.contains("kwnt token")
+ || t.contains("signin-link")
+ || t.contains("/api/signin")
}
/// Whether a tool call's arguments name kwnt's own secret files: in any text, or through a path
diff --git a/src/serve.rs b/src/serve.rs
index 91182e8d..d19fdbeb 100644
--- a/src/serve.rs
+++ b/src/serve.rs
@@ -73,9 +73,13 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(
"⚡ kwant bots: your team of super-intelligent bots, listening at http://{}",
addr
);
- // stdout only: the link carries the token
- for line in crate::server::auth::startup_notice(&config.host, config.port, api_token.require, api_token.reveal()) {
- println!("{line}");
+ // stdout only: a one-time link, never the API token
+ if crate::server::auth::startup_link_needed(&config.host, api_token.require) {
+ let code = api_token.signin.create_link(crate::server::signin::LINK_TTL);
+ let link = crate::server::auth::one_time_link(&config.host, config.port, api_token.public_base(), &code);
+ for line in crate::server::auth::one_time_notice(&link, true) {
+ println!("{line}");
+ }
}
let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>();
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 6949456c..e159c9aa 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -1,10 +1,12 @@
//! Who may call the API. Browsers may only call it from kwnt's own page (Origin allowlist), and
-//! requests that don't come from this machine need the API token, as a bearer header or the
-//! `kwnt_token` cookie the UI gets by posting the token to `/api/auth/session`.
+//! requests that don't come from this machine need the API token as a bearer header, or a session
+//! in the `kwnt_token` cookie, which the UI gets by posting the token or a one-time sign-in link
+//! code to `/api/auth/session` (see `signin`).
//!
//! "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::AppState;
use crate::config::Config;
use axum::{
@@ -38,6 +40,8 @@ pub struct ApiToken {
/// Extra browser origins allowed besides kwnt's own (`KWNT_ALLOWED_ORIGINS`).
extra_origins: Vec<String>,
port: u16,
+ /// Sessions and one-time sign-in links.
+ pub signin: signin::SignIn,
}
impl std::fmt::Debug for ApiToken {
@@ -72,6 +76,7 @@ impl ApiToken {
require,
extra_origins,
port: config.port,
+ signin: signin::SignIn::load(&config.data_dir),
}
}
@@ -81,9 +86,16 @@ impl ApiToken {
require,
extra_origins: Vec::new(),
port,
+ signin: signin::SignIn::in_memory(),
}
}
+ /// kwnt's public address: the first `KWNT_ALLOWED_ORIGINS` entry (the HTTPS address in front
+ /// of it), for sign-in links that open as they are.
+ pub fn public_base(&self) -> Option<&str> {
+ self.extra_origins.first().map(String::as_str)
+ }
+
/// The token, for `kwnt token` and the startup URL only.
pub fn reveal(&self) -> &str {
&self.token
@@ -179,8 +191,9 @@ pub fn is_loopback_bind(host: &str) -> bool {
.is_ok_and(|ip| ip.is_loopback())
}
-/// The link that signs a browser in once: `http://<host>:<port>/#kwnt_token=<token>`. The UI
-/// posts the token to `/api/auth/session` and clears it from the address bar.
+/// The link that signs a browser in: `http://<host>:<port>/#kwnt_token=<token or code>`. The UI
+/// posts what follows `#kwnt_token=` to `/api/auth/session` and clears it from the address bar;
+/// a fragment never reaches access logs or a `Referer`.
pub fn sign_in_link(host: &str, port: u16, token: &str) -> String {
let bare = host.trim_matches(['[', ']']);
let host = match bare.parse::<IpAddr>() {
@@ -190,32 +203,44 @@ pub fn sign_in_link(host: &str, port: u16, token: &str) -> String {
format!("http://{host}:{port}/#kwnt_token={token}")
}
-/// What `kwnt serve` says about signing in, for stdout only: the link carries the token, so it
-/// must never go through tracing into log files. On a loopback bind nobody needs the token,
-/// unless `KWNT_REQUIRE_TOKEN=always`.
-pub fn startup_notice(host: &str, port: u16, require: Require, token: &str) -> Vec<String> {
+/// A one-time link: on `base` (kwnt's public address) when known, else on the bound host
+/// (`<this-host>` when kwnt listens on every address).
+pub fn one_time_link(host: &str, port: u16, base: Option<&str>, code: &str) -> String {
+ match base {
+ Some(b) => format!("{}/#kwnt_token={code}", b.trim_end_matches('/')),
+ None => token_command_link(host, port, code),
+ }
+}
+
+/// Whether `kwnt serve` should print a sign-in link: not when nobody needs one (loopback, unless
+/// `KWNT_REQUIRE_TOKEN=always`, or `never`).
+pub fn startup_link_needed(host: &str, require: Require) -> bool {
match require {
- Require::Never => Vec::new(),
- Require::Auto if is_loopback_bind(host) => Vec::new(),
- Require::Always if is_loopback_bind(host) => vec![format!(
- "🔒 Open this link once to sign in (it signs in as you, keep it private): {}",
- sign_in_link(host, port, token)
- )],
- _ if is_any_bind(host) => {
- // No "localhost needs no sign-in" here: in Docker the published port arrives from the bridge
- vec![
- format!(
- "🔒 To sign in from another computer, open this link once (it signs in as you, keep it private): {}",
- sign_in_link(THIS_HOST, port, token)
- ),
- format!(" Replace {THIS_HOST} with this server's address."),
- ]
+ Require::Never => false,
+ Require::Auto => !is_loopback_bind(host),
+ Require::Always => true,
+ }
+}
+
+/// What `kwnt serve` and `kwnt signin-link` say about a one-time link, for stdout only (never
+/// through tracing into log files): the link, a QR code for a phone when the address is real, and
+/// how to get another.
+pub fn one_time_notice(link: &str, qr: bool) -> Vec<String> {
+ let minutes = signin::LINK_TTL.as_secs() / 60;
+ let mut lines = vec![format!(
+ "🔒 To sign in from another device, open this link. It works once, for {minutes} minutes (keep it private): {link}"
+ )];
+ if link.contains(THIS_HOST) {
+ lines.push(format!(" Replace {THIS_HOST} with this server's address. Set KWNT_ALLOWED_ORIGINS to your HTTPS address for a ready link and a QR code."));
+ } else if qr {
+ let code = signin::qr_lines(link);
+ if !code.is_empty() {
+ lines.push(" Or scan it with your phone:".into());
+ lines.extend(code);
}
- _ => vec![format!(
- "🔒 To sign in from another computer, open this link once (it signs in as you, keep it private): {}",
- sign_in_link(host, port, token)
- )],
}
+ lines.push(" Used or expired? `kwnt signin-link` makes a new one (Docker: docker compose exec kwnt kwnt signin-link).".into());
+ lines
}
/// Stands in for the server's address when kwnt listens on every address.
@@ -235,7 +260,7 @@ pub fn token_command_link(host: &str, port: u16, token: &str) -> String {
sign_in_link(if is_any_bind(host) { THIS_HOST } else { host }, port, token)
}
-fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
+pub(crate) fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
use std::io::Write;
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
@@ -301,6 +326,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "documents", ..] => true,
// Setup installs software on this machine and shows what is signed in
["", "api", "setup", ..] => true,
+ // Sign-in links, device approvals and sessions: who else may sign in as the person
+ ["", "api", "signin", ..] => true,
["", "api", "approvals", _, "resolve"] => *method == Method::POST,
["", "api", "spaces" | "kwants", _, "approvals"] => *method != Method::GET && *method != Method::HEAD,
["", "api", "kwants" | "teams", _] => *method == Method::DELETE,
@@ -348,9 +375,11 @@ fn bearer(headers: &HeaderMap) -> Option<&str> {
.map(str::trim)
}
+/// The API token as a bearer, or a cookie holding a live session (or the API token itself, as
+/// browsers signed in before sessions still have).
fn presented_token_ok(api: &ApiToken, headers: &HeaderMap) -> bool {
bearer(headers).is_some_and(|t| api.matches(t))
- || cookie_token(headers).is_some_and(|t| api.matches(t))
+ || cookie_token(headers).is_some_and(|t| api.matches(t) || api.signin.session_ok(t))
}
fn needs_token(api: &ApiToken, headers: &HeaderMap, peer: Option<IpAddr>) -> bool {
@@ -501,36 +530,85 @@ fn is_https(headers: &HeaderMap) -> bool {
header_str(headers, "x-forwarded-proto").is_some_and(|p| p.eq_ignore_ascii_case("https"))
}
-/// `POST /api/auth/session {token}`: checks the token and sets the `kwnt_token` cookie
-/// (HttpOnly, SameSite=Strict), which EventSource and the browser WebSocket then send.
+fn peer_ip(peer: &Option<ConnectInfo<SocketAddr>>) -> Option<IpAddr> {
+ peer.as_ref().map(|c| c.0.ip())
+}
+
+/// A response that signs this browser in with a new session's cookie (HttpOnly, SameSite=Strict),
+/// which EventSource and the browser WebSocket then send.
+pub(super) fn with_session_cookie(mut resp: Response, secret: &str, headers: &HeaderMap) -> Response {
+ resp.headers_mut().insert(
+ header::SET_COOKIE,
+ session_cookie(secret, signin::SESSION_SECS, is_https(headers)),
+ );
+ resp.headers_mut()
+ .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
+ resp
+}
+
+/// `POST /api/auth/session {token}`: `token` is the API token or a one-time sign-in link code.
+/// Either starts a new session for this browser (the cookie never holds the API token). 401
+/// `{error, reason}`: `wrong_token`, or `link_used_or_expired` for a link that worked once.
pub async fn create_session(
State(state): State<AppState>,
+ peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Json(body): Json<SessionBody>,
) -> Response {
let token = body.token.trim();
- if !state.api_token.matches(token) {
- // A wrong guess costs a little time
- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
- return deny(StatusCode::UNAUTHORIZED, "wrong token");
+ let client = signin::client(&headers, peer_ip(&peer));
+ let secret = if state.api_token.matches(token) {
+ state.api_token.signin.create_session(Via::Token, &client)
+ } else {
+ match state.api_token.signin.redeem_link(token, &client) {
+ Redeem::Ok(secret) => secret,
+ refused => {
+ // A wrong guess costs a little time
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ let (msg, reason) = if refused == Redeem::Spent {
+ ("this sign-in link was already used or has expired", "link_used_or_expired")
+ } else {
+ ("wrong token", "wrong_token")
+ };
+ return (StatusCode::UNAUTHORIZED, Json(json!({ "error": msg, "reason": reason }))).into_response();
+ }
+ }
+ };
+ with_session_cookie(StatusCode::NO_CONTENT.into_response(), &secret, &headers)
+}
+
+/// `DELETE /api/auth/session`: ends this browser's session and clears the cookie.
+pub async fn delete_session(State(state): State<AppState>, headers: HeaderMap) -> Response {
+ if let Some(secret) = cookie_token(&headers) {
+ state.api_token.signin.revoke_secret(secret);
}
let mut resp = StatusCode::NO_CONTENT.into_response();
resp.headers_mut().insert(
header::SET_COOKIE,
- session_cookie(token, 31_536_000, is_https(&headers)),
+ session_cookie("", 0, is_https(&headers)),
);
- resp.headers_mut()
- .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
resp
}
-/// `DELETE /api/auth/session`: clears the cookie.
-pub async fn delete_session(headers: HeaderMap) -> Response {
- let mut resp = StatusCode::NO_CONTENT.into_response();
- resp.headers_mut().insert(
- header::SET_COOKIE,
- session_cookie("", 0, is_https(&headers)),
- );
+/// `POST /api/signin/links` (person only): a one-time sign-in link for another device, live for
+/// 15 minutes: `{code, url, expires_at, expires_in}`. `url` is null when kwnt doesn't know its
+/// public address (no `KWNT_ALLOWED_ORIGINS`); the page then builds it from its own address.
+pub async fn create_link(State(state): State<AppState>) -> Response {
+ let code = state.api_token.signin.create_link(signin::LINK_TTL);
+ let ttl = signin::LINK_TTL.as_secs();
+ let url = state
+ .api_token
+ .public_base()
+ .map(|b| one_time_link("", 0, Some(b), &code));
+ let mut resp = Json(json!({
+ "code": code,
+ "url": url,
+ "expires_in": ttl,
+ "expires_at": chrono::Utc::now() + chrono::TimeDelta::seconds(ttl as i64),
+ }))
+ .into_response();
+ resp.headers_mut()
+ .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
resp
}
@@ -645,48 +723,53 @@ mod tests {
}
#[test]
- fn loopback_start_prints_no_token_line_unless_always() {
- let tok = "abcdefghijklmnopqrstuvwxyz012345";
+ fn startup_link_only_where_someone_needs_it() {
for host in ["127.0.0.1", "localhost", "::1", "[::1]"] {
- assert!(startup_notice(host, 8899, Require::Auto, tok).is_empty(), "{host}");
- assert!(startup_notice(host, 8899, Require::Never, tok).is_empty(), "{host}");
+ assert!(!startup_link_needed(host, Require::Auto), "{host}");
+ assert!(!startup_link_needed(host, Require::Never), "{host}");
+ assert!(startup_link_needed(host, Require::Always), "{host}");
+ }
+ for host in ["0.0.0.0", "::", "203.0.113.9", "kwnt.example.com"] {
+ assert!(startup_link_needed(host, Require::Auto), "{host}");
+ assert!(!startup_link_needed(host, Require::Never), "{host}");
}
- let always = startup_notice("127.0.0.1", 8899, Require::Always, tok).join("\n");
- assert!(always.contains("http://127.0.0.1:8899/#kwnt_token=abcdefghijklmnopqrstuvwxyz012345"), "{always}");
- assert!(!always.contains("kwnt token`"), "{always}");
- let v6 = startup_notice("::1", 8899, Require::Always, tok).join("\n");
- assert!(v6.contains("http://[::1]:8899/#kwnt_token="), "{v6}");
}
#[test]
- fn remote_start_prints_one_ready_to_open_link() {
- let tok = "abcdefghijklmnopqrstuvwxyz012345";
- let specific = startup_notice("203.0.113.9", 8799, Require::Auto, tok);
- assert_eq!(specific.len(), 1);
- assert!(specific[0].ends_with("http://203.0.113.9:8799/#kwnt_token=abcdefghijklmnopqrstuvwxyz012345"), "{specific:?}");
- let named = startup_notice("kwnt.example.com", 8799, Require::Auto, tok).join("\n");
- assert!(named.contains("http://kwnt.example.com:8799/#kwnt_token="), "{named}");
- for any in ["0.0.0.0", "::", "[::]"] {
- let lines = startup_notice(any, 8799, Require::Auto, tok);
- assert_eq!(lines.len(), 2, "{any}");
- assert!(lines[0].ends_with("http://<this-host>:8799/#kwnt_token=abcdefghijklmnopqrstuvwxyz012345"), "{lines:?}");
- assert_eq!(lines[1].trim(), "Replace <this-host> with this server's address.");
- }
- assert_eq!(startup_notice("0.0.0.0", 8799, Require::Always, tok).len(), 2);
- assert!(startup_notice("0.0.0.0", 8799, Require::Never, tok).is_empty());
- // Nothing sends the person off to run a command any more
- assert!(!specific.iter().chain(&lines_for_all(tok)).any(|l| l.contains("kwnt token")));
- assert_eq!(token_command_link("0.0.0.0", 8799, tok), "http://<this-host>:8799/#kwnt_token=abcdefghijklmnopqrstuvwxyz012345");
- assert_eq!(token_command_link("127.0.0.1", 8899, tok), "http://127.0.0.1:8899/#kwnt_token=abcdefghijklmnopqrstuvwxyz012345");
- assert_eq!(token_command_link("::1", 8899, tok), "http://[::1]:8899/#kwnt_token=abcdefghijklmnopqrstuvwxyz012345");
+ fn one_time_links_and_notice() {
+ let code = "kl1.abc";
+ assert_eq!(one_time_link("0.0.0.0", 8799, None, code), "http://<this-host>:8799/#kwnt_token=kl1.abc");
+ assert_eq!(one_time_link("::1", 8899, None, code), "http://[::1]:8899/#kwnt_token=kl1.abc");
+ assert_eq!(
+ one_time_link("0.0.0.0", 8799, Some("https://kwant.example.com/"), code),
+ "https://kwant.example.com/#kwnt_token=kl1.abc"
+ );
+ // A placeholder host: no QR code (it couldn't open), and how to get a real one
+ let placeholder = one_time_notice(&one_time_link("0.0.0.0", 8799, None, code), true);
+ assert!(placeholder[0].ends_with("http://<this-host>:8799/#kwnt_token=kl1.abc"), "{placeholder:?}");
+ assert!(placeholder[0].contains("works once, for 15 minutes"), "{placeholder:?}");
+ assert!(placeholder.iter().any(|l| l.contains("KWNT_ALLOWED_ORIGINS")));
+ assert!(!placeholder.iter().any(|l| l.contains('█')));
+ let real = one_time_notice("https://kwant.example.com/#kwnt_token=kl1.abc", true);
+ assert!(real.iter().any(|l| l.contains('█')), "QR code");
+ assert!(real.last().unwrap().contains("kwnt signin-link"));
+ assert!(!one_time_notice("https://kwant.example.com/#kwnt_token=kl1.abc", false).iter().any(|l| l.contains('█')));
+ // The API token itself is never printed at startup any more
+ assert!(!real.iter().chain(&placeholder).any(|l| l.contains("kwnt token")));
+ assert_eq!(token_command_link("0.0.0.0", 8799, "tok"), "http://<this-host>:8799/#kwnt_token=tok");
+ assert_eq!(token_command_link("127.0.0.1", 8899, "tok"), "http://127.0.0.1:8899/#kwnt_token=tok");
}
- fn lines_for_all(tok: &str) -> Vec<String> {
- ["127.0.0.1", "0.0.0.0", "203.0.113.9"]
- .iter()
- .flat_map(|h| [Require::Auto, Require::Always].map(|r| startup_notice(h, 8799, r, tok)))
- .flatten()
- .collect()
+ #[test]
+ fn a_session_cookie_counts_as_the_token() {
+ let api = ApiToken::for_tests("abcdefghijklmnopqrstuvwxyz012345", Require::Auto, 3000);
+ let secret = api.signin.create_session(Via::Link, &signin::Client::default());
+ assert!(presented_token_ok(&api, &headers(&[("cookie", &format!("kwnt_token={secret}"))])));
+ // Only as a cookie: a bearer that isn't the API token is an agent's
+ assert!(!presented_token_ok(&api, &headers(&[("authorization", &format!("Bearer {secret}"))])));
+ let id = api.signin.session_id(&secret).unwrap();
+ api.signin.revoke(&id);
+ assert!(!presented_token_ok(&api, &headers(&[("cookie", &format!("kwnt_token={secret}"))])));
}
#[test]
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 302143d1..6a16befe 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -10,6 +10,7 @@ pub mod profile_turn;
pub mod engine_routes;
pub mod engine_login;
pub mod auth;
+pub mod signin;
pub mod continuity;
pub mod model_usage;
pub mod scheduler;
@@ -163,6 +164,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/spaces", get(spaces::list).post(spaces::create))
.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/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
new file mode 100644
index 00000000..82b52741
--- /dev/null
+++ b/src/server/signin.rs
@@ -0,0 +1,551 @@
+//! Signing a browser in without pasting the API token. A one-time link (printed at startup, by
+//! `kwnt signin-link`, or made on a signed-in device) is exchanged once for a session: a random
+//! 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.
+
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::collections::HashMap;
+use std::net::IpAddr;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+/// How long a one-time link works.
+pub const LINK_TTL: Duration = Duration::from_secs(15 * 60);
+/// How long a session lasts (the cookie's Max-Age).
+pub const SESSION_SECS: u64 = 31_536_000;
+/// Live links kept at once; making another drops the oldest.
+const MAX_LINKS: usize = 20;
+/// Used or expired links are remembered this long, to say "already used" instead of "wrong".
+const SPENT_MEMORY: Duration = Duration::from_secs(60 * 60);
+/// `last_seen` is written to disk at most this often per session.
+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 a session was made.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Via {
+ /// The API token, pasted or from `#kwnt_token=<token>`.
+ Token,
+ /// A one-time link.
+ Link,
+ /// Approved from a signed-in device.
+ Device,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Session {
+ pub id: String,
+ /// SHA-256 of the cookie secret, hex.
+ hash: String,
+ pub browser: String,
+ pub ip: String,
+ pub via: Via,
+ pub created_at: DateTime<Utc>,
+ pub expires_at: DateTime<Utc>,
+ pub last_seen: DateTime<Utc>,
+ #[serde(skip)]
+ persisted_seen: Option<DateTime<Utc>>,
+}
+
+impl Session {
+ pub fn is_hash(&self, hash: &str) -> bool {
+ self.hash == hash
+ }
+}
+
+/// Who is signing in, for the sessions list and the approval card.
+#[derive(Debug, Clone, Default)]
+pub struct Client {
+ pub browser: String,
+ pub ip: String,
+}
+
+/// What redeeming a one-time link found.
+#[derive(Debug, PartialEq, Eq)]
+pub enum Redeem {
+ /// The link was live; it is spent now. Holds the new session's cookie secret.
+ Ok(String),
+ /// The link was already used or ran out.
+ Spent,
+ /// Not a link this server made (or forgotten since).
+ Unknown,
+}
+
+enum LinkState {
+ Live(Instant),
+ Spent(Instant),
+}
+
+pub struct SignIn {
+ path: Option<PathBuf>,
+ sessions: Mutex<Vec<Session>>,
+ links: Mutex<HashMap<String, LinkState>>,
+}
+
+impl std::fmt::Debug for SignIn {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SignIn").finish_non_exhaustive()
+ }
+}
+
+pub fn hash(secret: &str) -> String {
+ hex(&Sha256::digest(secret.as_bytes()))
+}
+
+fn hex(bytes: &[u8]) -> String {
+ bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// 244 random bits (two v4 UUIDs, from the OS RNG), hex.
+pub fn random_secret() -> String {
+ format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple())
+}
+
+impl SignIn {
+ /// Sessions from `<data_dir>/sessions.json`; an unreadable file signs every browser out
+ /// (the API token still works) instead of stopping the server.
+ pub fn load(data_dir: &Path) -> Self {
+ let path = data_dir.join(SESSIONS_FILE);
+ let sessions = match std::fs::read_to_string(&path) {
+ Ok(s) => serde_json::from_str::<Vec<Session>>(&s).unwrap_or_else(|e| {
+ tracing::warn!(error = %e, "sessions.json is unreadable; every browser has to sign in again");
+ Vec::new()
+ }),
+ Err(_) => Vec::new(),
+ };
+ let now = Utc::now();
+ let sessions = sessions
+ .into_iter()
+ .filter(|s| s.expires_at > now)
+ .map(|s| Session { persisted_seen: Some(s.last_seen), ..s })
+ .collect();
+ Self {
+ path: Some(path),
+ sessions: Mutex::new(sessions),
+ links: Mutex::new(HashMap::new()),
+ }
+ }
+
+ /// Nothing on disk (tests).
+ pub fn in_memory() -> Self {
+ Self {
+ path: None,
+ sessions: Mutex::new(Vec::new()),
+ links: Mutex::new(HashMap::new()),
+ }
+ }
+
+ fn save(&self, sessions: &mut [Session]) {
+ let Some(path) = &self.path else { return };
+ let now = Utc::now();
+ for s in sessions.iter_mut() {
+ s.persisted_seen = Some(s.last_seen);
+ }
+ let live: Vec<&Session> = sessions.iter().filter(|s| s.expires_at > now).collect();
+ let Ok(json) = serde_json::to_string_pretty(&live) else { return };
+ let tmp = path.with_extension("json.tmp");
+ let res = super::auth::write_private(&tmp, &json).and_then(|_| std::fs::rename(&tmp, path));
+ if let Err(e) = res {
+ tracing::warn!(error = %e, "could not save sessions; sign-ins since the last save end on restart");
+ }
+ }
+
+ /// A new session; returns its cookie secret.
+ pub fn create_session(&self, via: Via, client: &Client) -> String {
+ let secret = format!("{SESSION_PREFIX}{}", random_secret());
+ let now = Utc::now();
+ let session = Session {
+ id: uuid::Uuid::new_v4().simple().to_string()[..12].to_string(),
+ hash: hash(&secret),
+ browser: client.browser.clone(),
+ ip: client.ip.clone(),
+ via,
+ created_at: now,
+ expires_at: now + chrono::TimeDelta::seconds(SESSION_SECS as i64),
+ last_seen: now,
+ persisted_seen: None,
+ };
+ let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
+ sessions.retain(|s| s.expires_at > now);
+ sessions.push(session);
+ self.save(&mut sessions);
+ secret
+ }
+
+ /// Whether `secret` is a live session's; notes when it was last seen.
+ pub fn session_ok(&self, secret: &str) -> bool {
+ self.session_id(secret).is_some()
+ }
+
+ /// The id of the live session `secret` belongs to.
+ pub fn session_id(&self, secret: &str) -> Option<String> {
+ if !secret.starts_with(SESSION_PREFIX) {
+ return None;
+ }
+ let h = hash(secret);
+ let now = Utc::now();
+ let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
+ let s = sessions.iter_mut().find(|s| s.hash == h && s.expires_at > now)?;
+ s.last_seen = now;
+ let id = s.id.clone();
+ if s.persisted_seen.is_none_or(|p| now - p > LAST_SEEN_PERSIST) {
+ self.save(&mut sessions);
+ }
+ Some(id)
+ }
+
+ /// Live sessions, newest first.
+ pub fn sessions(&self) -> Vec<Session> {
+ let now = Utc::now();
+ let sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
+ let mut list: Vec<Session> = sessions.iter().filter(|s| s.expires_at > now).cloned().collect();
+ list.sort_by_key(|s| std::cmp::Reverse(s.created_at));
+ list
+ }
+
+ /// Ends one session; false when there was none with that id.
+ pub fn revoke(&self, id: &str) -> bool {
+ let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
+ let before = sessions.len();
+ sessions.retain(|s| s.id != id);
+ let removed = sessions.len() != before;
+ if removed {
+ self.save(&mut sessions);
+ }
+ removed
+ }
+
+ /// Ends the session behind a cookie secret (signing out).
+ pub fn revoke_secret(&self, secret: &str) {
+ if let Some(id) = self.session_id(secret) {
+ self.revoke(&id);
+ }
+ }
+
+ /// A new one-time link code, live for `ttl`.
+ pub fn create_link(&self, ttl: Duration) -> String {
+ let code = format!("{LINK_PREFIX}{}", random_secret());
+ let now = Instant::now();
+ let mut links = self.links.lock().unwrap_or_else(|e| e.into_inner());
+ sweep(&mut links, now);
+ let mut live: Vec<(String, Instant)> = links
+ .iter()
+ .filter_map(|(h, s)| match s {
+ LinkState::Live(exp) => Some((h.clone(), *exp)),
+ LinkState::Spent(_) => None,
+ })
+ .collect();
+ if live.len() >= MAX_LINKS {
+ live.sort_by_key(|(_, exp)| *exp);
+ for (h, _) in live.iter().take(live.len() + 1 - MAX_LINKS) {
+ links.insert(h.clone(), LinkState::Spent(now + SPENT_MEMORY));
+ }
+ }
+ links.insert(hash(&code), LinkState::Live(now + ttl));
+ code
+ }
+
+ /// Spends a one-time link and makes a session for it.
+ pub fn redeem_link(&self, code: &str, client: &Client) -> Redeem {
+ if !code.starts_with(LINK_PREFIX) {
+ return Redeem::Unknown;
+ }
+ let h = hash(code);
+ let now = Instant::now();
+ {
+ let mut links = self.links.lock().unwrap_or_else(|e| e.into_inner());
+ sweep(&mut links, now);
+ match links.get(&h) {
+ None => return Redeem::Unknown,
+ Some(LinkState::Spent(_)) => return Redeem::Spent,
+ Some(LinkState::Live(_)) => {
+ links.insert(h, LinkState::Spent(now + SPENT_MEMORY));
+ }
+ }
+ }
+ Redeem::Ok(self.create_session(Via::Link, client))
+ }
+}
+
+/// 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));
+ for s in links.values_mut() {
+ if let LinkState::Live(exp) = s {
+ if *exp <= now {
+ *s = LinkState::Spent(now + SPENT_MEMORY);
+ }
+ }
+ }
+}
+
+/// "Chrome on Android" from a User-Agent, for people to recognise their own devices.
+pub fn browser_label(user_agent: &str) -> String {
+ let ua = user_agent;
+ let browser = if ua.contains("Edg/") {
+ "Edge"
+ } else if ua.contains("OPR/") {
+ "Opera"
+ } else if ua.contains("Firefox/") || ua.contains("FxiOS/") {
+ "Firefox"
+ } else if ua.contains("Chrome/") || ua.contains("CriOS/") {
+ "Chrome"
+ } else if ua.contains("Safari/") {
+ "Safari"
+ } else if ua.contains("curl/") {
+ "curl"
+ } else {
+ "Browser"
+ };
+ let os = if ua.contains("iPhone") {
+ "iPhone"
+ } else if ua.contains("iPad") {
+ "iPad"
+ } else if ua.contains("Android") {
+ "Android"
+ } else if ua.contains("Mac OS X") || ua.contains("Macintosh") {
+ "Mac"
+ } else if ua.contains("Windows") {
+ "Windows"
+ } else if ua.contains("CrOS") {
+ "ChromeOS"
+ } else if ua.contains("Linux") {
+ "Linux"
+ } else {
+ ""
+ };
+ if os.is_empty() {
+ browser.to_string()
+ } else {
+ format!("{browser} on {os}")
+ }
+}
+
+/// The client's address for display and rate limits: behind a reverse proxy, the first
+/// `X-Forwarded-For` hop (which a client without a proxy can set to anything), else the peer.
+pub fn client_ip(headers: &axum::http::HeaderMap, peer: Option<IpAddr>) -> String {
+ headers
+ .get("x-forwarded-for")
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.split(',').next())
+ .map(str::trim)
+ .filter(|v| v.parse::<IpAddr>().is_ok())
+ .map(str::to_string)
+ .or_else(|| peer.map(|p| p.to_canonical().to_string()))
+ .unwrap_or_default()
+}
+
+pub fn client(headers: &axum::http::HeaderMap, peer: Option<IpAddr>) -> Client {
+ let ua = headers
+ .get(axum::http::header::USER_AGENT)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("");
+ Client {
+ browser: browser_label(ua),
+ ip: client_ip(headers, peer),
+ }
+}
+
+/// A QR code for `text` as terminal lines (two modules per character, with a quiet zone), dark
+/// modules drawn as spaces on a light background so it scans in dark and light terminals alike.
+pub fn qr_lines(text: &str) -> Vec<String> {
+ let Ok(code) = qrcode::QrCode::with_error_correction_level(text.as_bytes(), qrcode::EcLevel::L) else {
+ return Vec::new();
+ };
+ let width = code.width();
+ let colors = code.to_colors();
+ let quiet = 2usize;
+ let size = width + 2 * quiet;
+ let dark = |x: usize, y: usize| -> bool {
+ if x < quiet || y < quiet || x >= quiet + width || y >= quiet + width {
+ return false;
+ }
+ colors[(y - quiet) * width + (x - quiet)] == qrcode::Color::Dark
+ };
+ let mut lines = Vec::new();
+ let mut y = 0;
+ while y < size {
+ let mut line = String::new();
+ for x in 0..size {
+ // Light modules are drawn (█), dark ones left blank: top and bottom half per character
+ let top = !dark(x, y);
+ let bottom = y + 1 >= size || !dark(x, y + 1);
+ line.push(match (top, bottom) {
+ (true, true) => '█',
+ (true, false) => '▀',
+ (false, true) => '▄',
+ (false, false) => ' ',
+ });
+ }
+ lines.push(line);
+ y += 2;
+ }
+ lines
+}
+
+/// `kwnt signin-link`: asks the running server (with the API token, from this machine) for a new
+/// one-time link and prints it with a QR code.
+pub async fn cli_link(config: &crate::config::Config, url: Option<&str>, qr: bool) -> Result<(), String> {
+ use super::auth;
+ let token = auth::env_token()
+ .map(Ok)
+ .unwrap_or_else(|| auth::read_existing(&config.data_dir))
+ .map_err(|e| format!("{e}. Run it as the user that runs `kwnt serve`, with the same KWNT_DATA_DIR."))?;
+ let bound = config.host.trim_matches(['[', ']']);
+ let reach = if auth::is_loopback_bind(bound) || bound.is_empty() || bound.parse::<IpAddr>().is_ok_and(|ip| ip.is_unspecified()) {
+ "127.0.0.1".to_string()
+ } else if bound.parse::<std::net::Ipv6Addr>().is_ok() {
+ format!("[{bound}]")
+ } else {
+ bound.to_string()
+ };
+ let endpoint = format!("http://{reach}:{}/api/signin/links", config.port);
+ let resp = reqwest::Client::builder()
+ .no_proxy()
+ .timeout(Duration::from_secs(10))
+ .build()
+ .map_err(|e| e.to_string())?
+ .post(&endpoint)
+ .bearer_auth(&token)
+ .send()
+ .await
+ .map_err(|e| format!("can't reach kwnt at {endpoint} ({e}). Is `kwnt serve` running?"))?;
+ if !resp.status().is_success() {
+ return Err(format!("kwnt answered {} at {endpoint}", resp.status()));
+ }
+ let body: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
+ let code = body["code"].as_str().ok_or("no code in kwnt's answer")?;
+ let base = url.map(str::to_string).or_else(|| {
+ body["url"]
+ .as_str()
+ .and_then(|u| u.split_once("/#").map(|(b, _)| b.to_string()))
+ });
+ let link = auth::one_time_link(&config.host, config.port, base.as_deref(), code);
+ for line in auth::one_time_notice(&link, qr) {
+ println!("{line}");
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn me() -> Client {
+ Client { browser: "Chrome on Android".into(), ip: "203.0.113.9".into() }
+ }
+
+ #[test]
+ fn a_link_signs_in_once() {
+ let s = SignIn::in_memory();
+ let code = s.create_link(LINK_TTL);
+ assert!(code.starts_with(LINK_PREFIX));
+ let Redeem::Ok(secret) = s.redeem_link(&code, &me()) else { panic!("first use") };
+ assert!(s.session_ok(&secret));
+ assert_eq!(s.redeem_link(&code, &me()), Redeem::Spent);
+ assert_eq!(s.sessions().len(), 1);
+ assert_eq!(s.sessions()[0].via, Via::Link);
+ }
+
+ #[test]
+ fn an_expired_link_is_refused() {
+ let s = SignIn::in_memory();
+ let code = s.create_link(Duration::from_millis(1));
+ std::thread::sleep(Duration::from_millis(5));
+ assert_eq!(s.redeem_link(&code, &me()), Redeem::Spent);
+ assert!(s.sessions().is_empty());
+ }
+
+ #[test]
+ fn unknown_and_tampered_links_are_refused() {
+ let s = SignIn::in_memory();
+ let code = s.create_link(LINK_TTL);
+ assert_eq!(s.redeem_link("kl1.nope", &me()), Redeem::Unknown);
+ assert_eq!(s.redeem_link(&format!("{code}x"), &me()), Redeem::Unknown);
+ // A session secret is not a link, and a link is not a session
+ assert!(!s.session_ok(&code));
+ assert!(matches!(s.redeem_link(&code, &me()), Redeem::Ok(_)));
+ }
+
+ #[test]
+ fn too_many_links_drop_the_oldest() {
+ let s = SignIn::in_memory();
+ let first = s.create_link(Duration::from_secs(60));
+ for _ in 0..MAX_LINKS {
+ s.create_link(LINK_TTL);
+ }
+ assert_eq!(s.redeem_link(&first, &me()), Redeem::Spent);
+ }
+
+ #[test]
+ fn sessions_persist_hashed_and_revoke() {
+ let dir = tempfile::tempdir().unwrap();
+ let s = SignIn::load(dir.path());
+ let a = s.create_session(Via::Token, &me());
+ let b = s.create_session(Via::Link, &me());
+ let file = std::fs::read_to_string(dir.path().join(SESSIONS_FILE)).unwrap();
+ assert!(!file.contains(&a) && !file.contains(&b), "secrets on disk");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = std::fs::metadata(dir.path().join(SESSIONS_FILE)).unwrap().permissions().mode();
+ assert_eq!(mode & 0o777, 0o600);
+ }
+ // Survives a restart
+ let s2 = SignIn::load(dir.path());
+ assert!(s2.session_ok(&a) && s2.session_ok(&b));
+ let id = s2.session_id(&a).unwrap();
+ assert!(s2.revoke(&id));
+ assert!(!s2.revoke(&id));
+ assert!(!s2.session_ok(&a));
+ s2.revoke_secret(&b);
+ assert!(!s2.session_ok(&b));
+ assert!(SignIn::load(dir.path()).sessions().is_empty());
+ }
+
+ #[test]
+ fn a_corrupt_sessions_file_signs_everyone_out() {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join(SESSIONS_FILE), "{not json").unwrap();
+ assert!(SignIn::load(dir.path()).sessions().is_empty());
+ }
+
+ #[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";
+ assert_eq!(browser_label(android), "Chrome on Android");
+ let iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1";
+ assert_eq!(browser_label(iphone), "Safari on iPhone");
+ let mac_ff = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14.5; rv:131.0) Gecko/20100101 Firefox/131.0";
+ assert_eq!(browser_label(mac_ff), "Firefox on Mac");
+ assert_eq!(browser_label(""), "Browser");
+ }
+
+ #[test]
+ fn client_ip_prefers_the_proxy_hop() {
+ use axum::http::{HeaderMap, HeaderValue};
+ let mut h = HeaderMap::new();
+ let peer: Option<IpAddr> = Some("172.18.0.1".parse().unwrap());
+ assert_eq!(client_ip(&h, peer), "172.18.0.1");
+ h.insert("x-forwarded-for", HeaderValue::from_static("198.51.100.4, 172.18.0.1"));
+ assert_eq!(client_ip(&h, peer), "198.51.100.4");
+ h.insert("x-forwarded-for", HeaderValue::from_static("not-an-ip"));
+ assert_eq!(client_ip(&h, peer), "172.18.0.1");
+ }
+
+ #[test]
+ fn qr_is_square_text() {
+ let lines = qr_lines("https://kwant.example.com/#kwnt_token=kl1.0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd");
+ assert!(lines.len() > 10);
+ let w = lines[0].chars().count();
+ assert!(lines.iter().all(|l| l.chars().count() == w));
+ assert_eq!(lines.len(), w.div_ceil(2));
+ }
+}
diff --git a/tests/signin_link_test.rs b/tests/signin_link_test.rs
new file mode 100644
index 00000000..169b5c4f
--- /dev/null
+++ b/tests/signin_link_test.rs
@@ -0,0 +1,191 @@
+//! One-time sign-in links (2026-10-25): a link signs one browser in once and then stops working,
+//! runs out after its time, and gives a session cookie that is never the API token and can be
+//! signed out on its own. Making a link is the person's: another machine needs a sign-in, and a
+//! bot's turn token is refused.
+
+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 std::time::Duration;
+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 redeem(app: &Router, code: &str) -> Resp {
+ call(app, "POST", "/api/auth/session", Some(json!({ "token": code })), None, None).await
+}
+
+#[tokio::test]
+async fn a_link_signs_in_one_browser_once() {
+ let (app, _state, _tmp) = setup().await;
+ assert_eq!(call(&app, "GET", "/api/kwants", None, None, None).await.status, StatusCode::UNAUTHORIZED);
+
+ // The person (with the token here; the CLI does the same) makes a link
+ let made = call(&app, "POST", "/api/signin/links", None, Some(TOKEN), None).await;
+ assert_eq!(made.status, StatusCode::OK, "{}", made.body);
+ let code = made.body["code"].as_str().unwrap().to_string();
+ assert!(code.starts_with("kl1.") && !code.contains(TOKEN));
+ assert_eq!(made.body["expires_in"], 900);
+ assert!(made.body["url"].is_null(), "no public address configured");
+
+ let first = redeem(&app, &code).await;
+ assert_eq!(first.status, StatusCode::NO_CONTENT, "{}", first.body);
+ let cookie = first.cookie.unwrap();
+ assert!(cookie.starts_with("kwnt_token=ks1."), "{cookie}");
+ assert!(!cookie.contains(TOKEN), "the cookie must not be the API token");
+ assert_eq!(call(&app, "GET", "/api/kwants", None, None, Some(&cookie)).await.status, StatusCode::OK);
+ // A session is the person: it may make a link for the next device
+ assert_eq!(call(&app, "POST", "/api/signin/links", None, None, Some(&cookie)).await.status, StatusCode::OK);
+
+ let again = redeem(&app, &code).await;
+ assert_eq!(again.status, StatusCode::UNAUTHORIZED);
+ assert_eq!(again.body["reason"], "link_used_or_expired");
+ assert!(again.cookie.is_none());
+}
+
+#[tokio::test]
+async fn an_expired_link_is_refused() {
+ let (app, state, _tmp) = setup().await;
+ let code = state.api_token.signin.create_link(Duration::from_millis(1));
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ let r = redeem(&app, &code).await;
+ assert_eq!(r.status, StatusCode::UNAUTHORIZED);
+ assert_eq!(r.body["reason"], "link_used_or_expired");
+ assert!(r.cookie.is_none());
+}
+
+#[tokio::test]
+async fn a_made_up_code_is_a_wrong_token() {
+ let (app, _state, _tmp) = setup().await;
+ let r = redeem(&app, "kl1.0000000000000000000000000000000000000000000000000000000000000000").await;
+ assert_eq!(r.status, StatusCode::UNAUTHORIZED);
+ assert_eq!(r.body["reason"], "wrong_token");
+}
+
+#[tokio::test]
+async fn the_token_still_signs_in_but_the_cookie_is_a_session() {
+ let (app, state, _tmp) = setup().await;
+ let r = redeem(&app, TOKEN).await;
+ assert_eq!(r.status, StatusCode::NO_CONTENT);
+ let cookie = r.cookie.unwrap();
+ assert!(!cookie.contains(TOKEN), "{cookie}");
+ assert_eq!(call(&app, "GET", "/api/kwants", None, None, Some(&cookie)).await.status, StatusCode::OK);
+ // Browsers signed in before sessions hold the token itself: still accepted
+ let old = format!("kwnt_token={TOKEN}");
+ assert_eq!(call(&app, "GET", "/api/kwants", None, None, Some(&old)).await.status, StatusCode::OK);
+
+ // Signing out ends that session on the server, not just in this browser
+ assert_eq!(state.api_token.signin.sessions().len(), 1);
+ let out = call(&app, "DELETE", "/api/auth/session", None, None, Some(&cookie)).await;
+ assert_eq!(out.status, StatusCode::NO_CONTENT);
+ assert!(state.api_token.signin.sessions().is_empty());
+ assert_eq!(call(&app, "GET", "/api/kwants", None, None, Some(&cookie)).await.status, StatusCode::UNAUTHORIZED);
+}
+
+#[tokio::test]
+async fn only_the_person_makes_links() {
+ let (app, state, _tmp) = setup().await;
+ let none = call(&app, "POST", "/api/signin/links", None, None, None).await;
+ assert_eq!(none.status, StatusCode::UNAUTHORIZED);
+ let forged = call(&app, "POST", "/api/signin/links", None, None, Some("kwnt_token=ks1.forged")).await;
+ assert_eq!(forged.status, StatusCode::UNAUTHORIZED);
+
+ 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();
+ // From another machine a turn token isn't the API token (401); on this machine, where no
+ // token is needed, it is still refused (403)
+ let r = call(&app, "POST", "/api/signin/links", None, Some(&turn), None).await;
+ assert_eq!(r.status, StatusCode::UNAUTHORIZED, "{}", r.body);
+ let r = call_from(&app, "127.0.0.1:50000", "127.0.0.1:8799", "POST", "/api/signin/links", None, Some(&turn), None).await;
+ assert_eq!(r.status, StatusCode::FORBIDDEN, "a bot's turn token: {}", r.body);
+}