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: print one ready-to-open sign-in link on a remote bind

Lin (kwant bot)5269e2b14876
diff --git a/scripts/eval_initiative.py b/scripts/eval_initiative.py
index 4525ae16..edafe7ba 100644
--- a/scripts/eval_initiative.py
+++ b/scripts/eval_initiative.py
@@ -50,7 +50,7 @@ class Kwnt:
time.sleep(0.3)
else:
raise SystemExit("server did not start")
- self.token = subprocess.run([binary, "token"], env=env, capture_output=True, text=True).stdout.strip()
+ self.token = subprocess.run([binary, "token", "--raw"], env=env, capture_output=True, text=True).stdout.strip()
def call(self, method, path, body=None):
req = urllib.request.Request(self.base + path, method=method, data=json.dumps(body).encode() if body is not None else None)
diff --git a/src/main.rs b/src/main.rs
index 9204ae94..cbfe9f37 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -56,8 +56,12 @@ pub enum Commands {
/// List channels stored in the local database
Channels,
- /// Print the API token that browsers and scripts on other machines need
- Token,
+ /// Print the link that signs a browser on another machine in (`--raw`: just the token, for scripts)
+ Token {
+ /// Print only the token, for `Authorization: Bearer` in scripts
+ #[arg(long)]
+ raw: bool,
+ },
/// Run a tiny MCP test server on stdin/stdout (for tests and smoke checks)
#[command(hide = true)]
@@ -192,13 +196,17 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Some(Commands::Agents) => print_agents(&config).await?,
Some(Commands::Teams) => print_teams(&config).await?,
Some(Commands::Channels) => print_channels(&config).await?,
- Some(Commands::Token) => {
+ Some(Commands::Token { raw }) => {
let token = std::env::var("KWNT_API_TOKEN")
.ok()
.map(|t| t.trim().to_string())
.filter(|t| t.len() >= 16)
.unwrap_or_else(|| kwnt::server::auth::load_or_create(&config.data_dir));
- println!("{token}");
+ if raw {
+ println!("{token}");
+ } else {
+ println!("{}", kwnt::server::auth::token_command_link(&config.host, config.port, &token));
+ }
}
Some(Commands::McpEchoServer) => unreachable!("handled before config loading"),
Some(Commands::McpOauthMockServer { .. }) => unreachable!("handled before config loading"),
diff --git a/src/server/auth.rs b/src/server/auth.rs
index b850732c..63435933 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -167,12 +167,40 @@ pub fn startup_notice(host: &str, port: u16, require: Require, token: &str) -> V
"🔒 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."),
+ ]
+ }
_ => vec![format!(
- "🔒 Requests from other machines need the API token: run `kwnt token` and open http://<this-host>:{port}/#kwnt_token=<token>"
+ "🔒 To sign in from another computer, open this link once (it signs in as you, keep it private): {}",
+ sign_in_link(host, port, token)
)],
}
}
+/// Stands in for the server's address when kwnt listens on every address.
+pub const THIS_HOST: &str = "<this-host>";
+
+/// `0.0.0.0` or `::`: every address, so the bound host says nothing about how to reach it.
+fn is_any_bind(host: &str) -> bool {
+ host.is_empty()
+ || host
+ .trim_matches(['[', ']'])
+ .parse::<IpAddr>()
+ .is_ok_and(|ip| ip.is_unspecified())
+}
+
+/// The link `kwnt token` prints for the configured bind.
+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<()> {
use std::io::Write;
let mut opts = std::fs::OpenOptions::new();
@@ -322,7 +350,7 @@ pub(super) fn require_person_token(state: &AppState, headers: &HeaderMap, peer:
fn person_token_required() -> Response {
(
StatusCode::UNAUTHORIZED,
- Json(json!({ "error": "this needs the API token: sign in with `kwnt token`", "person_only": true })),
+ Json(json!({ "error": "this needs the API token: open the sign-in link kwant printed when it started, or run `kwnt token`", "person_only": true })),
)
.into_response()
}
@@ -587,6 +615,37 @@ mod tests {
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 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 token_file_is_private_and_stable() {
let dir = tempfile::tempdir().unwrap();