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.

serve: no token line on a loopback bind

Lin (kwant bot)0070f9bf78b8
diff --git a/src/main.rs b/src/main.rs
index 86f8e77c..9204ae94 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -157,6 +157,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
kwnt::server::scheduler::spawn_background(state.clone(), shutdown.clone());
kwnt::server::engine_routes::spawn_startup_check(state.clone());
kwnt::server::parallel_routes::spawn_startup_sweep(state.clone());
+ let api_token = state.api_token.clone();
let app = create_router(state);
let addr = format!("{}:{}", config.host, config.port);
@@ -174,16 +175,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"⚡ kwant bots: your team of super-intelligent bots, listening at http://{}",
addr
);
- if !is_loopback_bind(&config.host) {
- println!(
- "🔒 Requests from other machines need the API token: run `kwnt token` and open http://<this-host>:{}/#kwnt_token=<token>",
- config.port
- );
- } else {
- println!(
- "🔒 Saved passwords and approvals need the API token here too: run `kwnt token` and open http://localhost:{}/#kwnt_token=<token> once",
- config.port
- );
+ // stdout only: the link carries the token
+ for line in kwnt::server::auth::startup_notice(&config.host, config.port, api_token.require, api_token.reveal()) {
+ println!("{line}");
}
let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>();
@@ -217,14 +211,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
-fn is_loopback_bind(host: &str) -> bool {
- host == "localhost"
- || host
- .trim_matches(['[', ']'])
- .parse::<std::net::IpAddr>()
- .is_ok_and(|ip| ip.is_loopback())
-}
-
/// The data dir holds the database (keys, MCP tokens) and profile logins: owner only.
fn restrict_data_dir(dir: &std::path::Path) {
#[cfg(unix)]
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 730148ca..b850732c 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -136,6 +136,43 @@ pub fn load_or_create(data_dir: &Path) -> String {
token
}
+/// Whether `kwnt serve --host <host>` listens on this machine only.
+pub fn is_loopback_bind(host: &str) -> bool {
+ host.eq_ignore_ascii_case("localhost")
+ || host
+ .trim_matches(['[', ']'])
+ .parse::<IpAddr>()
+ .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.
+pub fn sign_in_link(host: &str, port: u16, token: &str) -> String {
+ let bare = host.trim_matches(['[', ']']);
+ let host = match bare.parse::<IpAddr>() {
+ Ok(IpAddr::V6(_)) => format!("[{bare}]"),
+ _ => bare.to_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> {
+ 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)
+ )],
+ _ => vec![format!(
+ "🔒 Requests from other machines need the API token: run `kwnt token` and open http://<this-host>:{port}/#kwnt_token=<token>"
+ )],
+ }
+}
+
fn write_private(path: &Path, contents: &str) -> std::io::Result<()> {
use std::io::Write;
let mut opts = std::fs::OpenOptions::new();
@@ -536,6 +573,20 @@ mod tests {
assert!(!person_only(&post, "/api/bot-actions/b1/confirm"));
}
+ #[test]
+ fn loopback_start_prints_no_token_line_unless_always() {
+ let tok = "abcdefghijklmnopqrstuvwxyz012345";
+ 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}");
+ }
+ 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 token_file_is_private_and_stable() {
let dir = tempfile::tempdir().unwrap();