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.

cli: kwnt token prints a one-time link, never the API token

Lin (kwant bot)7340f198693d
diff --git a/README.md b/README.md
index f36c45d1..ab689e6b 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 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).
+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 (`kwnt token --raw` does the same; `./target/release/kwnt` if kwnt isn't on your PATH), and `kwnt token` prints a new one-time link like `kwnt signin-link`. 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>
diff --git a/docs/llm-profiles.md b/docs/llm-profiles.md
index 239e072c..e6587a7d 100644
--- a/docs/llm-profiles.md
+++ b/docs/llm-profiles.md
@@ -79,8 +79,8 @@ 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.
-`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
+`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
user that runs `kwnt serve` (`./target/release/kwnt` from a source build without kwnt on the `PATH`):
as any other user it fails with an error, because it can't find or read the token file (with the
diff --git a/site-src/docs-install.html b/site-src/docs-install.html
index d88ff6d8..df65115a 100644
--- a/site-src/docs-install.html
+++ b/site-src/docs-install.html
@@ -34,11 +34,11 @@ scp target/release/kwnt user@your-vps:/usr/local/bin/kwnt
<span class="c"># 2. Run it</span>
ssh user@your-vps "kwnt serve --host 0.0.0.0 --port 8799"</code></pre>
-<p>On a bind other than loopback, <code>kwnt serve</code> prints a ready-to-open sign-in link on its output, never in the log:</p>
-<pre><code>http://&lt;this-host&gt;:8799/#kwnt_token=…</code></pre>
-<p>Swap <code>&lt;this-host&gt;</code> for the server's address and open the link once. The page signs in with an HttpOnly cookie that lasts a year and clears the address bar.</p>
+<p>On a bind other than loopback, <code>kwnt serve</code> prints a one-time sign-in link on its output, never in the log. It works once, for 15 minutes:</p>
+<pre><code>http://&lt;this-host&gt;:8799/#kwnt_token=kl1.…</code></pre>
+<p>Swap <code>&lt;this-host&gt;</code> for the server's address and open the link. The page signs in with an HttpOnly cookie that lasts a year and clears the address bar. With <code>KWNT_ALLOWED_ORIGINS</code> set to your HTTPS address, the link is ready to open and comes with a QR code to scan with your phone.</p>
<ul>
- <li><strong>Lost the link?</strong> On the server, as the user that runs kwnt, <code>kwnt token</code> prints it again, and <code>cat ~/.kwnt/api-token</code> prints the token to paste on the sign-in screen. With the systemd unit below that's <code>sudo cat /var/lib/kwnt/api-token</code>. Built from source and kwnt isn't on your <code>PATH</code>? Use <code>./target/release/kwnt token</code> from the source folder.</li>
+ <li><strong>Used, expired or lost the link?</strong> On the server, as the user that runs kwnt, <code>kwnt signin-link</code> (or <code>kwnt token</code>) prints a new one-time link, and <code>cat ~/.kwnt/api-token</code> prints the token to paste on the sign-in screen. With the systemd unit below that's <code>sudo cat /var/lib/kwnt/api-token</code>. Built from source and kwnt isn't on your <code>PATH</code>? Use <code>./target/release/kwnt token</code> from the source folder.</li>
<li><strong>Same user:</strong> run as another user, <code>kwnt token</code> fails with an error, because it can't find or read the token file. Run it as the user that runs kwnt, or with the systemd unit use <code>sudo cat /var/lib/kwnt/api-token</code>.</li>
<li><strong>Same machine:</strong> each install has its own token. A token from your laptop won't open kwnt on your server. Get it on the server.</li>
<li><strong>Scripts:</strong> <code>kwnt token --raw</code> prints just the token, to send as <code>Authorization: Bearer &lt;token&gt;</code>.</li>
@@ -74,7 +74,7 @@ docker compose exec kwnt kwnt doctor <span class="c"># what wor
docker compose exec kwnt claude auth login <span class="c"># or codex login --device-auth, grok login --device-auth</span>
docker compose exec kwnt kwnt token --raw <span class="c"># the token to paste on the sign-in screen</span></code></pre>
<p>Instead of CLIs you can add an API key in the app under <strong>Space settings → Accounts</strong>. CLI sign-ins persist in the <code>kwnt-home</code> volume and data in <code>kwnt-data</code>. The UI is published on <code>127.0.0.1:8799</code> only: put HTTPS in front (below) and set <code>KWNT_ALLOWED_ORIGINS=https://your.domain</code> in <code>.env</code>. With Caddy that's a two-line <code>Caddyfile</code>: <code>your.domain { reverse_proxy 127.0.0.1:8799 }</code>.</p>
-<p>Requests through Docker's published port count as remote, so sign in with the token (<code>docker compose logs kwnt | grep kwnt_token</code> shows the link). kwant's own <code>execute_shell</code> tool isn't available in this stack, because it would need the host's Docker socket; the CLIs' shell tools work. Upgrading from an older image, where kwnt ran as root? If it says <code>/data isn't writable</code>, run once: <code>docker compose run --rm -u root kwnt chown -R 10001:10001 /data</code>.</p>
+<p>Requests through Docker's published port count as remote, so sign in with a one-time link: <code>docker compose exec kwnt kwnt signin-link</code> prints a new one (and a QR code), or paste the token from <code>docker compose exec kwnt kwnt token --raw</code>. kwant's own <code>execute_shell</code> tool isn't available in this stack, because it would need the host's Docker socket; the CLIs' shell tools work. Upgrading from an older image, where kwnt ran as root? If it says <code>/data isn't writable</code>, run once: <code>docker compose run --rm -u root kwnt chown -R 10001:10001 /data</code>.</p>
<h2 id="deps">Without Docker: <code>kwnt setup</code>, then <code>kwnt doctor</code></h2>
<p><code>kwnt setup</code> installs what kwant needs on this machine: Chromium or Chrome for the bots' browser, Laya (in kwant's data folder, with its own <code>uv</code> if there's no Python) and a CLI (<code>claude</code> unless you name others with <code>--clis</code>). It asks before each step (<code>--yes</code> skips the questions), never runs <code>sudo</code> itself (it prints the command for you), installs into your home folder where it can, skips Docker unless you pass <code>--docker</code>, and is safe to run again. The app has the same checklist under <strong>Setup</strong>.</p>
diff --git a/site/docs/install.html b/site/docs/install.html
index ad5be3e2..da3e27ce 100644
--- a/site/docs/install.html
+++ b/site/docs/install.html
@@ -83,11 +83,11 @@ scp target/release/kwnt user@your-vps:/usr/local/bin/kwnt
<span class="c"># 2. Run it</span>
ssh user@your-vps "kwnt serve --host 0.0.0.0 --port 8799"</code></pre>
-<p>On a bind other than loopback, <code>kwnt serve</code> prints a ready-to-open sign-in link on its output, never in the log:</p>
-<pre><code>http://&lt;this-host&gt;:8799/#kwnt_token=…</code></pre>
-<p>Swap <code>&lt;this-host&gt;</code> for the server's address and open the link once. The page signs in with an HttpOnly cookie that lasts a year and clears the address bar.</p>
+<p>On a bind other than loopback, <code>kwnt serve</code> prints a one-time sign-in link on its output, never in the log. It works once, for 15 minutes:</p>
+<pre><code>http://&lt;this-host&gt;:8799/#kwnt_token=kl1.…</code></pre>
+<p>Swap <code>&lt;this-host&gt;</code> for the server's address and open the link. The page signs in with an HttpOnly cookie that lasts a year and clears the address bar. With <code>KWNT_ALLOWED_ORIGINS</code> set to your HTTPS address, the link is ready to open and comes with a QR code to scan with your phone.</p>
<ul>
- <li><strong>Lost the link?</strong> On the server, as the user that runs kwnt, <code>kwnt token</code> prints it again, and <code>cat ~/.kwnt/api-token</code> prints the token to paste on the sign-in screen. With the systemd unit below that's <code>sudo cat /var/lib/kwnt/api-token</code>. Built from source and kwnt isn't on your <code>PATH</code>? Use <code>./target/release/kwnt token</code> from the source folder.</li>
+ <li><strong>Used, expired or lost the link?</strong> On the server, as the user that runs kwnt, <code>kwnt signin-link</code> (or <code>kwnt token</code>) prints a new one-time link, and <code>cat ~/.kwnt/api-token</code> prints the token to paste on the sign-in screen. With the systemd unit below that's <code>sudo cat /var/lib/kwnt/api-token</code>. Built from source and kwnt isn't on your <code>PATH</code>? Use <code>./target/release/kwnt token</code> from the source folder.</li>
<li><strong>Same user:</strong> run as another user, <code>kwnt token</code> fails with an error, because it can't find or read the token file. Run it as the user that runs kwnt, or with the systemd unit use <code>sudo cat /var/lib/kwnt/api-token</code>.</li>
<li><strong>Same machine:</strong> each install has its own token. A token from your laptop won't open kwnt on your server. Get it on the server.</li>
<li><strong>Scripts:</strong> <code>kwnt token --raw</code> prints just the token, to send as <code>Authorization: Bearer &lt;token&gt;</code>.</li>
@@ -123,7 +123,7 @@ docker compose exec kwnt kwnt doctor <span class="c"># what wor
docker compose exec kwnt claude auth login <span class="c"># or codex login --device-auth, grok login --device-auth</span>
docker compose exec kwnt kwnt token --raw <span class="c"># the token to paste on the sign-in screen</span></code></pre>
<p>Instead of CLIs you can add an API key in the app under <strong>Space settings → Accounts</strong>. CLI sign-ins persist in the <code>kwnt-home</code> volume and data in <code>kwnt-data</code>. The UI is published on <code>127.0.0.1:8799</code> only: put HTTPS in front (below) and set <code>KWNT_ALLOWED_ORIGINS=https://your.domain</code> in <code>.env</code>. With Caddy that's a two-line <code>Caddyfile</code>: <code>your.domain { reverse_proxy 127.0.0.1:8799 }</code>.</p>
-<p>Requests through Docker's published port count as remote, so sign in with the token (<code>docker compose logs kwnt | grep kwnt_token</code> shows the link). kwant's own <code>execute_shell</code> tool isn't available in this stack, because it would need the host's Docker socket; the CLIs' shell tools work. Upgrading from an older image, where kwnt ran as root? If it says <code>/data isn't writable</code>, run once: <code>docker compose run --rm -u root kwnt chown -R 10001:10001 /data</code>.</p>
+<p>Requests through Docker's published port count as remote, so sign in with a one-time link: <code>docker compose exec kwnt kwnt signin-link</code> prints a new one (and a QR code), or paste the token from <code>docker compose exec kwnt kwnt token --raw</code>. kwant's own <code>execute_shell</code> tool isn't available in this stack, because it would need the host's Docker socket; the CLIs' shell tools work. Upgrading from an older image, where kwnt ran as root? If it says <code>/data isn't writable</code>, run once: <code>docker compose run --rm -u root kwnt chown -R 10001:10001 /data</code>.</p>
<h2 id="deps">Without Docker: <code>kwnt setup</code>, then <code>kwnt doctor</code></h2>
<p><code>kwnt setup</code> installs what kwant needs on this machine: Chromium or Chrome for the bots' browser, Laya (in kwant's data folder, with its own <code>uv</code> if there's no Python) and a CLI (<code>claude</code> unless you name others with <code>--clis</code>). It asks before each step (<code>--yes</code> skips the questions), never runs <code>sudo</code> itself (it prints the command for you), installs into your home folder where it can, skips Docker unless you pass <code>--docker</code>, and is safe to run again. The app has the same checklist under <strong>Setup</strong>.</p>
diff --git a/src/main.rs b/src/main.rs
index 207dd7bc..5ebead64 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -70,8 +70,8 @@ pub enum Commands {
/// List channels stored in the local database
Channels,
- /// Print the link that signs a browser on another machine in (`--raw`: just the token, for scripts).
- /// Only reads the existing token; never creates one
+ /// Print a new one-time sign-in link for another device, like `kwnt signin-link` (`--raw`: just
+ /// the API token, for scripts). Only reads the existing token; never creates one
Token {
/// Print only the token, for `Authorization: Bearer` in scripts
#[arg(long)]
@@ -206,7 +206,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
if raw {
println!("{token}");
} else {
- println!("{}", kwnt::server::auth::token_command_link(&config.host, config.port, &token));
+ // A one-time link, never the token itself: the token would make a link that works
+ // forever for whoever sees this output.
+ let where_token = if kwnt::server::auth::env_token().is_some() {
+ "the KWNT_API_TOKEN value".to_string()
+ } else {
+ config.data_dir.join("api-token").display().to_string()
+ };
+ if let Err(e) = kwnt::server::signin::cli_link(&config, None, true).await {
+ eprintln!("kwnt token: {e}");
+ eprintln!("The API token still works on the sign-in screen: it's {where_token} (`kwnt token --raw` prints it).");
+ std::process::exit(1);
+ }
+ println!(" Prefer typing the token? It's {where_token} (`kwnt token --raw` prints it).");
}
}
Some(Commands::SigninLink { url, no_qr }) => {
diff --git a/src/server/auth.rs b/src/server/auth.rs
index e159c9aa..56b0cb0b 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -255,7 +255,7 @@ fn is_any_bind(host: &str) -> bool {
.is_ok_and(|ip| ip.is_unspecified())
}
-/// The link `kwnt token` prints for the configured bind.
+/// A sign-in link on the configured bind (`<this-host>` when kwnt listens on every address).
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)
}
diff --git a/tests/token_cli_test.rs b/tests/token_cli_test.rs
index 27140b08..a3a5056b 100644
--- a/tests/token_cli_test.rs
+++ b/tests/token_cli_test.rs
@@ -33,8 +33,83 @@ fn token_prints_the_existing_token() {
let out = kwnt_token(dir.path(), true);
assert!(out.status.success());
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), tok);
- let link = kwnt_token(dir.path(), false);
- assert!(String::from_utf8_lossy(&link.stdout).contains(&format!("#kwnt_token={tok}")));
+}
+
+/// A stand-in `kwnt serve` that answers one `POST /api/signin/links` and hands back the request
+/// it got, so the test can check the CLI asked with the token.
+fn fake_server() -> (u16, std::thread::JoinHandle<String>) {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let handle = std::thread::spawn(move || {
+ let (mut sock, _) = listener.accept().unwrap();
+ sock.set_read_timeout(Some(std::time::Duration::from_secs(10))).unwrap();
+ let mut req = Vec::new();
+ let mut buf = [0u8; 4096];
+ while !req.windows(4).any(|w| w == b"\r\n\r\n") {
+ let n = sock.read(&mut buf).unwrap();
+ if n == 0 {
+ break;
+ }
+ req.extend_from_slice(&buf[..n]);
+ }
+ let body = r#"{"code":"kl1.onetimecode","url":null,"expires_in":900}"#;
+ let resp = format!(
+ "HTTP/1.1 201 Created\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ sock.write_all(resp.as_bytes()).unwrap();
+ String::from_utf8_lossy(&req).into_owned()
+ });
+ (port, handle)
+}
+
+fn kwnt_token_link(data_dir: &std::path::Path, port: u16) -> std::process::Output {
+ Command::new(env!("CARGO_BIN_EXE_kwnt"))
+ .arg("token")
+ .env("KWNT_DATA_DIR", data_dir)
+ .env_remove("KWNT_API_TOKEN")
+ .env("KWNT_HOST", "127.0.0.1")
+ .env("KWNT_PORT", port.to_string())
+ .env_remove("KWNT_ALLOWED_ORIGINS")
+ .output()
+ .expect("run kwnt token")
+}
+
+#[test]
+fn token_prints_a_one_time_link_never_the_token() {
+ let dir = tempfile::tempdir().unwrap();
+ let tok = "abcdefghijklmnopqrstuvwxyz012345";
+ std::fs::write(dir.path().join("api-token"), format!("{tok}\n")).unwrap();
+ let (port, server) = fake_server();
+ let out = kwnt_token_link(dir.path(), port);
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert!(out.status.success(), "{stdout}\n{stderr}");
+ assert!(stdout.contains(&format!("http://127.0.0.1:{port}/#kwnt_token=kl1.onetimecode")), "{stdout}");
+ assert!(stdout.contains("works once"), "{stdout}");
+ assert!(!stdout.contains(tok) && !stderr.contains(tok), "the API token must not be printed:\n{stdout}\n{stderr}");
+ // It points at the token for typing by hand, by where it lives, not by value
+ assert!(stdout.contains(&dir.path().join("api-token").display().to_string()), "{stdout}");
+ let req = server.join().unwrap();
+ assert!(req.starts_with("POST /api/signin/links "), "{req}");
+ assert!(req.to_ascii_lowercase().contains(&format!("authorization: bearer {tok}")), "{req}");
+}
+
+#[test]
+fn token_without_a_running_server_fails_without_printing_the_token() {
+ let dir = tempfile::tempdir().unwrap();
+ let tok = "abcdefghijklmnopqrstuvwxyz012345";
+ std::fs::write(dir.path().join("api-token"), format!("{tok}\n")).unwrap();
+ // A port nobody listens on
+ let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
+ let out = kwnt_token_link(dir.path(), port);
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert!(!out.status.success());
+ assert!(!stdout.contains(tok) && !stderr.contains(tok), "{stdout}\n{stderr}");
+ assert!(stderr.contains("Is `kwnt serve` running?"), "{stderr}");
+ assert!(stderr.contains("kwnt token --raw"), "{stderr}");
}
#[test]