Skip to main content

unlinkable_inference_cli/
serve.rs

1//! The local proxy server.
2//!
3//! Agents and SDKs talk to it as if it were the OpenAI or Anthropic API. For
4//! each conversation it opens a session paid with vouchers from the wallet,
5//! sends the request with the session secret in place of any key, streams the
6//! answer back, and closes the session once the conversation goes quiet,
7//! putting the change back in the wallet. Whatever key the client sends stays
8//! here: it only names which session to use.
9
10use crate::{dollars, Options};
11use anyhow::{anyhow, Result};
12use axum::{
13    body::Body,
14    extract::{Request, State},
15    http::{HeaderMap, HeaderValue, StatusCode},
16    response::{Html, IntoResponse, Response},
17    Json, Router,
18};
19use futures::StreamExt;
20use serde_json::{json, Value};
21use std::collections::{HashMap, VecDeque};
22use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
23use std::sync::{Arc, Mutex};
24use std::time::{Duration, SystemTime, UNIX_EPOCH};
25use unlinkable_inference::net::{Client, Observed, Request as Inner, Session};
26use unlinkable_inference::{Family, Voucher, Wallet};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Mode {
30    /// A new session for each conversation (system prompt + first user message)
31    Conversation,
32    /// One session per API key the client sends (name keys per agent run)
33    Key,
34    /// One session for everything until it goes idle
35    Run,
36}
37
38impl std::str::FromStr for Mode {
39    type Err = String;
40    fn from_str(s: &str) -> Result<Self, String> {
41        match s {
42            "conversation" => Ok(Mode::Conversation),
43            "key" => Ok(Mode::Key),
44            "run" => Ok(Mode::Run),
45            _ => Err("use conversation, key or run".into()),
46        }
47    }
48}
49
50#[derive(Debug, Clone)]
51pub struct Settings {
52    /// What each new session is funded with, in cents
53    pub funding_cents: i64,
54    pub mode: Mode,
55    /// Close a session after this long without a request
56    pub idle_close: Duration,
57    pub show_traffic: bool,
58    /// The account's API key, for keeping the wallet and passes topped up.
59    /// Never sent with a chat. If unset, the proxy learns it from the first
60    /// `sk-obs1_` key a client sends.
61    pub account_key: Option<String>,
62    /// Withdraw when the wallet holds less than this many cents…
63    pub keep_cents: i64,
64    /// …this much (one of the fixed withdrawal sizes)
65    pub refill_cents: i64,
66    /// Fetch passes when fewer than this many are left this month
67    pub keep_passes: usize,
68    /// The account is asked at random times this many seconds apart (min, max)...
69    pub contact_secs: (u64, u64),
70    /// ...and, when a request waits for it, at a random moment this far away (never sooner).
71    pub wait_secs: (u64, u64),
72    /// A request that needs money or a pass the wallet doesn't hold gets it from the account at
73    /// once (default; the two requests are then seconds apart, a hint that they go together).
74    /// False: the request waits (503, Retry-After) for a random contact instead.
75    pub fund_now: bool,
76    /// Client keys starting with this are taken to be the account's key
77    pub account_key_prefix: String,
78}
79
80impl Default for Settings {
81    fn default() -> Self {
82        Self {
83            funding_cents: 50,
84            mode: Mode::Conversation,
85            idle_close: Duration::from_secs(300),
86            show_traffic: false,
87            account_key: None,
88            // A pricey model's reply ($1 held, plus its prompt) fits in what the wallet keeps.
89            keep_cents: 200,
90            refill_cents: 500,
91            keep_passes: 10,
92            contact_secs: CONTACT_SECS,
93            wait_secs: WAIT_SECS,
94            fund_now: true,
95            account_key_prefix: "sk-obs1_".into(),
96        }
97    }
98}
99
100/// A session without money is closed after this long without a request.
101const FREE_IDLE_SECS: u64 = 6 * 3600;
102
103struct Entry {
104    session: Session,
105    /// Opened with a pass and no money: nothing to bring back, so it stays open longer
106    free: bool,
107    last_used: AtomicU64,
108    busy: AtomicUsize,
109    opened_at: u64,
110    requests: AtomicU64,
111}
112
113/// The account is asked for money and passes only at moments of its own (the proxy starting) and
114/// at random times: never because a request needs it. A withdrawal a second before a session
115/// opens or tops up ties the two together by timing alone.
116struct Contact {
117    /// When (Unix seconds)
118    next: u64,
119    /// A request is waiting for what only the account can give
120    waiting: bool,
121    /// The account had nothing to give at the last contact
122    account_empty: bool,
123    /// After the contact a waiting request needed, sessions are opened and topped up only from
124    /// this time (Unix seconds), so the withdrawal and the session's top-up aren't seconds apart
125    release_at: u64,
126    /// Labels a session asked for that the wallet had none of
127    wanted: std::collections::BTreeSet<String>,
128    /// Conversations told to wait: their retries are answered here, never sent on to the server
129    /// (a retry timed by Retry-After would land right next to the contact)
130    held: std::collections::HashSet<String>,
131}
132
133/// The account is asked this many seconds apart (at random in between)...
134pub const CONTACT_SECS: (u64, u64) = (5 * 60, 30 * 60);
135/// ...and, when a request waits for it, at a random moment this far away (never sooner).
136pub const WAIT_SECS: (u64, u64) = (60, 600);
137
138fn random_secs((min, max): (u64, u64)) -> u64 {
139    unlinkable_inference::manager::random_secs(min, max)
140}
141
142/// The request waits for the wallet (see [`Contact`]): 503 with Retry-After.
143fn refilling(at: u64) -> Response {
144    let wait = at.saturating_sub(now()).max(1);
145    let mut r = text(
146        StatusCode::SERVICE_UNAVAILABLE,
147        &format!("The private wallet is refilling from the account; try again in {wait} s. (It is never refilled at the moment a request needs it: that would tie the request to the account.)"),
148    );
149    r.headers_mut().insert("retry-after", wait.to_string().parse().unwrap());
150    r
151}
152
153#[derive(Debug)]
154struct Refilling(u64);
155
156impl std::fmt::Display for Refilling {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        write!(f, "the private wallet is refilling")
159    }
160}
161
162impl std::error::Error for Refilling {}
163
164pub struct Proxy {
165    client: Client,
166    wallet: tokio::sync::Mutex<Wallet>,
167    sessions: Mutex<HashMap<String, Arc<Entry>>>,
168    /// Held-conversation revs (x-obscurify-thread) to the session that owns them
169    threads: Mutex<HashMap<String, String>>,
170    traffic: Arc<Mutex<VecDeque<(u64, Observed)>>>,
171    opening: tokio::sync::Mutex<()>,
172    settings: Settings,
173    opts: Options,
174    account_key: Mutex<Option<String>>,
175    /// When the account is asked next, and what for (see [`Proxy::refill`])
176    contact: Mutex<Contact>,
177    /// The contact made as the proxy starts is done (requests wait for it: it is the account's
178    /// own moment, not theirs)
179    started: std::sync::atomic::AtomicBool,
180    /// The labels the account gets passes for, as last asked (at most every 10 minutes), and when
181    offered: tokio::sync::Mutex<Option<(unlinkable_inference::protocol::PassAllowance, std::time::Instant)>>,
182    /// The helper session's last seen balance (see [`Proxy::helper_secret`])
183    helper_balance: Mutex<String>,
184}
185
186/// The session handed out by `/_unlinkable/key` for agents that talk to the
187/// server directly (Claude Code's `apiKeyHelper`).
188const HELPER: &str = "helper";
189
190/// The server no longer knows this session (expired or closed elsewhere).
191fn gone(e: &anyhow::Error) -> bool {
192    matches!(
193        e.downcast_ref::<unlinkable_inference::net::ApiError>(),
194        Some(unlinkable_inference::net::ApiError::Server { status: 401 | 404 | 410, .. })
195    )
196}
197
198fn now() -> u64 {
199    SystemTime::now()
200        .duration_since(UNIX_EPOCH)
201        .map(|d| d.as_secs())
202        .unwrap_or(0)
203}
204
205/// Request headers passed on. Everything else (user agents, SDK telemetry,
206/// the client's own key) stays on this machine.
207const PASSED_HEADERS: &[&str] = &[
208    "content-type",
209    "accept",
210    "anthropic-version",
211    "anthropic-beta",
212    "openai-beta",
213];
214
215const DROPPED_RESPONSE_HEADERS: &[&str] = &[
216    "content-length",
217    "transfer-encoding",
218    "connection",
219    "set-cookie",
220];
221
222const MAX_BODY: usize = 32 * 1024 * 1024;
223
224/// POST endpoints (and anything under them) forwarded to the server.
225const FORWARDED_POSTS: &[&str] = &[
226    "/v1/chat/completions",
227    "/v1/completions",
228    "/v1/responses",
229    "/v1/messages",
230    "/v1/embeddings",
231    "/v1/images",
232    "/v1/tools",
233];
234
235fn text(status: StatusCode, message: &str) -> Response {
236    (
237        status,
238        Json(json!({"error": {"message": message, "type": "unlinkable_inference_cli_error"}})),
239    )
240        .into_response()
241}
242
243/// The part of a request that stays the same for a whole conversation.
244pub fn conversation_fingerprint(path: &str, body: &Value) -> String {
245    // Claude Code posts to /v1/messages?beta=true.
246    let path = path.split('?').next().unwrap_or(path);
247    let parts = if path.ends_with("/chat/completions") {
248        let messages = body["messages"].as_array().cloned().unwrap_or_default();
249        let end = messages
250            .iter()
251            .position(|m| m["role"] == "user")
252            .map(|i| i + 1)
253            .unwrap_or(messages.len());
254        json!(messages[..end])
255    } else if path.ends_with("/messages") || path.ends_with("/messages/count_tokens") {
256        json!([body["system"], body["messages"][0]])
257    } else if path.ends_with("/responses") {
258        let first = match &body["input"] {
259            Value::Array(items) => items.first().cloned().unwrap_or(Value::Null),
260            other => other.clone(),
261        };
262        json!([body["instructions"], first])
263    } else {
264        Value::Null
265    };
266    unlinkable_inference::sha256_hex(parts.to_string())[..16].to_string()
267}
268
269/// Body fields that say who or what is calling and that no model reads: Claude Code puts a fixed
270/// device id in `metadata`, Codex an installation id in `client_metadata`. Any of them would tie
271/// one conversation to the next.
272const DROPPED_BODY_FIELDS: &[&str] = &[
273    "metadata",
274    "client_metadata",
275    "user",
276    "safety_identifier",
277    "prompt_cache_key",
278];
279
280/// The body without [`DROPPED_BODY_FIELDS`]; untouched when it has none.
281fn without_client_ids(body: bytes::Bytes, json: &Value) -> bytes::Bytes {
282    let Some(fields) = json.as_object() else {
283        return body;
284    };
285    if !DROPPED_BODY_FIELDS.iter().any(|f| fields.contains_key(*f)) {
286        return body;
287    }
288    let mut fields = fields.clone();
289    fields.retain(|k, _| !DROPPED_BODY_FIELDS.contains(&k.as_str()));
290    Value::Object(fields).to_string().into()
291}
292
293fn client_key(headers: &HeaderMap) -> String {
294    headers
295        .get("authorization")
296        .and_then(|v| v.to_str().ok())
297        .map(|v| v.trim_start_matches("Bearer ").trim().to_string())
298        .or_else(|| {
299            headers
300                .get("x-api-key")
301                .and_then(|v| v.to_str().ok())
302                .map(str::to_string)
303        })
304        .unwrap_or_default()
305}
306
307impl Proxy {
308    pub fn new(mut client: Client, wallet: Wallet, settings: Settings, opts: Options) -> Arc<Self> {
309        let traffic: Arc<Mutex<VecDeque<(u64, Observed)>>> = Arc::new(Mutex::new(VecDeque::new()));
310        let log = traffic.clone();
311        let show = settings.show_traffic;
312        client.transport = client.transport.clone().observe(Arc::new(move |o: &Observed| {
313            if show {
314                eprintln!("→ {}: {}", o.server, o.server_sees);
315            }
316            let mut log = log.lock().unwrap();
317            log.push_front((now(), o.clone()));
318            log.truncate(100);
319        }));
320        Arc::new(Self {
321            client,
322            wallet: tokio::sync::Mutex::new(wallet),
323            sessions: Mutex::new(HashMap::new()),
324            threads: Mutex::new(HashMap::new()),
325            traffic,
326            opening: tokio::sync::Mutex::new(()),
327            account_key: Mutex::new(settings.account_key.clone()),
328            contact: Mutex::new(Contact { next: now(), waiting: false, account_empty: false, release_at: 0, wanted: Default::default(), held: Default::default() }),
329            offered: tokio::sync::Mutex::new(None),
330            // Without a key at start there is no start-up contact to wait for.
331            started: std::sync::atomic::AtomicBool::new(settings.account_key.is_none()),
332            helper_balance: Mutex::new(String::new()),
333            settings,
334            opts,
335        })
336    }
337
338    fn session_key(&self, path: &str, headers: &HeaderMap, body: &Value) -> String {
339        if let Some(rev) = body["thread"]["rev"].as_str() {
340            if let Some(key) = self.threads.lock().unwrap().get(rev) {
341                return key.clone();
342            }
343        }
344        match self.settings.mode {
345            Mode::Run => "run".to_string(),
346            Mode::Key => format!("key:{}", client_key(headers)),
347            Mode::Conversation => format!(
348                "conv:{}:{}",
349                client_key(headers),
350                conversation_fingerprint(path, body)
351            ),
352        }
353    }
354
355    async fn family_to_spend(&self) -> Family {
356        let wallet = self.wallet.lock().await;
357        if wallet.balance_cents(Family::Paid) == 0 && wallet.balance_cents(Family::Promo) > 0 {
358            Family::Promo
359        } else {
360            Family::Paid
361        }
362    }
363
364    /// A request needs what only the account can give: `Some(when)` the next contact is (brought
365    /// forward to a random moment `WAIT_SECS` away, unless one is due sooner); `None` when the
366    /// account has nothing to give, or there is no account key.
367    fn wait(&self) -> Option<u64> {
368        if self.account_key.lock().unwrap().is_none() {
369            return None;
370        }
371        let mut c = self.contact.lock().unwrap();
372        if c.account_empty {
373            return None;
374        }
375        if !c.waiting && now() < c.release_at {
376            return Some(c.release_at);
377        }
378        c.next = c.next.min(now() + random_secs(self.settings.wait_secs));
379        c.waiting = true;
380        Some(c.next)
381    }
382
383    /// Just filled for a request that waited: `Some(until)` while new sessions and top-ups hold
384    /// back (see `Contact::release_at`).
385    fn held_back(&self) -> Option<u64> {
386        let c = self.contact.lock().unwrap();
387        (now() < c.release_at).then_some(c.release_at)
388    }
389
390    /// Conversation `key` was told to wait: until the wallet is filled and the hold-back is
391    /// over, its requests are answered here. `Some(until)` while it waits.
392    fn still_held(&self, key: &str) -> Option<u64> {
393        let mut c = self.contact.lock().unwrap();
394        if !c.held.contains(key) {
395            return None;
396        }
397        // Waiting: until the contact, or (one is under way, the next already set far off) a moment.
398        let until = if c.waiting {
399            Some(if c.next > now() + self.settings.wait_secs.1 { now() + 2 } else { c.next.max(c.release_at) })
400        } else {
401            (now() < c.release_at).then_some(c.release_at)
402        };
403        if until.is_none() {
404            c.held.remove(key);
405        }
406        until
407    }
408
409    fn hold(&self, key: &str, at: u64) -> Response {
410        self.contact.lock().unwrap().held.insert(key.to_string());
411        refilling(at)
412    }
413
414    /// Keep the wallet and passes topped up from the account, in the background, so customers
415    /// never move money by hand. `now`: ask the account at once (the proxy starting, or a
416    /// person's command); else only when the next contact is due, set at random each time
417    /// (`CONTACT_SECS`), so when the account is asked says nothing about any request.
418    pub async fn refill(&self, now_: bool) {
419        {
420            let mut c = self.contact.lock().unwrap();
421            if !now_ && now() < c.next {
422                return;
423            }
424            c.next = now() + random_secs(self.settings.contact_secs);
425        }
426        let Some(key) = self.account_key.lock().unwrap().clone() else {
427            self.contact.lock().unwrap().waiting = false;
428            self.started.store(true, Ordering::SeqCst);
429            return;
430        };
431        let wanted: Vec<String> = self.contact.lock().unwrap().wanted.iter().cloned().collect();
432        let mut wallet = self.wallet.lock().await;
433        let mut failed = false;
434        // One wallet per account: what other devices withdrew, or got back as change from
435        // sessions they closed, comes first, before more is taken from the account.
436        if wallet.balance_cents(Family::Paid) < self.settings.keep_cents && self.client.seed.is_some() {
437            if let Err(e) = self.client.restore(&mut wallet, Some(&key)).await {
438                tracing::warn!("could not look for the account's other vouchers: {e:#}");
439            }
440        }
441        if wallet.balance_cents(Family::Paid) < self.settings.keep_cents {
442            // The account's last cents (under $1) too.
443            match self
444                .client
445                .withdraw_up_to_left(&mut wallet, &key, self.settings.refill_cents, 1)
446                .await
447            {
448                Ok((c, left)) => {
449                    tracing::info!("topped up the wallet with {} from the account", dollars(c));
450                    // Its last cents: a request that runs short doesn't wait for it.
451                    self.contact.lock().unwrap().account_empty = left == Some(0);
452                }
453                Err(e) => {
454                    failed = true;
455                    if matches!(e.downcast_ref::<unlinkable_inference::net::ApiError>(), Some(unlinkable_inference::net::ApiError::Server { status: 402, .. })) {
456                        self.contact.lock().unwrap().account_empty = true;
457                    }
458                    tracing::warn!("could not top up the wallet: {e:#}");
459                }
460            }
461        }
462        match self.stock(&mut wallet, &key, None, !wanted.is_empty()).await {
463            Ok(0) => {}
464            Ok(n) => tracing::info!("got {n} passes for this month"),
465            Err(e) => {
466                failed = true;
467                tracing::warn!("could not get passes: {e:#}");
468            }
469        }
470        if self.client.seed.is_some() {
471            // Let the server forget what is fully spent (at this quiet moment,
472            // not when a session opens).
473            if let Err(e) = self.client.flush_done(&mut wallet, Some(&key)).await {
474                tracing::warn!("could not mark spent records done: {e:#}");
475            }
476        }
477        let _ = wallet.save();
478        let _ = failed;
479        let period = unlinkable_inference::pass::current_period();
480        let mut c = self.contact.lock().unwrap();
481        c.wanted.retain(|label| wallet.passes_of(&period, label) == 0 && wanted.contains(label));
482        if c.waiting {
483            // The request that waited goes on a random while later, not at once.
484            c.release_at = now() + random_secs(self.settings.wait_secs);
485        }
486        c.waiting = false;
487        drop(c);
488        self.started.store(true, Ordering::SeqCst);
489    }
490
491    /// Keep `keep_passes` of each label the account gets (only `only`, when given). The
492    /// account is asked which labels those are at most every 10 minutes, or now with `fresh`.
493    async fn stock(&self, wallet: &mut Wallet, key: &str, only: Option<&str>, fresh: bool) -> Result<usize> {
494        if self.client.keyset.pass_key.is_none() {
495            return Ok(0);
496        }
497        let mut offered = self.offered.lock().await;
498        if fresh || offered.as_ref().is_none_or(|(_, at)| at.elapsed() >= Duration::from_secs(600)) {
499            *offered = Some((self.client.pass_allowance(key).await?, std::time::Instant::now()));
500        }
501        let Some((allowance, _)) = offered.as_mut() else { return Ok(0) };
502        Ok(self.client.stock_passes(wallet, key, allowance, self.settings.keep_passes, 30, only).await)
503    }
504
505    /// The server asked this session for a pass with `label`: present one. With none held,
506    /// what the account was last told decides: a label it has used up for the month means no;
507    /// otherwise (one it gets, or one it may get now, its plan having changed) the account is
508    /// asked at the next contact, never now, which would tie this session to it by timing:
509    /// `Err(when)`, the request waits. `Ok(false)`: none to present.
510    async fn present_pass(&self, entry: &Entry, label: &str) -> std::result::Result<bool, u64> {
511        let mut wallet = self.wallet.lock().await;
512        match self.client.present_pass(&mut wallet, &entry.session, label).await {
513            Ok(true) => return Ok(true),
514            Ok(false) => {}
515            Err(e) => {
516                tracing::warn!("could not present a {label} pass: {e:#}");
517                return Ok(false);
518            }
519        }
520        drop(wallet);
521        // What the account was told at the last contact. A label it wasn't offered: no.
522        let known = self
523            .offered
524            .lock()
525            .await
526            .as_ref()
527            .map(|(a, _)| a.labels.iter().find(|l| l.label == label).map(|l| l.remaining));
528        match known {
529            Some(None) => return Ok(false),
530            Some(Some(left)) if left <= 0 => return Ok(false),
531            _ => {}
532        }
533        {
534            let mut c = self.contact.lock().unwrap();
535            if c.wanted.contains(label) && !c.waiting {
536                // Asked for at the last contact and still none: the account doesn't give it.
537                c.wanted.remove(label);
538                return Ok(false);
539            }
540            c.wanted.insert(label.to_string());
541        }
542        if self.settings.fund_now && self.account_key.lock().unwrap().is_some() {
543            self.refill(true).await;
544            let mut wallet = self.wallet.lock().await;
545            return Ok(self.client.present_pass(&mut wallet, &entry.session, label).await.unwrap_or(false));
546        }
547        match self.wait() {
548            Some(at) => Err(at),
549            None => Ok(false),
550        }
551    }
552
553    fn learn_account_key(&self, headers: &HeaderMap) {
554        let key = client_key(headers);
555        if !self.settings.account_key_prefix.is_empty() && key.starts_with(&self.settings.account_key_prefix) {
556            let mut known = self.account_key.lock().unwrap();
557            if known.is_none() {
558                *known = Some(key);
559                // Learned from a request: the account is first asked a random while later, not
560                // right after it.
561                let mut c = self.contact.lock().unwrap();
562                c.next = c.next.max(now() + random_secs(self.settings.wait_secs));
563            }
564        }
565    }
566
567    /// A session without money, opened with one of the passes the server takes for that.
568    async fn open_free(&self) -> Option<Session> {
569        let label = self.client.free_open_label().await.ok()??;
570        let mut wallet = self.wallet.lock().await;
571        self.client.open_with_pass(&mut wallet, &label).await.ok()?
572    }
573
574    async fn entry(&self, key: &str) -> Result<Arc<Entry>> {
575        if let Some(e) = self.sessions.lock().unwrap().get(key) {
576            return Ok(e.clone());
577        }
578        let _guard = self.opening.lock().await;
579        if let Some(e) = self.sessions.lock().unwrap().get(key) {
580            return Ok(e.clone());
581        }
582        // The proxy is starting: the contact it makes then comes first (up to 30 s).
583        for _ in 0..60 {
584            if self.started.load(Ordering::SeqCst) {
585                break;
586            }
587            tokio::time::sleep(Duration::from_millis(500)).await;
588        }
589        if let Some(at) = self.held_back() {
590            return Err(Refilling(at).into());
591        }
592        let family = self.family_to_spend().await;
593        let mut free = false;
594        let opened = {
595            let mut wallet = self.wallet.lock().await;
596            self.client
597                .open(&mut wallet, family, self.settings.funding_cents)
598                .await
599        };
600        let session = match opened {
601            Ok(s) => s,
602            Err(e) => {
603                // The wallet is empty, or holds less than a session's minimum, and a request
604                // is waiting: top up now (or, without fund_now, wait for the next contact).
605                if self.settings.fund_now && self.account_key.lock().unwrap().is_some() {
606                    self.refill(true).await;
607                    let mut wallet = self.wallet.lock().await;
608                    if let Ok(s) = self.client.open(&mut wallet, family, self.settings.funding_cents).await {
609                        drop(wallet);
610                        return Ok(self.keep_entry(key, s, false));
611                    }
612                } else if let Some(at) = self.wait() {
613                    return Err(Refilling(at).into());
614                }
615                // No money anywhere: what costs none still works.
616                free = true;
617                self.open_free().await.ok_or(e)?
618            }
619        };
620        Ok(self.keep_entry(key, session, free))
621    }
622
623    /// A conversation's newly opened session, kept for its requests.
624    fn keep_entry(&self, key: &str, session: Session, free: bool) -> Arc<Entry> {
625        let entry = Arc::new(Entry {
626            session,
627            free,
628            last_used: AtomicU64::new(now()),
629            busy: AtomicUsize::new(0),
630            opened_at: now(),
631            requests: AtomicU64::new(0),
632        });
633        self.sessions.lock().unwrap().insert(key.to_string(), entry.clone());
634        entry
635    }
636
637    /// The secret of the helper session, opening one if there is none or the
638    /// server has closed it. Agents that send it straight to the server
639    /// (Claude Code's `apiKeyHelper`) ask again after a 401.
640    pub async fn helper_secret(&self) -> Result<String> {
641        let existing = self.sessions.lock().unwrap().get(HELPER).cloned();
642        if let Some(entry) = existing {
643            match self.client.status(&entry.session).await {
644                Ok(st) if st.closed => self.retire_entry(HELPER).await,
645                Err(e) if gone(&e) => self.retire_entry(HELPER).await,
646                // Open, or the server is unreachable: keep it, never drop a
647                // session that may still hold money.
648                _ => return Ok(entry.session.secret.clone()),
649            }
650        }
651        let entry = self.entry(HELPER).await?;
652        // Its requests go straight to the server, so nothing here sees the server ask for a
653        // pass: present one of each label the account gets now.
654        // What the wallet holds (stocked at contacts: asking the account now would tie it to this
655        // session by timing).
656        let mut wallet = self.wallet.lock().await;
657        let period = unlinkable_inference::pass::current_period();
658        let mut labels: Vec<String> = wallet.passes(&period).into_iter().map(|p| p.label).collect();
659        labels.sort();
660        labels.dedup();
661        for label in labels {
662            if let Err(e) = self.client.present_pass(&mut wallet, &entry.session, &label).await {
663                tracing::warn!("could not present a {label} pass for the helper session: {e:#}");
664            }
665        }
666        Ok(entry.session.secret.clone())
667    }
668
669    /// The helper session's requests never pass through here, so watch its
670    /// balance instead: a change means it is in use (not idle), and a low
671    /// balance gets topped up before a request fails for want of money.
672    pub async fn watch_helper(&self) {
673        let Some(entry) = self.sessions.lock().unwrap().get(HELPER).cloned() else {
674            return;
675        };
676        let st = match self.client.status(&entry.session).await {
677            Ok(st) if !st.closed => st,
678            Ok(_) => return self.retire_entry(HELPER).await,
679            Err(e) if gone(&e) => return self.retire_entry(HELPER).await,
680            Err(_) => return,
681        };
682        let changed = {
683            let mut last = self.helper_balance.lock().unwrap();
684            let changed = *last != st.balance_usd;
685            *last = st.balance_usd.clone();
686            changed
687        };
688        if changed {
689            entry.last_used.store(now(), Ordering::SeqCst);
690        }
691        if unlinkable_inference::net::usd_to_cents_floor(&st.balance_usd) < self.settings.funding_cents {
692            let mut wallet = self.wallet.lock().await;
693            if wallet.balance_cents(entry.session.family) < self.settings.funding_cents {
694                drop(wallet);
695                if self.settings.fund_now {
696                    self.refill(true).await;
697                    wallet = self.wallet.lock().await;
698                } else {
699                    // Never from the account now (this session just spent): at the next contact.
700                    let _ = self.wait();
701                    return;
702                }
703            }
704            if let Err(e) = self
705                .client
706                .topup(&mut wallet, &entry.session, self.settings.funding_cents)
707                .await
708            {
709                tracing::warn!("could not top up the helper session: {e:#}");
710            }
711        }
712    }
713
714    /// Stop using a session the server no longer serves and close it, so
715    /// its change comes back (an expired session can still be closed; if
716    /// closing fails it stays in the wallet for `recover`).
717    async fn retire_entry(&self, key: &str) {
718        if let Some(old) = self.drop_entry(key) {
719            self.close_entry(&old).await;
720        }
721    }
722
723    fn drop_entry(&self, key: &str) -> Option<Arc<Entry>> {
724        self.sessions.lock().unwrap().remove(key)
725    }
726
727    async fn close_entry(&self, entry: &Entry) {
728        let mut wallet = self.wallet.lock().await;
729        // Dates what the session cost (the wallet's spending log) by its last request.
730        wallet.used_session(&entry.session.secret, entry.last_used.load(Ordering::SeqCst));
731        match self.client.close(&mut wallet, &entry.session).await {
732            Ok(cents) => tracing::info!("closed a session; {} back in the wallet", dollars(cents)),
733            Err(e) => tracing::warn!("could not close a session (will retry at next start): {e}"),
734        }
735    }
736
737    /// Close every session that has been quiet for `idle_close`.
738    pub async fn close_idle(&self) {
739        let cutoff = now().saturating_sub(self.settings.idle_close.as_secs());
740        let free_cutoff = now().saturating_sub(self.settings.idle_close.as_secs().max(FREE_IDLE_SECS));
741        // A conversation told to wait for the wallet makes no requests: its session isn't idle.
742        let held: std::collections::HashSet<String> = self.contact.lock().unwrap().held.clone();
743        let idle: Vec<(String, Arc<Entry>)> = {
744            let mut sessions = self.sessions.lock().unwrap();
745            let keys: Vec<String> = sessions
746                .iter()
747                .filter(|(k, _)| !held.contains(*k))
748                .filter(|(_, e)| {
749                    let cutoff = if e.free { free_cutoff } else { cutoff };
750                    e.busy.load(Ordering::SeqCst) == 0 && e.last_used.load(Ordering::SeqCst) <= cutoff
751                })
752                .map(|(k, _)| k.clone())
753                .collect();
754            keys.into_iter()
755                .filter_map(|k| sessions.remove(&k).map(|e| (k, e)))
756                .collect()
757        };
758        for (key, entry) in idle {
759            self.threads.lock().unwrap().retain(|_, v| *v != key);
760            self.close_entry(&entry).await;
761        }
762    }
763
764    pub async fn close_all(&self) {
765        let all: Vec<Arc<Entry>> = self.sessions.lock().unwrap().drain().map(|(_, e)| e).collect();
766        self.threads.lock().unwrap().clear();
767        for entry in all {
768            self.close_entry(&entry).await;
769        }
770    }
771
772    async fn send(&self, entry: &Entry, method: &str, path: &str, headers: &[(String, String)], body: &[u8]) -> Result<unlinkable_inference::net::Response> {
773        let mut inner = Inner {
774            method: method.to_string(),
775            path: path.to_string(),
776            headers: headers.to_vec(),
777            body: body.to_vec(),
778        };
779        inner = inner.bearer(&entry.session.secret);
780        self.client.transport.send(inner).await
781    }
782
783    async fn forward(&self, method: &str, path: &str, headers: HeaderMap, body: bytes::Bytes) -> Response {
784        let passed: Vec<(String, String)> = PASSED_HEADERS
785            .iter()
786            .filter_map(|&h| {
787                headers
788                    .get(h)
789                    .and_then(|v| v.to_str().ok())
790                    .map(|v| (h.to_string(), v.to_string()))
791            })
792            .collect();
793
794        // Model lists need no session.
795        if method == "GET" && (path == "/v1/models" || path.starts_with("/v1/models/")) {
796            let req = Inner {
797                method: method.into(),
798                path: path.into(),
799                headers: passed,
800                body: Vec::new(),
801            };
802            return match self.client.transport.send(req).await {
803                Ok(r) => pass_through(r),
804                Err(e) => text(StatusCode::BAD_GATEWAY, &format!("{e:#}")),
805            };
806        }
807
808        self.learn_account_key(&headers);
809        let json_body: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
810        let key = self.session_key(path, &headers, &json_body);
811        let has_thread = json_body["thread"]["rev"].is_string();
812        let body = without_client_ids(body, &json_body);
813
814        let mut reopened = false;
815        let mut topups = 0;
816        let mut rest = false;
817        let mut presented = 0;
818        let mut none: Vec<String> = Vec::new();
819        if let Some(at) = self.still_held(&key) {
820            return refilling(at);
821        }
822        loop {
823            let entry = match self.entry(&key).await {
824                Ok(e) => e,
825                Err(e) => {
826                    if let Some(Refilling(at)) = e.downcast_ref::<Refilling>() {
827                        return self.hold(&key, *at);
828                    }
829                    return text(StatusCode::PAYMENT_REQUIRED, &format!("{e:#}"));
830                }
831            };
832            entry.busy.fetch_add(1, Ordering::SeqCst);
833            let mut sent = passed.clone();
834            if rest {
835                sent.push((unlinkable_inference::protocol::REST_HEADER.to_string(), "1".to_string()));
836            }
837            let result = self.send(&entry, method, path, &sent, &body).await;
838            entry.last_used.store(now(), Ordering::SeqCst);
839            entry.requests.fetch_add(1, Ordering::SeqCst);
840            let response = match result {
841                Ok(r) => r,
842                Err(e) => {
843                    entry.busy.fetch_sub(1, Ordering::SeqCst);
844                    return text(StatusCode::BAD_GATEWAY, &format!("{e:#}"));
845                }
846            };
847            match response.status {
848                402 if topups < 5 => {
849                    if let Some(at) = self.held_back() {
850                        entry.busy.fetch_sub(1, Ordering::SeqCst);
851                        return self.hold(&key, at);
852                    }
853                    // Out of money for this request: add more from the wallet
854                    // (the top-up links only to this session) and try again.
855                    topups += 1;
856                    let cents = self.settings.funding_cents << topups;
857                    let result = {
858                        let mut wallet = self.wallet.lock().await;
859                        self.client.topup(&mut wallet, &entry.session, cents).await
860                    };
861                    entry.busy.fetch_sub(1, Ordering::SeqCst);
862                    let result = match result {
863                        // The wallet is empty (or what it held was spent elsewhere): top it up
864                        // now and try again, as in `entry` (or, without fund_now, wait).
865                        Err(_) if self.settings.fund_now && self.account_key.lock().unwrap().is_some() => {
866                            self.refill(true).await;
867                            let mut wallet = self.wallet.lock().await;
868                            self.client.topup(&mut wallet, &entry.session, cents).await
869                        }
870                        Err(e) => match self.wait() {
871                            Some(at) => return self.hold(&key, at),
872                            None => Err(e),
873                        },
874                        ok => ok,
875                    };
876                    // Nothing more to add: the reply gets what the session's money still buys.
877                    if let Err(e) = result {
878                        if rest {
879                            return text(
880                                StatusCode::PAYMENT_REQUIRED,
881                                &format!("The session ran out and the wallet could not top it up: {e:#}"),
882                            );
883                        }
884                        rest = true;
885                    }
886                    continue;
887                }
888                403 if presented < 8 && response.header(unlinkable_inference::protocol::PASS_REQUIRED_HEADER).is_some() => {
889                    // The server wants a pass for this request: present one (it links only
890                    // to this session) and try again. With none to present, send it once more
891                    // as it was: a server may serve it another way (at another price).
892                    let label = response.header(unlinkable_inference::protocol::PASS_REQUIRED_HEADER).unwrap_or_default().to_string();
893                    match self.present_pass(&entry, &label).await {
894                        Ok(true) => {
895                            presented += 1;
896                            entry.busy.fetch_sub(1, Ordering::SeqCst);
897                            continue;
898                        }
899                        Ok(false) => {}
900                        Err(at) => {
901                            entry.busy.fetch_sub(1, Ordering::SeqCst);
902                            return self.hold(&key, at);
903                        }
904                    }
905                    if !none.contains(&label) {
906                        none.push(label);
907                        entry.busy.fetch_sub(1, Ordering::SeqCst);
908                        continue;
909                    }
910                }
911                401 if !reopened && !has_thread => {
912                    // The session expired: close it for its change, start a new one.
913                    entry.busy.fetch_sub(1, Ordering::SeqCst);
914                    reopened = true;
915                    self.retire_entry(&key).await;
916                    continue;
917                }
918                _ => {}
919            }
920            if let Some(rev) = response.header("x-obscurify-thread") {
921                self.threads
922                    .lock()
923                    .unwrap()
924                    .insert(rev.to_string(), key.clone());
925            }
926            let out = pass_through_tracked(response, entry.clone());
927            return out;
928        }
929    }
930
931    async fn status_json(&self) -> Value {
932        let mut wallet = self.wallet.lock().await;
933        let period = unlinkable_inference::pass::current_period();
934        let passes = wallet.passes(&period);
935        let mut pass_labels = std::collections::BTreeMap::<String, usize>::new();
936        for p in &passes {
937            *pass_labels.entry(p.label.clone()).or_default() += 1;
938        }
939        let sessions: Vec<Value> = self
940            .sessions
941            .lock()
942            .unwrap()
943            .values()
944            .map(|e| {
945                json!({
946                    "family": e.session.family,
947                    "age_seconds": now() - e.opened_at,
948                    "idle_seconds": now() - e.last_used.load(Ordering::SeqCst),
949                    "requests": e.requests.load(Ordering::SeqCst),
950                })
951            })
952            .collect();
953        let traffic: Vec<Value> = self
954            .traffic
955            .lock()
956            .unwrap()
957            .iter()
958            .take(40)
959            .map(|(at, o)| {
960                json!({"at": at, "bytes_sent": o.bytes_sent, "server_sees": o.server_sees})
961            })
962            .collect();
963        json!({
964            "server": self.opts.server,
965            "keyset": self.client.keyset.fingerprint(),
966            "wallet": {
967                "paid_cents": wallet.balance_cents(Family::Paid),
968                "promo_cents": wallet.balance_cents(Family::Promo),
969                "vouchers": wallet.vouchers().len(),
970                "passes": passes.len(),
971                "pass_labels": pass_labels,
972            },
973            "settings": {
974                "session_funding_cents": self.settings.funding_cents,
975                "idle_close_seconds": self.settings.idle_close.as_secs(),
976            },
977            "sessions": sessions,
978            "traffic": traffic,
979        })
980    }
981
982    /// What private use cost, oldest first: closed sessions from the wallet's
983    /// log plus what open ones have used so far (each asked with its own secret).
984    async fn spending_json(&self) -> Value {
985        let (mut spent, open, mut prepaid) = {
986            let wallet = self.wallet.lock().await;
987            (wallet.spending().to_vec(), wallet.sessions().to_vec(), wallet.balance_millicents(Family::Paid))
988        };
989        for o in open.into_iter().filter(|o| o.funded_millicents > 0) {
990            let session = unlinkable_inference::net::Session { secret: o.secret.clone(), family: o.family };
991            if let Ok(status) = self.client.status(&session).await {
992                let left = unlinkable_inference::net::usd_to_millicents_ceil(&status.balance_usd);
993                prepaid += left;
994                if o.funded_millicents > left {
995                    spent.push(unlinkable_inference::Spend { at: o.used_at.max(o.opened_at), millicents: o.funded_millicents - left });
996                }
997            }
998        }
999        json!({ "spent": spent, "prepaid_millicents": prepaid })
1000    }
1001
1002    async fn withdraw(&self, api_key: &str, cents: i64) -> Result<i64> {
1003        let mut wallet = self.wallet.lock().await;
1004        self.client.withdraw(&mut wallet, api_key, cents).await
1005    }
1006
1007    /// Get up to `count` passes of each label the account gets.
1008    async fn passes(&self, api_key: &str, count: i64) -> Result<usize> {
1009        let mut wallet = self.wallet.lock().await;
1010        let allowance = self.client.pass_allowance(api_key).await?;
1011        let mut got = 0;
1012        for l in &allowance.labels {
1013            got += self.client.get_passes(&mut wallet, api_key, &l.label, &allowance.period, count.min(l.remaining)).await?;
1014        }
1015        Ok(got)
1016    }
1017
1018    async fn import(&self, codes: &[String]) -> Result<i64> {
1019        let mut added = 0;
1020        let mut wallet = self.wallet.lock().await;
1021        for code in codes {
1022            let voucher = Voucher::parse(code).ok_or_else(|| anyhow!("not a voucher: {code}"))?;
1023            let family = unlinkable_inference::blank::verify(&self.client.keyset, &voucher)
1024                .ok_or_else(|| anyhow!("this server did not sign {code}"))?;
1025            added += voucher.denomination_cents;
1026            wallet.add(family, [voucher]);
1027        }
1028        wallet.save()?;
1029        Ok(added)
1030    }
1031}
1032
1033fn copy_headers(resp: &unlinkable_inference::net::Response, out: &mut HeaderMap) {
1034    for (k, v) in &resp.headers {
1035        let k = k.to_ascii_lowercase();
1036        if DROPPED_RESPONSE_HEADERS.contains(&k.as_str()) {
1037            continue;
1038        }
1039        if let (Ok(name), Ok(value)) = (
1040            axum::http::HeaderName::from_bytes(k.as_bytes()),
1041            HeaderValue::from_str(v),
1042        ) {
1043            out.insert(name, value);
1044        }
1045    }
1046}
1047
1048fn pass_through(resp: unlinkable_inference::net::Response) -> Response {
1049    let mut headers = HeaderMap::new();
1050    copy_headers(&resp, &mut headers);
1051    let status = StatusCode::from_u16(resp.status).unwrap_or(StatusCode::BAD_GATEWAY);
1052    let body = Body::from_stream(resp.body.map(|r| r.map_err(std::io::Error::other)));
1053    (status, headers, body).into_response()
1054}
1055
1056/// Like [`pass_through`], keeping the session marked busy until the
1057/// stream ends, so it is never closed mid-answer.
1058fn pass_through_tracked(resp: unlinkable_inference::net::Response, entry: Arc<Entry>) -> Response {
1059    let mut headers = HeaderMap::new();
1060    copy_headers(&resp, &mut headers);
1061    let status = StatusCode::from_u16(resp.status).unwrap_or(StatusCode::BAD_GATEWAY);
1062    struct Done(Arc<Entry>);
1063    impl Drop for Done {
1064        fn drop(&mut self) {
1065            self.0.last_used.store(now(), Ordering::SeqCst);
1066            self.0.busy.fetch_sub(1, Ordering::SeqCst);
1067        }
1068    }
1069    let done = Done(entry);
1070    let body = resp.body.map(move |r| {
1071        let _keep = &done;
1072        r.map_err(std::io::Error::other)
1073    });
1074    (status, headers, Body::from_stream(body)).into_response()
1075}
1076
1077/// Only local clients, and never a web page: a site you visit must not be
1078/// able to spend your wallet through this proxy.
1079fn local_only(headers: &HeaderMap) -> Option<Response> {
1080    let host = headers
1081        .get("host")
1082        .and_then(|v| v.to_str().ok())
1083        .unwrap_or("");
1084    let host_name = host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host);
1085    if !matches!(host_name, "127.0.0.1" | "localhost" | "[::1]" | "") {
1086        return Some(text(StatusCode::FORBIDDEN, "local clients only"));
1087    }
1088    if let Some(origin) = headers.get("origin").and_then(|v| v.to_str().ok()) {
1089        let ok = ["http://127.0.0.1", "http://localhost", "http://[::1]"]
1090            .iter()
1091            .any(|p| origin.starts_with(p));
1092        if !ok {
1093            return Some(text(StatusCode::FORBIDDEN, "web pages cannot use this proxy"));
1094        }
1095    }
1096    None
1097}
1098
1099async fn handle(State(proxy): State<Arc<Proxy>>, req: Request) -> Response {
1100    let (parts, body) = req.into_parts();
1101    if let Some(refusal) = local_only(&parts.headers) {
1102        return refusal;
1103    }
1104    let path = parts
1105        .uri
1106        .path_and_query()
1107        .map(|p| p.as_str().to_string())
1108        .unwrap_or_else(|| "/".into());
1109    let method = parts.method.as_str().to_string();
1110    let Ok(body) = axum::body::to_bytes(body, MAX_BODY).await else {
1111        return text(StatusCode::PAYLOAD_TOO_LARGE, "request too large");
1112    };
1113
1114    if path.starts_with("/_unlinkable") {
1115        return control(&proxy, &method, &path, &parts.headers, &body).await;
1116    }
1117    if method == "POST" {
1118        let json = parts
1119            .headers
1120            .get("content-type")
1121            .and_then(|v| v.to_str().ok())
1122            .is_some_and(|v| v.starts_with("application/json"));
1123        if !json {
1124            return text(StatusCode::UNSUPPORTED_MEDIA_TYPE, "send application/json");
1125        }
1126    }
1127    // Clients configured with a base URL without /v1 (some Anthropic
1128    // setups) still reach the API.
1129    let path = if path.starts_with("/v1/") {
1130        path
1131    } else {
1132        format!("/v1{path}")
1133    };
1134    // Only API calls go out (and only they open sessions): a browser's
1135    // favicon request or a typo must not spend the wallet.
1136    let route = path.split('?').next().unwrap_or("");
1137    let api = match method.as_str() {
1138        "GET" => route == "/v1/models" || route.starts_with("/v1/models/"),
1139        "POST" => FORWARDED_POSTS.iter().any(|p| route == *p || route.starts_with(&format!("{p}/"))),
1140        _ => false,
1141    };
1142    if !api {
1143        return text(StatusCode::NOT_FOUND, "not an API path this proxy forwards");
1144    }
1145    proxy.forward(&method, &path, parts.headers, body).await
1146}
1147
1148async fn control(proxy: &Proxy, method: &str, path: &str, headers: &HeaderMap, body: &[u8]) -> Response {
1149    if method == "POST" {
1150        let json = headers
1151            .get("content-type")
1152            .and_then(|v| v.to_str().ok())
1153            .is_some_and(|v| v.starts_with("application/json"));
1154        if !json {
1155            return text(StatusCode::UNSUPPORTED_MEDIA_TYPE, "send application/json");
1156        }
1157    }
1158    let body: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
1159    match (method, path) {
1160        ("GET", "/_unlinkable") | ("GET", "/_unlinkable/") => Html(PAGE).into_response(),
1161        ("GET", "/_unlinkable/status") => Json(proxy.status_json().await).into_response(),
1162        ("GET", "/_unlinkable/spending") => Json(proxy.spending_json().await).into_response(),
1163        ("GET", "/_unlinkable/key") => match proxy.helper_secret().await {
1164            Ok(secret) => secret.into_response(),
1165            Err(e) => text(StatusCode::PAYMENT_REQUIRED, &format!("{e:#}")),
1166        },
1167        ("POST", "/_unlinkable/withdraw") => {
1168            let cents = body["amount_cents"].as_i64().unwrap_or(0);
1169            let key = body["api_key"].as_str().unwrap_or("");
1170            match proxy.withdraw(key, cents).await {
1171                Ok(c) => Json(json!({"withdrawn_cents": c})).into_response(),
1172                Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
1173            }
1174        }
1175        ("POST", "/_unlinkable/passes") => {
1176            let count = body["count"].as_i64().unwrap_or(30);
1177            let key = body["api_key"].as_str().unwrap_or("");
1178            match proxy.passes(key, count).await {
1179                Ok(n) => Json(json!({"got": n})).into_response(),
1180                Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
1181            }
1182        }
1183        ("POST", "/_unlinkable/import") => {
1184            let codes: Vec<String> = body["vouchers"]
1185                .as_array()
1186                .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
1187                .unwrap_or_default();
1188            match proxy.import(&codes).await {
1189                Ok(c) => Json(json!({"added_cents": c})).into_response(),
1190                Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
1191            }
1192        }
1193        ("POST", "/_unlinkable/close") => {
1194            proxy.close_all().await;
1195            Json(json!({"closed": true})).into_response()
1196        }
1197        _ => text(StatusCode::NOT_FOUND, "no such control endpoint"),
1198    }
1199}
1200
1201pub fn router(proxy: Arc<Proxy>) -> Router {
1202    Router::new().fallback(handle).with_state(proxy)
1203}
1204
1205/// Serve until `shutdown` resolves, closing idle sessions as it goes and
1206/// every session at the end.
1207pub async fn run(
1208    listener: tokio::net::TcpListener,
1209    proxy: Arc<Proxy>,
1210    shutdown: impl std::future::Future<Output = ()> + Send + 'static,
1211) -> Result<()> {
1212    let closer = proxy.clone();
1213    let ticker = tokio::spawn(async move {
1214        let mut tick = tokio::time::interval(Duration::from_secs(5));
1215        loop {
1216            tick.tick().await;
1217            closer.watch_helper().await;
1218            closer.close_idle().await;
1219            // Asks the account only when the next contact (random) is due.
1220            closer.refill(false).await;
1221        }
1222    });
1223    axum::serve(listener, router(proxy.clone()))
1224        .with_graceful_shutdown(shutdown)
1225        .await?;
1226    ticker.abort();
1227    proxy.close_all().await;
1228    Ok(())
1229}
1230
1231const PAGE: &str = r#"<!doctype html>
1232<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
1233<title>unlinkable-inference: what leaves this device</title>
1234<style>
1235body{font:15px/1.45 system-ui,sans-serif;background:#111;color:#ddd;margin:0;padding:1rem 1rem 6rem}
1236h1{font-size:1.2rem;margin:.2rem 0 1rem}h2{font-size:1rem;margin:1.5rem 0 .5rem;color:#aaa}
1237.card{background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;padding:.8rem;margin:.5rem 0}
1238code{color:#9cf}.peer{color:#fc9}.server{color:#9f9}.warn{color:#f99}
1239table{border-collapse:collapse;width:100%}td{padding:.35rem .4rem;border-top:1px solid #2a2a2a;vertical-align:top}
1240.dock{position:fixed;right:1rem;bottom:1rem;display:flex;gap:.5rem;flex-wrap:wrap;justify-content:flex-end}
1241button,input{font:inherit;border-radius:6px;border:1px solid #444;background:#222;color:#eee;padding:.5rem .8rem}
1242button{background:#2d4f7c;border-color:#3d6aa5}
1243</style></head><body>
1244<h1>What leaves this device</h1>
1245<div id="summary" class="card">Loading…</div>
1246<h2>Spent</h2><div id="spent" class="card">Loading…</div>
1247<h2>Open sessions</h2><div id="sessions" class="card"></div>
1248<h2>Last requests</h2><div class="card"><table id="traffic"></table></div>
1249<div class="dock">
1250<input id="key" placeholder="account API key" size="18">
1251<select id="amt"><option value="100">$1</option><option value="500" selected>$5</option><option value="2000">$20</option><option value="5000">$50</option><option value="10000">$100</option></select>
1252<button onclick="passes()">Get passes</button>
1253<button onclick="withdraw()">Withdraw into wallet</button>
1254</div>
1255<script>
1256const $=id=>document.getElementById(id);
1257const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
1258const usd=c=>'$'+(c/100).toFixed(2);
1259async function load(){
1260 const s=await (await fetch('/_unlinkable/status')).json();
1261 $('summary').innerHTML=`Server <code>${esc(s.server)}</code><br>`+
1262  `The server sees your IP address unless Tor or a VPN hides it. It never sees your account or how you paid.`+
1263  `<br>Keyset <code>${esc(s.keyset)}</code><br>Wallet ${usd(s.wallet.paid_cents)} paid, ${usd(s.wallet.promo_cents)} promo, in ${s.wallet.vouchers} vouchers`+
1264  `<br>Passes this month: ${s.wallet.passes}${s.wallet.passes?' ('+Object.entries(s.wallet.pass_labels).map(([l,n])=>esc(l)+' '+n).join(', ')+')':''}. A conversation presents one when the server asks for it.`;
1265 $('sessions').innerHTML=s.sessions.length?s.sessions.map(x=>`${x.requests} request${x.requests==1?'':'s'}, open ${x.age_seconds}s, idle ${x.idle_seconds}s`).join('<br>'):'None. Sessions close after '+s.settings.idle_close_seconds+'s without a request; change goes back to the wallet.';
1266 $('traffic').innerHTML=s.traffic.map(t=>`<tr><td>${new Date(t.at*1000).toLocaleTimeString()}</td><td><span class="server">server sees</span> ${esc(t.server_sees)}</td></tr>`).join('')||'<tr><td>Nothing sent yet.</td></tr>';
1267}
1268async function spent(){
1269 const list=(await (await fetch('/_unlinkable/spending')).json()).spent;
1270 const day=t=>new Date(t*1000).toLocaleDateString(undefined,{weekday:'short',month:'short',day:'numeric'});
1271 const m=x=>'$'+(x/100000).toFixed(x&&x<1000?4:2);
1272 const now=new Date(), today=day(now/1000), month=now.getFullYear()*12+now.getMonth();
1273 const days=new Map(); let t=0,mo=0;
1274 for(const e of list){const d=new Date(e.at*1000); if(day(e.at)===today)t+=e.millicents; if(d.getFullYear()*12+d.getMonth()===month)mo+=e.millicents; days.set(day(e.at),(days.get(day(e.at))||0)+e.millicents);}
1275 $('spent').innerHTML=`Today ${m(t)} · this month ${m(mo)}`+([...days].reverse().slice(0,30).map(([d,v])=>`<br><span style="color:#888">${d}</span> ${m(v)}`).join(''))+
1276  '<br><span style="color:#888">Kept on this device only: the server cannot tie these sessions to your account.</span>';
1277}
1278async function withdraw(){
1279 const r=await fetch('/_unlinkable/withdraw',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({api_key:$('key').value.trim(),amount_cents:+$('amt').value})});
1280 const j=await r.json(); alert(r.ok?'Added '+usd(j.withdrawn_cents)+' to the wallet':j.error.message); $('key').value=''; load();
1281}
1282async function passes(){
1283 const r=await fetch('/_unlinkable/passes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({api_key:$('key').value.trim(),count:30})});
1284 const j=await r.json(); alert(r.ok?'Got '+j.got+' passes':j.error.message); $('key').value=''; load();
1285}
1286load(); setInterval(load,4000); spent(); setInterval(spent,30000);
1287</script></body></html>"#;