diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f5bd02ce..2b2a4854 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -50,6 +50,11 @@ jobs:
- name: Run Workspace Unit and Integration Tests
run: cargo test --workspace --verbose -- --test-threads=1
+ - name: Run Required Agent Preflight
+ env:
+ AIEN_PROOF_OFF: '1'
+ run: bash scripts/agent-preflight.sh
+
- name: Enforce Zero Disk Secrets Invariant
run: |
echo "Auditing repository for prohibited plaintext secret files..."
diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs
index 675c9b71..fb2c0dbd 100644
--- a/crates/aien-cli/src/commands.rs
+++ b/crates/aien-cli/src/commands.rs
@@ -1489,7 +1489,6 @@ pub async fn handle_cockpit_command() {
"==================================================================".cyan()
);
println!(" Local: http://127.0.0.1:18095");
- println!(" Tailscale: http://100.116.106.93:18095");
println!(" Mascot: AIEN Cosmic Monkey Warrior");
println!(" Audio: Natural Voice Response Enabled");
println!(
diff --git a/crates/spark-cockpit-rs/src/access.rs b/crates/spark-cockpit-rs/src/access.rs
new file mode 100644
index 00000000..6c04ebbb
--- /dev/null
+++ b/crates/spark-cockpit-rs/src/access.rs
@@ -0,0 +1,481 @@
+//! Operator access boundary. Browser sessions never put credentials in URLs.
+use axum::{
+ extract::{Form, Request, State},
+ http::{HeaderMap, StatusCode, header},
+ middleware::Next,
+ response::{Html, IntoResponse, Response},
+};
+use serde::Deserialize;
+use std::{
+ collections::HashMap,
+ net::SocketAddr,
+ sync::{Arc, Mutex},
+ time::{Duration, Instant},
+};
+
+const COOKIE: &str = "aien_cockpit_session";
+const LOGIN: &str = r#"
AIEN sign inSign in to AIEN
"#;
+
+pub struct Access {
+ token: String,
+ origins: Vec,
+ sessions: Mutex>,
+}
+
+impl Access {
+ pub fn new(token: String, origins: Vec) -> Result {
+ if token.len() < 32
+ || token.len() > 256
+ || !token
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b"-_+=/.".contains(&b))
+ {
+ return Err("Cockpit token must contain 32 to 256 cookie-safe ASCII characters".into());
+ }
+ if origins.is_empty()
+ || origins.iter().any(|o| {
+ o.parse::().map_or(true, |uri| {
+ uri.authority().is_none() || uri.path() != "/" || uri.query().is_some()
+ }) || !(o.starts_with("http://") || o.starts_with("https://"))
+ || o.ends_with('/')
+ })
+ {
+ return Err(
+ "Cockpit origins must be explicit HTTP(S) origins without a trailing slash".into(),
+ );
+ }
+ Ok(Self {
+ token,
+ origins,
+ sessions: Mutex::new(HashMap::new()),
+ })
+ }
+
+ pub fn from_environment() -> Result {
+ let from_env = std::env::var("AIEN_COCKPIT_TOKEN")
+ .ok()
+ .filter(|t| !t.trim().is_empty());
+ let token = from_env
+ .or_else(|| {
+ let result = std::process::Command::new("atlas-vault")
+ .args(["get", "AIEN_COCKPIT_TOKEN"])
+ .output()
+ .ok()?;
+ result
+ .status
+ .success()
+ .then(|| String::from_utf8(result.stdout).ok())
+ .flatten()
+ })
+ .ok_or("AIEN_COCKPIT_TOKEN is unavailable from memory or atlas-vault")?;
+ let origins = std::env::var("AIEN_COCKPIT_ORIGINS")
+ .unwrap_or_else(|_| "http://127.0.0.1:18095,http://localhost:18095".into());
+ Self::new(
+ token.trim().to_owned(),
+ origins.split(',').map(|o| o.trim().to_owned()).collect(),
+ )
+ }
+
+ fn matches(&self, supplied: &str) -> bool {
+ if supplied.len() != self.token.len() {
+ return false;
+ }
+ self.token
+ .bytes()
+ .zip(supplied.bytes())
+ .fold(0u8, |diff, (a, b)| diff | (a ^ b))
+ == 0
+ }
+
+ fn create_session(&self) -> Option {
+ let mut sessions = self.sessions.lock().ok()?;
+ sessions.retain(|_, expires| *expires > Instant::now());
+ if sessions.len() >= 1024 {
+ return None;
+ }
+ let id = format!(
+ "{}{}",
+ uuid::Uuid::new_v4().simple(),
+ uuid::Uuid::new_v4().simple()
+ );
+ sessions.insert(id.clone(), Instant::now() + Duration::from_secs(3600));
+ Some(id)
+ }
+
+ fn session_valid(&self, id: &str) -> bool {
+ self.sessions.lock().ok().is_some_and(|sessions| {
+ sessions
+ .get(id)
+ .is_some_and(|expires| *expires > Instant::now())
+ })
+ }
+
+ fn origin_allowed(&self, headers: &HeaderMap) -> bool {
+ headers
+ .get(header::ORIGIN)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|origin| self.origins.iter().any(|o| o == origin))
+ }
+}
+
+/// Read-only health routes that local monitors (aien-cli, spark-debugger,
+/// spark-supervisor, bench_inference_stack) poll without credentials. GET/HEAD
+/// only, and only when the Host header names the loopback listener, so a
+/// DNS-rebinding page cannot read them through a foreign hostname.
+const PUBLIC_READ_ROUTES: &[&str] = &["/api/pulse", "/api/status"];
+
+fn loopback_host(headers: &HeaderMap) -> bool {
+ headers
+ .get(header::HOST)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|host| host.parse::().ok())
+ .is_some_and(|authority| matches!(authority.host(), "127.0.0.1" | "localhost" | "[::1]"))
+}
+
+pub fn bind_address() -> Result {
+ std::env::var("AIEN_COCKPIT_ADDR")
+ .unwrap_or_else(|_| "127.0.0.1:18095".into())
+ .parse()
+ .map_err(|_| "AIEN_COCKPIT_ADDR must be a socket address".into())
+}
+
+pub async fn login() -> Response {
+ let mut response = Html(LOGIN).into_response();
+ response
+ .headers_mut()
+ .insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
+ response.headers_mut().insert(
+ header::CONTENT_SECURITY_POLICY,
+ "default-src 'none'; form-action 'self'; frame-ancestors 'none'"
+ .parse()
+ .unwrap(),
+ );
+ response
+}
+
+#[derive(Deserialize)]
+pub struct LoginForm {
+ token: String,
+}
+
+pub async fn session(
+ State(access): State>,
+ headers: HeaderMap,
+ Form(form): Form,
+) -> Response {
+ if !access.origin_allowed(&headers) {
+ return StatusCode::FORBIDDEN.into_response();
+ }
+ if !access.matches(&form.token) {
+ return StatusCode::UNAUTHORIZED.into_response();
+ }
+ let secure = headers
+ .get(header::ORIGIN)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|v| v.starts_with("https://"));
+ let Some(id) = access.create_session() else {
+ return StatusCode::SERVICE_UNAVAILABLE.into_response();
+ };
+ let cookie = format!(
+ "{COOKIE}={}; Path=/; HttpOnly; SameSite=Strict; Max-Age=3600{}",
+ id,
+ if secure { "; Secure" } else { "" }
+ );
+ let mut response = StatusCode::SEE_OTHER.into_response();
+ response
+ .headers_mut()
+ .insert(header::LOCATION, "/".parse().unwrap());
+ response
+ .headers_mut()
+ .insert(header::SET_COOKIE, cookie.parse().unwrap());
+ response
+ .headers_mut()
+ .insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
+ response
+}
+
+pub async fn require_access(
+ State(access): State>,
+ request: Request,
+ next: Next,
+) -> Response {
+ let headers = request.headers();
+ let origin_present = headers.contains_key(header::ORIGIN);
+ let websocket = headers
+ .get(header::UPGRADE)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|v| v.eq_ignore_ascii_case("websocket"));
+ if (origin_present && !access.origin_allowed(headers))
+ || (websocket && !access.origin_allowed(headers))
+ {
+ return StatusCode::FORBIDDEN.into_response();
+ }
+ let read_only =
+ request.method() == axum::http::Method::GET || request.method() == axum::http::Method::HEAD;
+ if read_only
+ && !websocket
+ && PUBLIC_READ_ROUTES.contains(&request.uri().path())
+ && loopback_host(headers)
+ {
+ return next.run(request).await;
+ }
+ let bearer = headers
+ .get(header::AUTHORIZATION)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .is_some_and(|t| access.matches(t));
+ let cookie = headers
+ .get(header::COOKIE)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|cookies| {
+ cookies.split(';').any(|v| {
+ v.trim()
+ .strip_prefix(&format!("{COOKIE}="))
+ .is_some_and(|t| access.session_valid(t))
+ })
+ });
+ // Cookie credentials require an allowed browser Origin for every mutation.
+ let safe =
+ request.method() == axum::http::Method::GET || request.method() == axum::http::Method::HEAD;
+ if !bearer && (!cookie || (!safe && !access.origin_allowed(headers))) {
+ if safe
+ && headers
+ .get(header::ACCEPT)
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|v| v.contains("text/html"))
+ {
+ return axum::response::Redirect::to("/login").into_response();
+ }
+ return StatusCode::UNAUTHORIZED.into_response();
+ }
+ let mut response = next.run(request).await;
+ response
+ .headers_mut()
+ .insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
+ response
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::{
+ Router, middleware,
+ routing::{get, post},
+ };
+
+ #[tokio::test]
+ async fn boundary_rejects_missing_tokens_and_cross_origin_sessions() {
+ let access =
+ Arc::new(Access::new("a".repeat(64), vec!["http://localhost:18095".into()]).unwrap());
+ let app = Router::new()
+ .route(
+ "/private",
+ get(|| async { "private" }).post(|| async { "changed" }),
+ )
+ .route("/ws/terminal", get(|| async { "terminal" }))
+ .layer(middleware::from_fn_with_state(
+ Arc::clone(&access),
+ require_access,
+ ))
+ .merge(
+ Router::new()
+ .route("/auth/session", post(session))
+ .with_state(Arc::clone(&access)),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ let client = reqwest::Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .build()
+ .unwrap();
+ for path in ["/private", "/ws/terminal"] {
+ assert_eq!(
+ client
+ .get(format!("{url}{path}"))
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 401
+ );
+ }
+ assert_eq!(
+ client
+ .get(format!("{url}/private"))
+ .bearer_auth("wrong")
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 401
+ );
+ assert_eq!(
+ client
+ .get(format!("{url}/private"))
+ .bearer_auth("a".repeat(64))
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 200
+ );
+ let form = format!("token={}", "a".repeat(64));
+ assert_eq!(
+ client
+ .post(format!("{url}/auth/session"))
+ .header("Origin", "http://evil.example")
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .body(form.clone())
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 403
+ );
+ let login = client
+ .post(format!("{url}/auth/session"))
+ .header("Origin", "http://localhost:18095")
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .body(form)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(login.status(), 303);
+ let cookie = login
+ .headers()
+ .get("set-cookie")
+ .unwrap()
+ .to_str()
+ .unwrap()
+ .split(';')
+ .next()
+ .unwrap()
+ .to_owned();
+ assert!(!cookie.contains(&"a".repeat(64)));
+ assert_eq!(
+ client
+ .get(format!("{url}/private"))
+ .header("Cookie", &cookie)
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 200
+ );
+ assert_eq!(
+ client
+ .post(format!("{url}/private"))
+ .header("Cookie", &cookie)
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 401
+ );
+ assert_eq!(
+ client
+ .post(format!("{url}/private"))
+ .header("Cookie", &cookie)
+ .header("Origin", "http://evil.example")
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 403
+ );
+ assert_eq!(
+ client
+ .post(format!("{url}/private"))
+ .header("Cookie", &cookie)
+ .header("Origin", "http://localhost:18095")
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 200
+ );
+ for expires in access.sessions.lock().unwrap().values_mut() {
+ *expires = Instant::now() - Duration::from_secs(1);
+ }
+ assert_eq!(
+ client
+ .get(format!("{url}/private"))
+ .header("Cookie", &cookie)
+ .send()
+ .await
+ .unwrap()
+ .status(),
+ 401
+ );
+ server.abort();
+ }
+
+ #[test]
+ fn refuses_empty_credentials_and_invalid_origins() {
+ assert!(Access::new(String::new(), vec!["http://localhost:18095".into()]).is_err());
+ assert!(Access::new("a".repeat(64), vec!["http://localhost:18095/path".into()]).is_err());
+ }
+
+ #[tokio::test]
+ async fn health_reads_stay_open_on_loopback_only() {
+ let access =
+ Arc::new(Access::new("a".repeat(64), vec!["http://localhost:18095".into()]).unwrap());
+ let app = Router::new()
+ .route("/api/pulse", get(|| async { "pulse" }))
+ .route("/api/status", get(|| async { "status" }))
+ .route("/api/goals", get(|| async { "goals" }))
+ .layer(middleware::from_fn_with_state(
+ Arc::clone(&access),
+ require_access,
+ ));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ let client = reqwest::Client::new();
+ for path in ["/api/pulse", "/api/status"] {
+ let status = client
+ .get(format!("{url}{path}"))
+ .send()
+ .await
+ .unwrap()
+ .status();
+ assert_eq!(status, 200, "{path} must stay readable for local monitors");
+ }
+ let not_public = client
+ .get(format!("{url}/api/goals"))
+ .send()
+ .await
+ .unwrap()
+ .status();
+ assert_eq!(not_public, 401);
+ let mutation = client
+ .post(format!("{url}/api/pulse"))
+ .send()
+ .await
+ .unwrap()
+ .status();
+ assert_eq!(mutation, 401);
+ let rebound = client
+ .get(format!("{url}/api/pulse"))
+ .header("Host", "evil.example:18095")
+ .send()
+ .await
+ .unwrap()
+ .status();
+ assert_eq!(rebound, 401);
+ let foreign_origin = client
+ .get(format!("{url}/api/pulse"))
+ .header("Origin", "http://evil.example")
+ .send()
+ .await
+ .unwrap()
+ .status();
+ assert_eq!(foreign_origin, 403);
+ server.abort();
+ }
+}
diff --git a/crates/spark-cockpit-rs/src/main.rs b/crates/spark-cockpit-rs/src/main.rs
index 6bf5834f..aca211dc 100644
--- a/crates/spark-cockpit-rs/src/main.rs
+++ b/crates/spark-cockpit-rs/src/main.rs
@@ -1,3 +1,5 @@
+mod access;
+
use axum::{
Router,
extract::{
@@ -26,7 +28,6 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::process::Command;
-use tower_http::cors::{Any, CorsLayer};
use tower_http::services::ServeDir;
const MAX_SEAT_URL: &str = "http://127.0.0.1:18006";
@@ -897,6 +898,10 @@ async fn handle_workshop_commit(
#[tokio::main]
async fn main() {
+ let access = Arc::new(access::Access::from_environment().unwrap_or_else(|error| {
+ eprintln!("Cockpit refused to start: {error}");
+ std::process::exit(1);
+ }));
let patterns = Arc::new(build_patterns());
let client = reqwest::Client::builder()
.tcp_nodelay(true)
@@ -1028,20 +1033,22 @@ async fn main() {
.route("/api/artifacts/{filename}", get(handle_get_artifact))
.nest_service("/artifacts", ServeDir::new(artifacts_dir()))
.fallback_service(ServeDir::new(static_dir()))
- .layer(
- CorsLayer::new()
- .allow_origin([
- "http://127.0.0.1:18095".parse().unwrap(),
- "http://localhost:18095".parse().unwrap(),
- "http://192.168.1.108:18095".parse().unwrap(),
- "http://100.116.106.93:18095".parse().unwrap(),
- ])
- .allow_methods(Any)
- .allow_headers(Any),
- )
- .with_state(state);
+ .with_state(state)
+ .layer(axum::middleware::from_fn_with_state(
+ Arc::clone(&access),
+ access::require_access,
+ ))
+ .merge(
+ Router::new()
+ .route("/login", get(access::login))
+ .route("/auth/session", post(access::session))
+ .with_state(access),
+ );
- let addr = SocketAddr::from(([127, 0, 0, 1], 18095));
+ let addr = access::bind_address().unwrap_or_else(|error| {
+ eprintln!("Cockpit refused to start: {error}");
+ std::process::exit(1);
+ });
println!(
"🚀 AIEN Native Sovereign Cockpit (Rust Axum) active on http://{}",
addr
@@ -2984,21 +2991,8 @@ struct OperatorUpdatePayload {
}
async fn handle_post_operator(
- headers: HeaderMap,
Json(payload): Json,
) -> Result, (StatusCode, Json)> {
- if let Some(token) = get_cortex_token()
- && let Some(auth) = headers.get(axum::http::header::AUTHORIZATION)
- && let Ok(auth_str) = auth.to_str()
- && let Some(provided) = auth_str.strip_prefix("Bearer ")
- && provided.trim() != token
- {
- return Err((
- StatusCode::UNAUTHORIZED,
- Json(json!({"error": "Invalid bearer token"})),
- ));
- }
-
let clean_name = payload.name.map(|n| {
n.chars()
.filter(|c| !c.is_control())
@@ -3160,10 +3154,22 @@ async fn handle_install_en2_imprint(
})))
}
+/// Mail API bearer token: environment, then the owner-only file shared with
+/// spark-mail (~/.config/aien/mail-api.token), then atlas-vault.
+fn mail_access_token() -> String {
+ if let Ok(value) = std::env::var("AIEN_MAIL_API_TOKEN")
+ && !value.trim().is_empty()
+ {
+ return value.trim().to_owned();
+ }
+ spark_adapters::vault::resolve_secret("AIEN_MAIL_API_TOKEN").unwrap_or_default()
+}
+
async fn handle_mail_status(State(state): State) -> Json {
let res = state
.client
.get(format!("{}/api/mail/status", MAIL_API_URL))
+ .bearer_auth(mail_access_token())
.timeout(Duration::from_millis(500))
.send()
.await;
@@ -3191,6 +3197,7 @@ async fn handle_mail_inbox(State(state): State) -> Json {
let res = state
.client
.get(format!("{}/api/mail/inbox", MAIL_API_URL))
+ .bearer_auth(mail_access_token())
.timeout(Duration::from_millis(800))
.send()
.await;
@@ -3208,6 +3215,7 @@ async fn handle_mail_sent(State(state): State) -> Json {
let res = state
.client
.get(format!("{}/api/mail/sent", MAIL_API_URL))
+ .bearer_auth(mail_access_token())
.timeout(Duration::from_millis(800))
.send()
.await;
@@ -3228,7 +3236,8 @@ async fn handle_mail_send(
let res = state
.client
.post(format!("{}/api/mail/send", MAIL_API_URL))
- .timeout(Duration::from_secs(3))
+ .bearer_auth(mail_access_token())
+ .timeout(Duration::from_secs(90))
.json(&payload)
.send()
.await
@@ -3561,7 +3570,7 @@ mod tests {
handle: Some("drake_ops-1".to_string()),
sign_commits: Some(true),
};
- let res = handle_post_operator(HeaderMap::new(), Json(payload)).await;
+ let res = handle_post_operator(Json(payload)).await;
assert!(res.is_ok());
let Json(body) = res.unwrap();
let op = body.get("operator").unwrap();
diff --git a/crates/spark-cockpit-rs/static/sw.js b/crates/spark-cockpit-rs/static/sw.js
index dc687c6e..28a3a695 100644
--- a/crates/spark-cockpit-rs/static/sw.js
+++ b/crates/spark-cockpit-rs/static/sw.js
@@ -1,28 +1,10 @@
-const CACHE_NAME = "aien-cockpit-v1";
-const ASSETS = [
- "/",
- "/manifest.json",
- "/icon-192.png",
- "/icon-512.png"
-];
-
-self.addEventListener("install", (e) => {
- e.waitUntil(
- caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS))
- );
- self.skipWaiting();
-});
-
-self.addEventListener("activate", (e) => {
- e.waitUntil(self.clients.claim());
-});
-
-self.addEventListener("fetch", (e) => {
- // Pass dynamic API and stream calls directly through
- if (e.request.url.includes("/api/")) {
- return;
- }
- e.respondWith(
- caches.match(e.request).then((res) => res || fetch(e.request))
- );
+// Retire cached operator pages. Authentication always reaches the server.
+self.addEventListener("install", () => self.skipWaiting());
+self.addEventListener("activate", (event) => {
+ event.waitUntil((async () => {
+ for (const name of await caches.keys()) {
+ if (name.startsWith("aien-cockpit-")) await caches.delete(name);
+ }
+ await self.clients.claim();
+ })());
});
diff --git a/docs/security/cockpit-access.md b/docs/security/cockpit-access.md
new file mode 100644
index 00000000..ea4644de
--- /dev/null
+++ b/docs/security/cockpit-access.md
@@ -0,0 +1,46 @@
+# Cockpit operator access
+
+## Opening the cockpit on the Spark (plain steps)
+
+The cockpit now asks for a password-like access token before it shows anything or lets anyone press a button. Only the Spark itself can reach it.
+
+1. Open a terminal on the Spark and type:
+
+ ```
+ atlas-vault get AIEN_COCKPIT_TOKEN
+ ```
+
+ It prints one long line of letters and numbers. Select it and copy it. That line is the cockpit key; do not paste it into chats, issues or screenshots.
+2. Open a web browser on the Spark and go to `http://127.0.0.1:18095` (or `http://localhost:18095`).
+3. The browser shows a page titled "Sign in to AIEN". Paste the key into the box and press "Sign in".
+4. The normal cockpit appears. The sign-in lasts one hour, and restarting the cockpit service also signs you out. After that, the browser returns to the sign-in page; repeat steps 1 to 3.
+
+From the MacBook, open a tunnel first (Terminal on the Mac: `ssh -L 18095:127.0.0.1:18095 `, leave it open), then follow steps 2 to 4 in a Mac browser at `http://127.0.0.1:18095`. The LAN address and the Tailscale address no longer work on purpose.
+
+## Token provisioning
+
+Both keys live in atlas-vault, the machine's TPM-sealed key store (encrypted by the Spark's security chip, kept under `~/.config/atlas/vault` with owner-only permissions). They never sit in a repository or a plain text file, and the services never print them to logs.
+
+| Key | Who reads it |
+| --- | --- |
+| `AIEN_COCKPIT_TOKEN` | spark-cockpit-rs at start; Drake pastes it at `/login` |
+| `AIEN_MAIL_API_TOKEN` | spark-mail (checks it) and the cockpit (sends it when forwarding mail requests) |
+
+Create or rotate a key, then restart the service that reads it:
+
+```
+head -c 48 /dev/urandom | base64 | tr -d '/+=\n' | atlas-vault add AIEN_COCKPIT_TOKEN
+```
+
+Store `AIEN_COCKPIT_TOKEN` and `AIEN_MAIL_API_TOKEN` with `atlas-vault add `, which reads the value from standard input. Use a random token of at least 32 ASCII characters. The cockpit and mail service resolve these through process memory or `atlas-vault get `. Plaintext token files are not supported. Missing credentials fail closed. Restart the cockpit after rotating its token; existing sessions are cleared.
+
+## What is protected
+
+- Listener: `127.0.0.1:18095` by default. `AIEN_COCKPIT_ADDR` changes it explicitly.
+- Allowed browser origins: `http://127.0.0.1:18095` and `http://localhost:18095`. `AIEN_COCKPIT_ORIGINS` (comma separated, exact origins) replaces the list. Use HTTPS for any remote browser origin.
+- Every route except `/login` and `/auth/session` needs either `Authorization: Bearer ` or a signed-in browser session. Browser sessions are random, HttpOnly, SameSite=Strict cookies with a server-enforced one-hour lifetime; HTTPS origins also get Secure cookies.
+- Browser mutations (anything other than GET/HEAD) and terminal upgrades additionally need an allowed Origin. A request carrying a foreign Origin gets 403.
+- The terminal (`/ws/terminal`) keeps its own check on top: exact loopback Origin and a loopback peer address. Remote origins cannot open a shell.
+- Health reads stay open for local monitors: `GET /api/pulse` and `GET /api/status` answer without a token, but only when the request's Host is `127.0.0.1`, `localhost` or `[::1]` (blocks DNS-rebinding pages) and it carries no foreign Origin. aien-cli, spark-debugger, spark-supervisor and bench_inference_stack only use these reads.
+
+The token authorizes the operator's administrative surface, not an untrusted agent principal.