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    /// Client keys starting with this are taken to be the account's key
69    pub account_key_prefix: String,
70}
71
72impl Default for Settings {
73    fn default() -> Self {
74        Self {
75            funding_cents: 50,
76            mode: Mode::Conversation,
77            idle_close: Duration::from_secs(300),
78            show_traffic: false,
79            account_key: None,
80            keep_cents: 50,
81            refill_cents: 100,
82            keep_passes: 10,
83            account_key_prefix: "sk-obs1_".into(),
84        }
85    }
86}
87
88struct Entry {
89    session: Session,
90    last_used: AtomicU64,
91    busy: AtomicUsize,
92    opened_at: u64,
93    requests: AtomicU64,
94}
95
96pub struct Proxy {
97    client: Client,
98    wallet: tokio::sync::Mutex<Wallet>,
99    sessions: Mutex<HashMap<String, Arc<Entry>>>,
100    /// Held-conversation revs (x-obscurify-thread) to the session that owns them
101    threads: Mutex<HashMap<String, String>>,
102    traffic: Arc<Mutex<VecDeque<(u64, Observed)>>>,
103    opening: tokio::sync::Mutex<()>,
104    settings: Settings,
105    opts: Options,
106    account_key: Mutex<Option<String>>,
107    /// After a failed top-up, wait before trying again
108    refill_backoff: Mutex<Option<std::time::Instant>>,
109    /// The helper session's last seen balance (see [`Proxy::helper_secret`])
110    helper_balance: Mutex<String>,
111}
112
113/// The session handed out by `/_unlinkable/key` for agents that talk to the
114/// server directly (Claude Code's `apiKeyHelper`).
115const HELPER: &str = "helper";
116
117/// The server no longer knows this session (expired or closed elsewhere).
118fn gone(e: &anyhow::Error) -> bool {
119    matches!(
120        e.downcast_ref::<unlinkable_inference::net::ApiError>(),
121        Some(unlinkable_inference::net::ApiError::Server { status: 401 | 404 | 410, .. })
122    )
123}
124
125fn now() -> u64 {
126    SystemTime::now()
127        .duration_since(UNIX_EPOCH)
128        .map(|d| d.as_secs())
129        .unwrap_or(0)
130}
131
132/// Request headers passed on. Everything else (user agents, SDK telemetry,
133/// the client's own key) stays on this machine.
134const PASSED_HEADERS: &[&str] = &[
135    "content-type",
136    "accept",
137    "anthropic-version",
138    "anthropic-beta",
139    "openai-beta",
140];
141
142const DROPPED_RESPONSE_HEADERS: &[&str] = &[
143    "content-length",
144    "transfer-encoding",
145    "connection",
146    "set-cookie",
147];
148
149const MAX_BODY: usize = 32 * 1024 * 1024;
150
151/// POST endpoints (and anything under them) forwarded to the server.
152const FORWARDED_POSTS: &[&str] = &[
153    "/v1/chat/completions",
154    "/v1/completions",
155    "/v1/responses",
156    "/v1/messages",
157    "/v1/embeddings",
158    "/v1/images",
159    "/v1/tools",
160];
161
162fn text(status: StatusCode, message: &str) -> Response {
163    (
164        status,
165        Json(json!({"error": {"message": message, "type": "unlinkable_inference_cli_error"}})),
166    )
167        .into_response()
168}
169
170/// The part of a request that stays the same for a whole conversation.
171pub fn conversation_fingerprint(path: &str, body: &Value) -> String {
172    let parts = if path.ends_with("/chat/completions") {
173        let messages = body["messages"].as_array().cloned().unwrap_or_default();
174        let end = messages
175            .iter()
176            .position(|m| m["role"] == "user")
177            .map(|i| i + 1)
178            .unwrap_or(messages.len());
179        json!(messages[..end])
180    } else if path.ends_with("/messages") {
181        json!([body["system"], body["messages"][0]])
182    } else if path.ends_with("/responses") {
183        let first = match &body["input"] {
184            Value::Array(items) => items.first().cloned().unwrap_or(Value::Null),
185            other => other.clone(),
186        };
187        json!([body["instructions"], first])
188    } else {
189        Value::Null
190    };
191    unlinkable_inference::sha256_hex(parts.to_string())[..16].to_string()
192}
193
194fn client_key(headers: &HeaderMap) -> String {
195    headers
196        .get("authorization")
197        .and_then(|v| v.to_str().ok())
198        .map(|v| v.trim_start_matches("Bearer ").trim().to_string())
199        .or_else(|| {
200            headers
201                .get("x-api-key")
202                .and_then(|v| v.to_str().ok())
203                .map(str::to_string)
204        })
205        .unwrap_or_default()
206}
207
208impl Proxy {
209    pub fn new(mut client: Client, wallet: Wallet, settings: Settings, opts: Options) -> Arc<Self> {
210        let traffic: Arc<Mutex<VecDeque<(u64, Observed)>>> = Arc::new(Mutex::new(VecDeque::new()));
211        let log = traffic.clone();
212        let show = settings.show_traffic;
213        client.transport = client.transport.clone().observe(Arc::new(move |o: &Observed| {
214            if show {
215                eprintln!("→ {}: {}", o.server, o.server_sees);
216            }
217            let mut log = log.lock().unwrap();
218            log.push_front((now(), o.clone()));
219            log.truncate(100);
220        }));
221        Arc::new(Self {
222            client,
223            wallet: tokio::sync::Mutex::new(wallet),
224            sessions: Mutex::new(HashMap::new()),
225            threads: Mutex::new(HashMap::new()),
226            traffic,
227            opening: tokio::sync::Mutex::new(()),
228            account_key: Mutex::new(settings.account_key.clone()),
229            refill_backoff: Mutex::new(None),
230            helper_balance: Mutex::new(String::new()),
231            settings,
232            opts,
233        })
234    }
235
236    fn session_key(&self, path: &str, headers: &HeaderMap, body: &Value) -> String {
237        if let Some(rev) = body["thread"]["rev"].as_str() {
238            if let Some(key) = self.threads.lock().unwrap().get(rev) {
239                return key.clone();
240            }
241        }
242        match self.settings.mode {
243            Mode::Run => "run".to_string(),
244            Mode::Key => format!("key:{}", client_key(headers)),
245            Mode::Conversation => format!(
246                "conv:{}:{}",
247                client_key(headers),
248                conversation_fingerprint(path, body)
249            ),
250        }
251    }
252
253    async fn family_to_spend(&self) -> Family {
254        let wallet = self.wallet.lock().await;
255        if wallet.balance_cents(Family::Paid) == 0 && wallet.balance_cents(Family::Promo) > 0 {
256            Family::Promo
257        } else {
258            Family::Paid
259        }
260    }
261
262    /// Keep the wallet and passes topped up from the account, in the
263    /// background, so customers never move money by hand. Withdrawals happen
264    /// when the wallet runs low, not when a session opens, so their timing
265    /// says little about any one conversation. `urgent` skips the backoff
266    /// (the wallet is empty and a request is waiting).
267    pub async fn refill(&self, urgent: bool) {
268        let Some(key) = self.account_key.lock().unwrap().clone() else {
269            return;
270        };
271        if !urgent {
272            if let Some(at) = *self.refill_backoff.lock().unwrap() {
273                if at.elapsed() < Duration::from_secs(600) {
274                    return;
275                }
276            }
277        }
278        let mut wallet = self.wallet.lock().await;
279        let mut failed = false;
280        // One wallet per account: what other devices withdrew, or got back as change from
281        // sessions they closed, comes first, before more is taken from the account.
282        if wallet.balance_cents(Family::Paid) < self.settings.keep_cents && self.client.seed.is_some() {
283            if let Err(e) = self.client.restore(&mut wallet, Some(&key)).await {
284                tracing::warn!("could not look for the account's other vouchers: {e:#}");
285            }
286        }
287        if wallet.balance_cents(Family::Paid) < self.settings.keep_cents {
288            // The account's last cents (under $1) too, down to a session's 10¢.
289            match self
290                .client
291                .withdraw_up_to(&mut wallet, &key, self.settings.refill_cents, 10)
292                .await
293            {
294                Ok(c) => tracing::info!("topped up the wallet with {} from the account", dollars(c)),
295                Err(e) => {
296                    failed = true;
297                    tracing::warn!("could not top up the wallet: {e:#}");
298                }
299            }
300        }
301        if self.client.keyset.pass_key.is_some() {
302            let period = unlinkable_inference::pass::current_period();
303            let held = wallet.passes(&period).len();
304            if held < self.settings.keep_passes {
305                match self.client.get_passes(&mut wallet, &key, 30).await {
306                    Ok(0) => {}
307                    Ok(n) => tracing::info!("got {n} passes for this month"),
308                    Err(e) => {
309                        failed = true;
310                        tracing::warn!("could not get passes: {e:#}");
311                    }
312                }
313            }
314        }
315        if self.client.seed.is_some() {
316            // Let the server forget what is fully spent (at this quiet moment,
317            // not when a session opens).
318            if let Err(e) = self.client.flush_done(&mut wallet, Some(&key)).await {
319                tracing::warn!("could not mark spent records done: {e:#}");
320            }
321        }
322        let _ = wallet.save();
323        *self.refill_backoff.lock().unwrap() = failed.then(std::time::Instant::now);
324    }
325
326    fn learn_account_key(&self, headers: &HeaderMap) {
327        let key = client_key(headers);
328        if !self.settings.account_key_prefix.is_empty() && key.starts_with(&self.settings.account_key_prefix) {
329            let mut known = self.account_key.lock().unwrap();
330            if known.is_none() {
331                *known = Some(key);
332            }
333        }
334    }
335
336    async fn entry(&self, key: &str) -> Result<Arc<Entry>> {
337        if let Some(e) = self.sessions.lock().unwrap().get(key) {
338            return Ok(e.clone());
339        }
340        let _guard = self.opening.lock().await;
341        if let Some(e) = self.sessions.lock().unwrap().get(key) {
342            return Ok(e.clone());
343        }
344        let family = self.family_to_spend().await;
345        let opened = {
346            let mut wallet = self.wallet.lock().await;
347            self.client
348                .open(&mut wallet, family, self.settings.funding_cents)
349                .await
350        };
351        let session = match opened {
352            Ok(s) => s,
353            Err(e) if e.to_string().contains("has no") => {
354                // Empty wallet and a request waiting: top up now rather
355                // than fail (the background refill should prevent this).
356                self.refill(true).await;
357                let mut wallet = self.wallet.lock().await;
358                self.client
359                    .open(&mut wallet, family, self.settings.funding_cents)
360                    .await?
361            }
362            Err(e) => return Err(e),
363        };
364        let entry = Arc::new(Entry {
365            session,
366            last_used: AtomicU64::new(now()),
367            busy: AtomicUsize::new(0),
368            opened_at: now(),
369            requests: AtomicU64::new(0),
370        });
371        self.sessions
372            .lock()
373            .unwrap()
374            .insert(key.to_string(), entry.clone());
375        Ok(entry)
376    }
377
378    /// The secret of the helper session, opening one if there is none or the
379    /// server has closed it. Agents that send it straight to the server
380    /// (Claude Code's `apiKeyHelper`) ask again after a 401.
381    pub async fn helper_secret(&self) -> Result<String> {
382        let existing = self.sessions.lock().unwrap().get(HELPER).cloned();
383        if let Some(entry) = existing {
384            match self.client.status(&entry.session).await {
385                Ok(st) if st.closed => self.retire_entry(HELPER).await,
386                Err(e) if gone(&e) => self.retire_entry(HELPER).await,
387                // Open, or the server is unreachable: keep it, never drop a
388                // session that may still hold money.
389                _ => return Ok(entry.session.secret.clone()),
390            }
391        }
392        Ok(self.entry(HELPER).await?.session.secret.clone())
393    }
394
395    /// The helper session's requests never pass through here, so watch its
396    /// balance instead: a change means it is in use (not idle), and a low
397    /// balance gets topped up before a request fails for want of money.
398    pub async fn watch_helper(&self) {
399        let Some(entry) = self.sessions.lock().unwrap().get(HELPER).cloned() else {
400            return;
401        };
402        let st = match self.client.status(&entry.session).await {
403            Ok(st) if !st.closed => st,
404            Ok(_) => return self.retire_entry(HELPER).await,
405            Err(e) if gone(&e) => return self.retire_entry(HELPER).await,
406            Err(_) => return,
407        };
408        let changed = {
409            let mut last = self.helper_balance.lock().unwrap();
410            let changed = *last != st.balance_usd;
411            *last = st.balance_usd.clone();
412            changed
413        };
414        if changed {
415            entry.last_used.store(now(), Ordering::SeqCst);
416        }
417        if unlinkable_inference::net::usd_to_cents_floor(&st.balance_usd) < self.settings.funding_cents {
418            let mut wallet = self.wallet.lock().await;
419            if wallet.balance_cents(entry.session.family) < self.settings.funding_cents {
420                drop(wallet);
421                self.refill(true).await;
422                wallet = self.wallet.lock().await;
423            }
424            if let Err(e) = self
425                .client
426                .topup(&mut wallet, &entry.session, self.settings.funding_cents)
427                .await
428            {
429                tracing::warn!("could not top up the helper session: {e:#}");
430            }
431        }
432    }
433
434    /// Stop using a session the server no longer serves and close it, so
435    /// its change comes back (an expired session can still be closed; if
436    /// closing fails it stays in the wallet for `recover`).
437    async fn retire_entry(&self, key: &str) {
438        if let Some(old) = self.drop_entry(key) {
439            self.close_entry(&old).await;
440        }
441    }
442
443    fn drop_entry(&self, key: &str) -> Option<Arc<Entry>> {
444        self.sessions.lock().unwrap().remove(key)
445    }
446
447    async fn close_entry(&self, entry: &Entry) {
448        let mut wallet = self.wallet.lock().await;
449        // Dates what the session cost (the wallet's spending log) by its last request.
450        wallet.used_session(&entry.session.secret, entry.last_used.load(Ordering::SeqCst));
451        match self.client.close(&mut wallet, &entry.session).await {
452            Ok(cents) => tracing::info!("closed a session; {} back in the wallet", dollars(cents)),
453            Err(e) => tracing::warn!("could not close a session (will retry at next start): {e}"),
454        }
455    }
456
457    /// Close every session that has been quiet for `idle_close`.
458    pub async fn close_idle(&self) {
459        let cutoff = now().saturating_sub(self.settings.idle_close.as_secs());
460        let idle: Vec<(String, Arc<Entry>)> = {
461            let mut sessions = self.sessions.lock().unwrap();
462            let keys: Vec<String> = sessions
463                .iter()
464                .filter(|(_, e)| {
465                    e.busy.load(Ordering::SeqCst) == 0 && e.last_used.load(Ordering::SeqCst) <= cutoff
466                })
467                .map(|(k, _)| k.clone())
468                .collect();
469            keys.into_iter()
470                .filter_map(|k| sessions.remove(&k).map(|e| (k, e)))
471                .collect()
472        };
473        for (key, entry) in idle {
474            self.threads.lock().unwrap().retain(|_, v| *v != key);
475            self.close_entry(&entry).await;
476        }
477    }
478
479    pub async fn close_all(&self) {
480        let all: Vec<Arc<Entry>> = self.sessions.lock().unwrap().drain().map(|(_, e)| e).collect();
481        self.threads.lock().unwrap().clear();
482        for entry in all {
483            self.close_entry(&entry).await;
484        }
485    }
486
487    async fn send(&self, entry: &Entry, method: &str, path: &str, headers: &[(String, String)], body: &[u8]) -> Result<unlinkable_inference::net::Response> {
488        let mut inner = Inner {
489            method: method.to_string(),
490            path: path.to_string(),
491            headers: headers.to_vec(),
492            body: body.to_vec(),
493        };
494        inner = inner.bearer(&entry.session.secret);
495        self.client.transport.send(inner).await
496    }
497
498    async fn forward(&self, method: &str, path: &str, headers: HeaderMap, body: bytes::Bytes) -> Response {
499        let passed: Vec<(String, String)> = PASSED_HEADERS
500            .iter()
501            .filter_map(|&h| {
502                headers
503                    .get(h)
504                    .and_then(|v| v.to_str().ok())
505                    .map(|v| (h.to_string(), v.to_string()))
506            })
507            .collect();
508
509        // Model lists need no session.
510        if method == "GET" && (path == "/v1/models" || path.starts_with("/v1/models/")) {
511            let req = Inner {
512                method: method.into(),
513                path: path.into(),
514                headers: passed,
515                body: Vec::new(),
516            };
517            return match self.client.transport.send(req).await {
518                Ok(r) => pass_through(r),
519                Err(e) => text(StatusCode::BAD_GATEWAY, &format!("{e:#}")),
520            };
521        }
522
523        self.learn_account_key(&headers);
524        let json_body: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
525        let key = self.session_key(path, &headers, &json_body);
526        let has_thread = json_body["thread"]["rev"].is_string();
527
528        let mut reopened = false;
529        let mut topups = 0;
530        loop {
531            let entry = match self.entry(&key).await {
532                Ok(e) => e,
533                Err(e) => return text(StatusCode::PAYMENT_REQUIRED, &format!("{e:#}")),
534            };
535            entry.busy.fetch_add(1, Ordering::SeqCst);
536            let result = self.send(&entry, method, path, &passed, &body).await;
537            entry.last_used.store(now(), Ordering::SeqCst);
538            entry.requests.fetch_add(1, Ordering::SeqCst);
539            let response = match result {
540                Ok(r) => r,
541                Err(e) => {
542                    entry.busy.fetch_sub(1, Ordering::SeqCst);
543                    return text(StatusCode::BAD_GATEWAY, &format!("{e:#}"));
544                }
545            };
546            match response.status {
547                402 if topups < 5 => {
548                    // Out of money for this request: add more from the wallet
549                    // (the top-up links only to this session) and try again.
550                    topups += 1;
551                    let cents = self.settings.funding_cents << topups;
552                    let result = {
553                        let mut wallet = self.wallet.lock().await;
554                        self.client.topup(&mut wallet, &entry.session, cents).await
555                    };
556                    entry.busy.fetch_sub(1, Ordering::SeqCst);
557                    if let Err(e) = result {
558                        return text(
559                            StatusCode::PAYMENT_REQUIRED,
560                            &format!("The session ran out and the wallet could not top it up: {e:#}"),
561                        );
562                    }
563                    continue;
564                }
565                401 if !reopened && !has_thread => {
566                    // The session expired: close it for its change, start a new one.
567                    entry.busy.fetch_sub(1, Ordering::SeqCst);
568                    reopened = true;
569                    self.retire_entry(&key).await;
570                    continue;
571                }
572                _ => {}
573            }
574            if let Some(rev) = response.header("x-obscurify-thread") {
575                self.threads
576                    .lock()
577                    .unwrap()
578                    .insert(rev.to_string(), key.clone());
579            }
580            let out = pass_through_tracked(response, entry.clone());
581            return out;
582        }
583    }
584
585    async fn status_json(&self) -> Value {
586        let mut wallet = self.wallet.lock().await;
587        let period = unlinkable_inference::pass::current_period();
588        let passes = wallet.passes(&period);
589        let sessions: Vec<Value> = self
590            .sessions
591            .lock()
592            .unwrap()
593            .values()
594            .map(|e| {
595                json!({
596                    "family": e.session.family,
597                    "age_seconds": now() - e.opened_at,
598                    "idle_seconds": now() - e.last_used.load(Ordering::SeqCst),
599                    "requests": e.requests.load(Ordering::SeqCst),
600                })
601            })
602            .collect();
603        let traffic: Vec<Value> = self
604            .traffic
605            .lock()
606            .unwrap()
607            .iter()
608            .take(40)
609            .map(|(at, o)| {
610                json!({"at": at, "bytes_sent": o.bytes_sent, "server_sees": o.server_sees})
611            })
612            .collect();
613        json!({
614            "server": self.opts.server,
615            "keyset": self.client.keyset.fingerprint(),
616            "wallet": {
617                "paid_cents": wallet.balance_cents(Family::Paid),
618                "promo_cents": wallet.balance_cents(Family::Promo),
619                "vouchers": wallet.vouchers().len(),
620                "passes": passes.len(),
621                "pass_tier": passes.first().map(|p| p.tier.clone()),
622            },
623            "settings": {
624                "session_funding_cents": self.settings.funding_cents,
625                "idle_close_seconds": self.settings.idle_close.as_secs(),
626            },
627            "sessions": sessions,
628            "traffic": traffic,
629        })
630    }
631
632    /// What private use cost, oldest first: closed sessions from the wallet's
633    /// log plus what open ones have used so far (each asked with its own secret).
634    async fn spending_json(&self) -> Value {
635        let (mut spent, open, mut prepaid) = {
636            let wallet = self.wallet.lock().await;
637            (wallet.spending().to_vec(), wallet.sessions().to_vec(), wallet.balance_millicents(Family::Paid))
638        };
639        for o in open.into_iter().filter(|o| o.funded_millicents > 0) {
640            let session = unlinkable_inference::net::Session { secret: o.secret.clone(), family: o.family };
641            if let Ok(status) = self.client.status(&session).await {
642                let left = unlinkable_inference::net::usd_to_millicents_ceil(&status.balance_usd);
643                prepaid += left;
644                if o.funded_millicents > left {
645                    spent.push(unlinkable_inference::Spend { at: o.used_at.max(o.opened_at), millicents: o.funded_millicents - left });
646                }
647            }
648        }
649        json!({ "spent": spent, "prepaid_millicents": prepaid })
650    }
651
652    async fn withdraw(&self, api_key: &str, cents: i64) -> Result<i64> {
653        let mut wallet = self.wallet.lock().await;
654        self.client.withdraw(&mut wallet, api_key, cents).await
655    }
656
657    async fn passes(&self, api_key: &str, count: i64) -> Result<usize> {
658        let mut wallet = self.wallet.lock().await;
659        self.client.get_passes(&mut wallet, api_key, count).await
660    }
661
662    async fn import(&self, codes: &[String]) -> Result<i64> {
663        let mut added = 0;
664        let mut wallet = self.wallet.lock().await;
665        for code in codes {
666            let voucher = Voucher::parse(code).ok_or_else(|| anyhow!("not a voucher: {code}"))?;
667            let family = unlinkable_inference::blank::verify(&self.client.keyset, &voucher)
668                .ok_or_else(|| anyhow!("this server did not sign {code}"))?;
669            added += voucher.denomination_cents;
670            wallet.add(family, [voucher]);
671        }
672        wallet.save()?;
673        Ok(added)
674    }
675}
676
677fn copy_headers(resp: &unlinkable_inference::net::Response, out: &mut HeaderMap) {
678    for (k, v) in &resp.headers {
679        let k = k.to_ascii_lowercase();
680        if DROPPED_RESPONSE_HEADERS.contains(&k.as_str()) {
681            continue;
682        }
683        if let (Ok(name), Ok(value)) = (
684            axum::http::HeaderName::from_bytes(k.as_bytes()),
685            HeaderValue::from_str(v),
686        ) {
687            out.insert(name, value);
688        }
689    }
690}
691
692fn pass_through(resp: unlinkable_inference::net::Response) -> Response {
693    let mut headers = HeaderMap::new();
694    copy_headers(&resp, &mut headers);
695    let status = StatusCode::from_u16(resp.status).unwrap_or(StatusCode::BAD_GATEWAY);
696    let body = Body::from_stream(resp.body.map(|r| r.map_err(std::io::Error::other)));
697    (status, headers, body).into_response()
698}
699
700/// Like [`pass_through`], keeping the session marked busy until the
701/// stream ends, so it is never closed mid-answer.
702fn pass_through_tracked(resp: unlinkable_inference::net::Response, entry: Arc<Entry>) -> Response {
703    let mut headers = HeaderMap::new();
704    copy_headers(&resp, &mut headers);
705    let status = StatusCode::from_u16(resp.status).unwrap_or(StatusCode::BAD_GATEWAY);
706    struct Done(Arc<Entry>);
707    impl Drop for Done {
708        fn drop(&mut self) {
709            self.0.last_used.store(now(), Ordering::SeqCst);
710            self.0.busy.fetch_sub(1, Ordering::SeqCst);
711        }
712    }
713    let done = Done(entry);
714    let body = resp.body.map(move |r| {
715        let _keep = &done;
716        r.map_err(std::io::Error::other)
717    });
718    (status, headers, Body::from_stream(body)).into_response()
719}
720
721/// Only local clients, and never a web page: a site you visit must not be
722/// able to spend your wallet through this proxy.
723fn local_only(headers: &HeaderMap) -> Option<Response> {
724    let host = headers
725        .get("host")
726        .and_then(|v| v.to_str().ok())
727        .unwrap_or("");
728    let host_name = host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host);
729    if !matches!(host_name, "127.0.0.1" | "localhost" | "[::1]" | "") {
730        return Some(text(StatusCode::FORBIDDEN, "local clients only"));
731    }
732    if let Some(origin) = headers.get("origin").and_then(|v| v.to_str().ok()) {
733        let ok = ["http://127.0.0.1", "http://localhost", "http://[::1]"]
734            .iter()
735            .any(|p| origin.starts_with(p));
736        if !ok {
737            return Some(text(StatusCode::FORBIDDEN, "web pages cannot use this proxy"));
738        }
739    }
740    None
741}
742
743async fn handle(State(proxy): State<Arc<Proxy>>, req: Request) -> Response {
744    let (parts, body) = req.into_parts();
745    if let Some(refusal) = local_only(&parts.headers) {
746        return refusal;
747    }
748    let path = parts
749        .uri
750        .path_and_query()
751        .map(|p| p.as_str().to_string())
752        .unwrap_or_else(|| "/".into());
753    let method = parts.method.as_str().to_string();
754    let Ok(body) = axum::body::to_bytes(body, MAX_BODY).await else {
755        return text(StatusCode::PAYLOAD_TOO_LARGE, "request too large");
756    };
757
758    if path.starts_with("/_unlinkable") {
759        return control(&proxy, &method, &path, &parts.headers, &body).await;
760    }
761    if method == "POST" {
762        let json = parts
763            .headers
764            .get("content-type")
765            .and_then(|v| v.to_str().ok())
766            .is_some_and(|v| v.starts_with("application/json"));
767        if !json {
768            return text(StatusCode::UNSUPPORTED_MEDIA_TYPE, "send application/json");
769        }
770    }
771    // Clients configured with a base URL without /v1 (some Anthropic
772    // setups) still reach the API.
773    let path = if path.starts_with("/v1/") {
774        path
775    } else {
776        format!("/v1{path}")
777    };
778    // Only API calls go out (and only they open sessions): a browser's
779    // favicon request or a typo must not spend the wallet.
780    let route = path.split('?').next().unwrap_or("");
781    let api = match method.as_str() {
782        "GET" => route == "/v1/models" || route.starts_with("/v1/models/"),
783        "POST" => FORWARDED_POSTS.iter().any(|p| route == *p || route.starts_with(&format!("{p}/"))),
784        _ => false,
785    };
786    if !api {
787        return text(StatusCode::NOT_FOUND, "not an API path this proxy forwards");
788    }
789    proxy.forward(&method, &path, parts.headers, body).await
790}
791
792async fn control(proxy: &Proxy, method: &str, path: &str, headers: &HeaderMap, body: &[u8]) -> Response {
793    if method == "POST" {
794        let json = headers
795            .get("content-type")
796            .and_then(|v| v.to_str().ok())
797            .is_some_and(|v| v.starts_with("application/json"));
798        if !json {
799            return text(StatusCode::UNSUPPORTED_MEDIA_TYPE, "send application/json");
800        }
801    }
802    let body: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
803    match (method, path) {
804        ("GET", "/_unlinkable") | ("GET", "/_unlinkable/") => Html(PAGE).into_response(),
805        ("GET", "/_unlinkable/status") => Json(proxy.status_json().await).into_response(),
806        ("GET", "/_unlinkable/spending") => Json(proxy.spending_json().await).into_response(),
807        ("GET", "/_unlinkable/key") => match proxy.helper_secret().await {
808            Ok(secret) => secret.into_response(),
809            Err(e) => text(StatusCode::PAYMENT_REQUIRED, &format!("{e:#}")),
810        },
811        ("POST", "/_unlinkable/withdraw") => {
812            let cents = body["amount_cents"].as_i64().unwrap_or(0);
813            let key = body["api_key"].as_str().unwrap_or("");
814            match proxy.withdraw(key, cents).await {
815                Ok(c) => Json(json!({"withdrawn_cents": c})).into_response(),
816                Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
817            }
818        }
819        ("POST", "/_unlinkable/passes") => {
820            let count = body["count"].as_i64().unwrap_or(30);
821            let key = body["api_key"].as_str().unwrap_or("");
822            match proxy.passes(key, count).await {
823                Ok(n) => Json(json!({"got": n})).into_response(),
824                Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
825            }
826        }
827        ("POST", "/_unlinkable/import") => {
828            let codes: Vec<String> = body["vouchers"]
829                .as_array()
830                .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
831                .unwrap_or_default();
832            match proxy.import(&codes).await {
833                Ok(c) => Json(json!({"added_cents": c})).into_response(),
834                Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
835            }
836        }
837        ("POST", "/_unlinkable/close") => {
838            proxy.close_all().await;
839            Json(json!({"closed": true})).into_response()
840        }
841        _ => text(StatusCode::NOT_FOUND, "no such control endpoint"),
842    }
843}
844
845pub fn router(proxy: Arc<Proxy>) -> Router {
846    Router::new().fallback(handle).with_state(proxy)
847}
848
849/// Serve until `shutdown` resolves, closing idle sessions as it goes and
850/// every session at the end.
851pub async fn run(
852    listener: tokio::net::TcpListener,
853    proxy: Arc<Proxy>,
854    shutdown: impl std::future::Future<Output = ()> + Send + 'static,
855) -> Result<()> {
856    let closer = proxy.clone();
857    let ticker = tokio::spawn(async move {
858        let mut tick = tokio::time::interval(Duration::from_secs(5));
859        let mut n: u64 = 0;
860        loop {
861            tick.tick().await;
862            closer.watch_helper().await;
863            closer.close_idle().await;
864            if n.is_multiple_of(12) {
865                closer.refill(false).await;
866            }
867            n += 1;
868        }
869    });
870    axum::serve(listener, router(proxy.clone()))
871        .with_graceful_shutdown(shutdown)
872        .await?;
873    ticker.abort();
874    proxy.close_all().await;
875    Ok(())
876}
877
878const PAGE: &str = r#"<!doctype html>
879<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
880<title>unlinkable-inference: what leaves this device</title>
881<style>
882body{font:15px/1.45 system-ui,sans-serif;background:#111;color:#ddd;margin:0;padding:1rem 1rem 6rem}
883h1{font-size:1.2rem;margin:.2rem 0 1rem}h2{font-size:1rem;margin:1.5rem 0 .5rem;color:#aaa}
884.card{background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;padding:.8rem;margin:.5rem 0}
885code{color:#9cf}.peer{color:#fc9}.server{color:#9f9}.warn{color:#f99}
886table{border-collapse:collapse;width:100%}td{padding:.35rem .4rem;border-top:1px solid #2a2a2a;vertical-align:top}
887.dock{position:fixed;right:1rem;bottom:1rem;display:flex;gap:.5rem;flex-wrap:wrap;justify-content:flex-end}
888button,input{font:inherit;border-radius:6px;border:1px solid #444;background:#222;color:#eee;padding:.5rem .8rem}
889button{background:#2d4f7c;border-color:#3d6aa5}
890</style></head><body>
891<h1>What leaves this device</h1>
892<div id="summary" class="card">Loading…</div>
893<h2>Spent</h2><div id="spent" class="card">Loading…</div>
894<h2>Open sessions</h2><div id="sessions" class="card"></div>
895<h2>Last requests</h2><div class="card"><table id="traffic"></table></div>
896<div class="dock">
897<input id="key" placeholder="account API key" size="18">
898<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>
899<button onclick="passes()">Get passes</button>
900<button onclick="withdraw()">Withdraw into wallet</button>
901</div>
902<script>
903const $=id=>document.getElementById(id);
904const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
905const usd=c=>'$'+(c/100).toFixed(2);
906async function load(){
907 const s=await (await fetch('/_unlinkable/status')).json();
908 $('summary').innerHTML=`Server <code>${esc(s.server)}</code><br>`+
909  `The server sees your IP address unless Tor or a VPN hides it. It never sees your account or how you paid.`+
910  `<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`+
911  `<br>Passes this month: ${s.wallet.passes}${s.wallet.pass_tier?' ('+esc(s.wallet.pass_tier)+')':''}. Each new conversation uses one, so it gets your plan's models.`;
912 $('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.';
913 $('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>';
914}
915async function spent(){
916 const list=(await (await fetch('/_unlinkable/spending')).json()).spent;
917 const day=t=>new Date(t*1000).toLocaleDateString(undefined,{weekday:'short',month:'short',day:'numeric'});
918 const m=x=>'$'+(x/100000).toFixed(x&&x<1000?4:2);
919 const now=new Date(), today=day(now/1000), month=now.getFullYear()*12+now.getMonth();
920 const days=new Map(); let t=0,mo=0;
921 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);}
922 $('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(''))+
923  '<br><span style="color:#888">Kept on this device only: the server cannot tie these sessions to your account.</span>';
924}
925async function withdraw(){
926 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})});
927 const j=await r.json(); alert(r.ok?'Added '+usd(j.withdrawn_cents)+' to the wallet':j.error.message); $('key').value=''; load();
928}
929async function passes(){
930 const r=await fetch('/_unlinkable/passes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({api_key:$('key').value.trim(),count:30})});
931 const j=await r.json(); alert(r.ok?'Got '+j.got+' passes':j.error.message); $('key').value=''; load();
932}
933load(); setInterval(load,4000); spent(); setInterval(spent,30000);
934</script></body></html>"#;