1use std::sync::OnceLock;
14use std::time::{Duration, Instant};
15
16use axum::body::Bytes;
17use axum::extract::{ConnectInfo, DefaultBodyLimit};
18use axum::http::{HeaderMap, HeaderValue};
19use serde::Deserialize;
20
21use super::local_proof::{self, Admitted, Channels};
22use super::local_session::{CodeState, Collected, ConfirmHow, RouteClass, SessionId, SessionStore, LOGGED_FAILURES};
23use super::*;
24
25const COOKIE_PREFIX: &str = "amx-s-";
27pub(crate) const TOKEN_HEADER: &str = "x-am-session";
29pub(crate) const WS_PROTOCOL: &str = "amx-session";
31const FAILURE_DELAY: Duration = Duration::from_millis(250);
33const MAX_DELAYED: usize = 64;
35const WAIT_HOLD: Duration = Duration::from_secs(20);
37pub(crate) const COOKIE_ONLY_GET: &[&str] = &[];
41
42struct Shape {
44 cookie_name: String,
45 origins: Vec<String>,
47}
48
49impl Shape {
50 fn new(port: u16, instance_id: &str, declared: Option<&str>) -> Shape {
51 let id: String = instance_id.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
52 let mut origins = vec![format!("http://127.0.0.1:{port}")];
53 origins.extend(declared.map(str::to_string).filter(|o| *o != origins[0]));
54 Shape { cookie_name: format!("{COOKIE_PREFIX}{id}"), origins }
55 }
56
57 fn host_ok(&self, host: &str) -> bool {
58 self.origins.iter().any(|o| o.strip_prefix("http://") == Some(host))
59 }
60
61 fn bound(&self) -> &str {
63 self.origins[0].strip_prefix("http://").unwrap_or(&self.origins[0])
64 }
65
66 fn declared(&self) -> &str {
68 self.origins.get(1).map_or("", String::as_str)
69 }
70}
71
72static SHAPE: OnceLock<Shape> = OnceLock::new();
73static STORE: OnceLock<SessionStore> = OnceLock::new();
74static CHANNELS: OnceLock<Channels> = OnceLock::new();
75static SHUTDOWN: std::sync::Mutex<Option<tokio_util::sync::CancellationToken>> = std::sync::Mutex::new(None);
78
79fn store() -> &'static SessionStore {
80 STORE.get_or_init(SessionStore::default)
81}
82
83pub(crate) fn sign_in_exists() -> bool {
86 crate::headless::local_sign_in() || store().session_count(std::time::Instant::now()) > 0
87}
88
89fn channels() -> &'static Channels {
90 CHANNELS.get_or_init(Channels::default)
91}
92
93pub(crate) fn enable(port: u16, instance_id: &str) {
95 if crate::headless::local_sign_in() {
96 let _ = SHAPE.set(Shape::new(port, instance_id, crate::headless::public_origin()));
97 crate::headless::publish_port(port);
98 if let Some((path, binding)) = crate::headless::session_file() {
99 store().keep_in(path, binding, Instant::now(), agentmux_common::time::now_secs_u64());
100 }
101 }
102}
103
104pub(crate) fn set_shutdown(token: tokio_util::sync::CancellationToken) {
106 *SHUTDOWN.lock().unwrap_or_else(|e| e.into_inner()) = Some(token);
107}
108
109pub(crate) fn enabled() -> bool {
110 SHAPE.get().is_some()
111}
112
113pub(crate) fn routes() -> Router<AppState> {
115 Router::new()
116 .route("/auth/hello", post(handle_hello))
117 .route("/auth/code", post(handle_code))
118 .route("/auth/pending", post(handle_pending))
119 .route("/auth/confirm", post(handle_confirm))
120 .route("/auth/logout", post(handle_logout))
121 .route("/auth/sessions", post(handle_sessions))
122 .route("/auth/shutdown", post(handle_shutdown))
123 .route("/auth/enter", get(handle_page).post(handle_enter))
124 .route("/auth/enter.js", get(handle_script))
125 .route("/auth/enter.css", get(handle_style))
126 .route("/auth/wait", post(handle_wait))
127 .route("/auth/signout", post(handle_signout))
128 .route("/auth/signout-all", post(handle_signout_all))
129 .layer(DefaultBodyLimit::max(1024))
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136enum Reason {
137 Code,
138 Host,
139 Origin,
140 FetchSite,
141 Proof,
142 Session,
143}
144
145impl Reason {
146 fn name(self) -> &'static str {
147 match self {
148 Reason::Code => "code",
149 Reason::Host => "host",
150 Reason::Origin => "origin",
151 Reason::FetchSite => "fetch-site",
152 Reason::Proof => "proof",
153 Reason::Session => "session",
154 }
155 }
156}
157
158#[derive(Clone, Copy, PartialEq, Eq)]
159enum Kind {
160 Client,
162 Browser,
164 Any,
166}
167
168fn hval<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
169 headers.get(name).and_then(|v| v.to_str().ok())
170}
171
172fn check_shape(shape: &Shape, headers: &HeaderMap, kind: Kind) -> Result<(), Reason> {
175 if !hval(headers, "host").is_some_and(|h| shape.host_ok(h)) {
176 return Err(Reason::Host);
177 }
178 if let Some(origin) = headers.get(header::ORIGIN) {
179 if !origin.to_str().is_ok_and(|o| shape.origins.iter().any(|x| x == o)) {
180 return Err(Reason::Origin);
181 }
182 }
183 let site = headers.get("sec-fetch-site");
184 let site_ok = match kind {
185 Kind::Client => site.is_none(),
186 Kind::Browser => site.is_some_and(|s| s == "same-origin"),
187 Kind::Any => true,
188 };
189 if site_ok { Ok(()) } else { Err(Reason::FetchSite) }
190}
191
192async fn refuse(route: &'static str, reason: Reason) -> Response {
194 static DELAYED: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(MAX_DELAYED);
195 let recent = store().note_failure(Instant::now());
196 match recent {
197 n if n <= LOGGED_FAILURES => tracing::warn!(route, reason = reason.name(), failures_last_minute = n, "local sign-in refused"),
198 n if n == LOGGED_FAILURES + 1 => tracing::warn!(failures_last_minute = n, "local sign-in refused again and again: more this minute are counted, not logged"),
199 _ => {}
200 }
201 if let Ok(_slot) = DELAYED.try_acquire() {
202 tokio::time::sleep(FAILURE_DELAY).await;
203 }
204 refusal()
205}
206
207fn refusal() -> Response {
208 let mut r = (StatusCode::FORBIDDEN, "not accepted").into_response();
209 r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
210 r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
211 r
212}
213
214fn no_store(mut r: Response) -> Response {
215 r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
216 r
217}
218
219async fn channel_gate(headers: &HeaderMap, route: &'static str, body: &[u8]) -> Result<Admitted, Response> {
223 let Some(shape) = SHAPE.get() else { return Err(refusal()) };
224 if let Err(reason) = check_shape(shape, headers, Kind::Client) {
225 return Err(refuse(route, reason).await);
226 }
227 let seq = hval(headers, local_proof::SEQ_HEADER).and_then(|s| s.parse::<u64>().ok());
228 let admitted = match (hval(headers, local_proof::CHANNEL_HEADER), seq, hval(headers, local_proof::PROOF_HEADER)) {
229 (Some(channel), Some(seq), Some(proof)) => channels().admit(channel, seq, "POST", route, body, proof, Instant::now()),
230 _ => None,
231 };
232 match admitted {
233 Some(a) => Ok(a),
234 None => Err(refuse(route, Reason::Proof).await),
235 }
236}
237
238fn proved(admitted: &Admitted, value: serde_json::Value) -> Response {
240 let body = serde_json::to_vec(&value).unwrap_or_default();
241 let proof = local_proof::response_proof(&admitted.key, admitted.seq, 200, &body);
242 let mut r = (StatusCode::OK, body).into_response();
243 r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
244 if let Ok(v) = HeaderValue::from_str(&proof) {
245 r.headers_mut().insert(local_proof::PROOF_HEADER, v);
246 }
247 no_store(r)
248}
249
250#[derive(Deserialize)]
251struct HelloBody {
252 nonce: String,
253}
254
255#[derive(Deserialize)]
256struct CodeBody {
257 code: String,
258}
259
260#[derive(Deserialize)]
261struct ConfirmBody {
262 code: String,
263 accept: bool,
264}
265
266#[derive(Deserialize)]
267struct HandleBody {
268 handle: String,
269}
270
271async fn handle_hello(State(state): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
277 let Some(shape) = SHAPE.get() else { return refusal() };
278 if let Err(reason) = check_shape(shape, &headers, Kind::Client) {
279 return refuse("/auth/hello", reason).await;
280 }
281 let Ok(HelloBody { nonce }) = serde_json::from_slice(&body) else { return refuse("/auth/hello", Reason::Code).await };
282 let Some(hello) = channels().hello(state.auth_key.as_bytes(), &nonce, shape.bound(), shape.declared(), Instant::now()) else {
283 return refuse("/auth/hello", Reason::Code).await;
284 };
285 no_store(Json(json!({ "channel": hello.channel, "nonce": hello.nonce, "declared": shape.declared(), "proof": hello.proof })).into_response())
286}
287
288async fn handle_code(headers: HeaderMap, body: Bytes) -> Response {
290 let admitted = match channel_gate(&headers, "/auth/code", &body).await {
291 Ok(a) => a,
292 Err(r) => return r,
293 };
294 proved(&admitted, json!({ "code": store().mint_code(Instant::now()) }))
295}
296
297async fn handle_pending(headers: HeaderMap, body: Bytes) -> Response {
299 let admitted = match channel_gate(&headers, "/auth/pending", &body).await {
300 Ok(a) => a,
301 Err(r) => return r,
302 };
303 let Ok(CodeBody { code }) = serde_json::from_slice(&body) else { return refuse("/auth/pending", Reason::Code).await };
304 let state = match store().code_state(&code, Instant::now()) {
305 CodeState::Unused => json!({ "state": "unused" }),
306 CodeState::Entered { phrase } => json!({ "state": "entered", "phrase": phrase }),
307 CodeState::Gone => json!({ "state": "gone" }),
308 };
309 proved(&admitted, state)
310}
311
312async fn handle_confirm(
317 State(state): State<AppState>,
318 conn: Option<ConnectInfo<super::confirm_peer::Conn>>,
319 headers: HeaderMap,
320 body: Bytes,
321) -> Response {
322 let admitted = match channel_gate(&headers, "/auth/confirm", &body).await {
323 Ok(a) => a,
324 Err(r) => return r,
325 };
326 let Ok(ConfirmBody { code, accept }) = serde_json::from_slice(&body) else { return refuse("/auth/confirm", Reason::Code).await };
327 if accept {
328 let how = match conn {
329 Some(ConnectInfo(conn)) => super::confirm_peer::classify(&state, conn, super::confirm_peer::is_forwarded(&headers)).await,
330 None => ConfirmHow::Unknown,
331 };
332 let found = store().note_confirm(&code, how.clone(), Instant::now());
333 if !how.is_taken() {
334 tracing::warn!(found, how = %how.label(), "local sign-in confirm not taken");
335 return proved(&admitted, json!({ "found": false, "refused": super::confirm_peer::refusal_text(&how) }));
336 }
337 }
338 let found = store().decide(&code, accept, Instant::now());
339 tracing::info!(accepted = accept && found, found, "local sign-in answered");
340 proved(&admitted, json!({ "found": found }))
341}
342
343async fn handle_logout(headers: HeaderMap, body: Bytes) -> Response {
345 let admitted = match channel_gate(&headers, "/auth/logout", &body).await {
346 Ok(a) => a,
347 Err(r) => return r,
348 };
349 let revoked = store().revoke_all();
350 tracing::info!(revoked, "local sign-in sessions revoked");
351 proved(&admitted, json!({ "revoked": revoked }))
352}
353
354async fn handle_sessions(headers: HeaderMap, body: Bytes) -> Response {
357 let admitted = match channel_gate(&headers, "/auth/sessions", &body).await {
358 Ok(a) => a,
359 Err(r) => return r,
360 };
361 let confirms: Vec<_> = store()
362 .confirms()
363 .iter()
364 .map(|c| json!({ "at_unix_ms": c.at_unix_ms, "session": c.session, "how": c.how.label() }))
365 .collect();
366 proved(&admitted, json!({ "sessions": store().session_count(Instant::now()), "confirms": confirms }))
367}
368
369async fn handle_shutdown(headers: HeaderMap, body: Bytes) -> Response {
372 let admitted = match channel_gate(&headers, "/auth/shutdown", &body).await {
373 Ok(a) => a,
374 Err(r) => return r,
375 };
376 let token = SHUTDOWN.lock().unwrap_or_else(|e| e.into_inner()).clone();
377 let known = token.is_some();
378 if let Some(token) = token {
379 tracing::info!("shutdown asked for by `agentmux stop`");
380 tokio::spawn(async move {
381 tokio::time::sleep(Duration::from_millis(300)).await;
382 token.cancel();
383 });
384 }
385 proved(&admitted, json!({ "stopping": known }))
386}
387
388async fn handle_page(headers: HeaderMap) -> Response {
392 let Some(shape) = SHAPE.get() else { return refusal() };
393 if let Err(reason) = check_shape(shape, &headers, Kind::Any) {
394 return refuse("/auth/enter", reason).await;
395 }
396 with_ui_headers(shape, no_store(([(header::CONTENT_TYPE, "text/html; charset=utf-8")], ENTER_HTML).into_response()))
397}
398
399async fn handle_script() -> Response {
400 let Some(shape) = SHAPE.get() else { return refusal() };
401 with_ui_headers(shape, no_store(([(header::CONTENT_TYPE, "text/javascript; charset=utf-8")], ENTER_JS).into_response()))
402}
403
404async fn handle_style() -> Response {
405 let Some(shape) = SHAPE.get() else { return refusal() };
406 with_ui_headers(shape, no_store(([(header::CONTENT_TYPE, "text/css; charset=utf-8")], ENTER_CSS).into_response()))
407}
408
409async fn handle_enter(headers: HeaderMap, body: Bytes) -> Response {
412 let Some(shape) = SHAPE.get() else { return refusal() };
413 if let Err(reason) = check_shape(shape, &headers, Kind::Browser) {
414 return refuse("/auth/enter", reason).await;
415 }
416 let entered = serde_json::from_slice::<CodeBody>(&body).ok().and_then(|b| store().enter(&b.code, Instant::now()));
417 match entered {
418 Some(e) => no_store(Json(json!({ "handle": e.handle, "phrase": e.phrase })).into_response()),
419 None => refuse("/auth/enter", Reason::Code).await,
420 }
421}
422
423async fn handle_wait(headers: HeaderMap, body: Bytes) -> Response {
426 let Some(shape) = SHAPE.get() else { return refusal() };
427 if let Err(reason) = check_shape(shape, &headers, Kind::Browser) {
428 return refuse("/auth/wait", reason).await;
429 }
430 let Ok(HandleBody { handle }) = serde_json::from_slice(&body) else { return refuse("/auth/wait", Reason::Code).await };
431 let until = Instant::now() + WAIT_HOLD;
432 loop {
433 match store().collect(&handle, Instant::now()) {
434 Collected::Granted(grant) => {
435 let cookie = format!("{}={}; HttpOnly; SameSite=Strict; Path=/", shape.cookie_name, grant.cookie);
436 let mut r = no_store(Json(json!({ "token": grant.token })).into_response());
437 if let Ok(v) = HeaderValue::from_str(&cookie) {
438 r.headers_mut().insert(header::SET_COOKIE, v);
439 }
440 return r;
441 }
442 Collected::Refused => return refuse("/auth/wait", Reason::Code).await,
443 Collected::Waiting if Instant::now() >= until => return no_store((StatusCode::ACCEPTED, Json(json!({ "waiting": true }))).into_response()),
444 Collected::Waiting => tokio::time::sleep(Duration::from_millis(200)).await,
445 }
446 }
447}
448
449async fn handle_signout(req: Request<Body>) -> Response {
452 let Some(shape) = SHAPE.get() else { return refusal() };
453 if let Err(reason) = check_shape(shape, req.headers(), Kind::Browser) {
454 return refuse("/auth/signout", reason).await;
455 }
456 let Some(session) = admit_session(&req) else { return refuse("/auth/signout", Reason::Session).await };
457 let ended = store().revoke(session, Instant::now());
458 tracing::info!(ended, "local sign-in session signed out");
459 let mut r = no_store(Json(json!({ "signedOut": ended })).into_response());
460 let cleared = format!("{}=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/", shape.cookie_name);
461 if let Ok(v) = HeaderValue::from_str(&cleared) {
462 r.headers_mut().insert(header::SET_COOKIE, v);
463 }
464 r
465}
466
467async fn handle_signout_all(req: Request<Body>) -> Response {
470 let Some(shape) = SHAPE.get() else { return refusal() };
471 if let Err(reason) = check_shape(shape, req.headers(), Kind::Browser) {
472 return refuse("/auth/signout-all", reason).await;
473 }
474 if admit_session(&req).is_none() {
475 return refuse("/auth/signout-all", Reason::Session).await;
476 }
477 let ended = store().revoke_all();
478 tracing::info!(ended, "every local sign-in session signed out from a browser");
479 let mut r = no_store(Json(json!({ "signedOut": ended })).into_response());
480 let cleared = format!("{}=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/", shape.cookie_name);
481 if let Ok(v) = HeaderValue::from_str(&cleared) {
482 r.headers_mut().insert(header::SET_COOKIE, v);
483 }
484 r
485}
486
487pub(crate) fn route_class(method: &Method, path: &str) -> RouteClass {
492 use crate::backend::route_audience::Match;
493 let listed = *method == Method::GET && COOKIE_ONLY_GET.iter().any(|pattern| Match::Route(*pattern).matches(path));
494 if listed { RouteClass::CookieOnly } else { RouteClass::Both }
495}
496
497fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
498 hval(headers, "cookie")?.split(';').filter_map(|c| c.trim().split_once('=')).find(|(n, _)| *n == name).map(|(_, v)| v)
499}
500
501fn is_websocket_route(path: &str) -> bool {
503 path == "/ws" || path == super::streamed_browser::ROUTE
504}
505
506fn session_token<'a>(headers: &'a HeaderMap, path: &str) -> Option<&'a str> {
508 if let Some(t) = hval(headers, TOKEN_HEADER) {
509 return Some(t);
510 }
511 if !is_websocket_route(path) {
512 return None;
513 }
514 hval(headers, "sec-websocket-protocol")?.split(',').map(str::trim).find(|p| !p.is_empty() && *p != WS_PROTOCOL)
515}
516
517pub(crate) fn admit_session(req: &Request<Body>) -> Option<SessionId> {
520 let shape = SHAPE.get()?;
521 let headers = req.headers();
522 check_shape(shape, headers, Kind::Any).ok()?;
523 let class = route_class(req.method(), req.uri().path());
524 if class == RouteClass::CookieOnly && hval(headers, "sec-fetch-site") != Some("same-origin") {
525 return None;
526 }
527 let cookie = cookie_value(headers, &shape.cookie_name)?;
528 let token = session_token(headers, req.uri().path());
529 store().admit(Some(cookie), token, class, Instant::now()).then(|| SessionId::of_cookie(cookie))
530}
531
532pub(crate) async fn session_ended(session: Option<SessionId>) {
535 match session {
536 Some(id) => store().ended(id).await,
537 None => std::future::pending().await,
538 }
539}
540
541fn content_security_policy(shape: &Shape) -> String {
550 let ws: Vec<String> = shape.origins.iter().map(|o| o.replacen("http://", "ws://", 1)).collect();
551 format!(
552 "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; \
553 font-src 'self' data:; connect-src 'self' {}; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; \
554 form-action 'self'; frame-ancestors 'none'",
555 ws.join(" ")
556 )
557}
558
559fn with_ui_headers(shape: &Shape, mut r: Response) -> Response {
560 let h = r.headers_mut();
561 if let Ok(v) = HeaderValue::from_str(&content_security_policy(shape)) {
562 h.insert(header::CONTENT_SECURITY_POLICY, v);
563 }
564 h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
565 h.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
566 h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
567 r
568}
569
570fn ui_host_ok(shape: &Shape, headers: &HeaderMap) -> bool {
573 hval(headers, "host").is_some_and(|h| shape.host_ok(h))
574}
575
576pub(crate) async fn ui_headers(req: Request<Body>, next: Next) -> Response {
578 if let Some(shape) = SHAPE.get() {
579 if !ui_host_ok(shape, req.headers()) {
580 return refusal();
581 }
582 }
583 let response = next.run(req).await;
584 match SHAPE.get() {
585 Some(shape) => with_ui_headers(shape, response),
586 None => response,
587 }
588}
589
590const ENTER_HTML: &str = r#"<!doctype html>
591<html lang="en">
592<head>
593<meta charset="utf-8">
594<meta name="viewport" content="width=device-width, initial-scale=1">
595<meta name="referrer" content="no-referrer">
596<title>Open AgentMux</title>
597<link rel="stylesheet" href="/auth/enter.css">
598</head>
599<body>
600<main>
601<h1>AgentMux</h1>
602<p id="msg">Opening…</p>
603<p id="phrase" hidden></p>
604<p id="hint" hidden>Compare this with the terminal where you ran <code>agentmux open</code>. Answer <code>y</code> there only if the two match: that keeps another user of this computer from opening your AgentMux.</p>
605<form id="paste" hidden><label>Code from the terminal <input id="code" autocomplete="off" autocapitalize="off" spellcheck="false"></label> <button type="submit">Open</button></form>
606</main>
607<script src="/auth/enter.js"></script>
608</body>
609</html>
610"#;
611
612const ENTER_CSS: &str = "body{font-family:system-ui,sans-serif;background:#111;color:#eee;display:flex;justify-content:center;padding-top:15vh}\
613main{max-width:34rem;padding:0 1rem;text-align:center}\
614#phrase{font-family:ui-monospace,monospace;font-size:3rem;letter-spacing:.05em;margin:1.5rem 0}\
615#hint{color:#bbb}code{background:#222;padding:.1rem .3rem;border-radius:.2rem}\
616#paste{margin-top:1rem}#code{font-family:ui-monospace,monospace;background:#222;color:#eee;border:1px solid #444;border-radius:.2rem;padding:.3rem;width:20rem;max-width:100%}\n";
617
618const ENTER_JS: &str = r#"(() => {
623 const msg = document.getElementById("msg");
624 const phrase = document.getElementById("phrase");
625 const hint = document.getElementById("hint");
626 const paste = document.getElementById("paste");
627 const field = document.getElementById("code");
628 // Each attempt to open is a run; a new code in the fragment (a hash-only navigation in this tab) starts a new one and ends the last.
629 let run = 0;
630 const begin = async () => {
631 const mine = ++run;
632 const current = () => mine === run;
633 const fail = () => {
634 if (!current()) return;
635 msg.textContent = "not accepted";
636 phrase.hidden = true;
637 // The same words for everyone, whatever went wrong: how to try again.
638 hint.textContent = "Run agentmux open in the terminal again for a new link.";
639 hint.hidden = false;
640 };
641 msg.textContent = "Opening...";
642 phrase.hidden = true;
643 hint.hidden = true;
644 paste.hidden = true;
645 const code = location.hash.slice(1);
646 history.replaceState(null, "", location.pathname);
647 if (!code) {
648 // Nobody tried to open it: a visitor with no session, or a browser that has just been disconnected.
649 msg.textContent = "This browser is not open to AgentMux.";
650 hint.textContent = "To open AgentMux here, run agentmux open (or agentmux-srv open) in a terminal on the machine where AgentMux runs, as the user that started it, and paste the code it prints below if its link will not copy.";
651 hint.hidden = false;
652 paste.hidden = false;
653 return;
654 }
655 const post = (path, body) =>
656 fetch(path, {
657 method: "POST",
658 headers: { "content-type": "application/json" },
659 body: JSON.stringify(body),
660 cache: "no-store",
661 credentials: "same-origin",
662 });
663 let entered;
664 try {
665 const r = await post("/auth/enter", { code });
666 if (!current()) return;
667 if (!r.ok) return fail();
668 entered = await r.json();
669 } catch {
670 return fail();
671 }
672 if (!current()) return;
673 msg.textContent = "Waiting for you to confirm in the terminal.";
674 phrase.textContent = entered.phrase;
675 phrase.hidden = false;
676 hint.textContent = "Compare this with the terminal where you ran agentmux open. Answer y there only if the two match: that keeps another user of this computer from opening your AgentMux.";
677 hint.hidden = false;
678 for (;;) {
679 let w;
680 try {
681 w = await post("/auth/wait", { handle: entered.handle });
682 } catch {
683 return fail();
684 }
685 if (!current()) return;
686 if (w.status === 202) continue;
687 if (!w.ok) return fail();
688 const { token } = await w.json();
689 if (!current()) return;
690 sessionStorage.setItem("amx-session", token);
691 location.replace("/");
692 return;
693 }
694 };
695 paste.addEventListener("submit", (e) => {
696 e.preventDefault();
697 const typed = field.value.trim();
698 field.value = "";
699 if (typed) location.hash = typed;
700 });
701 window.addEventListener("hashchange", begin);
702 begin();
703})();
704"#;
705
706#[cfg(test)]
707#[path = "tests/local_session_route_tests.rs"]
708mod tests;