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