1use 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 Conversation,
32 Key,
34 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 pub funding_cents: i64,
54 pub mode: Mode,
55 pub idle_close: Duration,
57 pub show_traffic: bool,
58 pub account_key: Option<String>,
62 pub keep_cents: i64,
64 pub refill_cents: i64,
66 pub keep_passes: usize,
68 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 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 refill_backoff: Mutex<Option<std::time::Instant>>,
109 offered: tokio::sync::Mutex<Option<(unlinkable_inference::protocol::PassAllowance, std::time::Instant)>>,
111 refused_labels: Mutex<HashMap<String, std::time::Instant>>,
113 helper_balance: Mutex<String>,
115}
116
117const HELPER: &str = "helper";
120
121fn 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
136const 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
155const 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
174pub fn conversation_fingerprint(path: &str, body: &Value) -> String {
176 let parts = if path.ends_with("/chat/completions") {
177 let messages = body["messages"].as_array().cloned().unwrap_or_default();
178 let end = messages
179 .iter()
180 .position(|m| m["role"] == "user")
181 .map(|i| i + 1)
182 .unwrap_or(messages.len());
183 json!(messages[..end])
184 } else if path.ends_with("/messages") {
185 json!([body["system"], body["messages"][0]])
186 } else if path.ends_with("/responses") {
187 let first = match &body["input"] {
188 Value::Array(items) => items.first().cloned().unwrap_or(Value::Null),
189 other => other.clone(),
190 };
191 json!([body["instructions"], first])
192 } else {
193 Value::Null
194 };
195 unlinkable_inference::sha256_hex(parts.to_string())[..16].to_string()
196}
197
198fn client_key(headers: &HeaderMap) -> String {
199 headers
200 .get("authorization")
201 .and_then(|v| v.to_str().ok())
202 .map(|v| v.trim_start_matches("Bearer ").trim().to_string())
203 .or_else(|| {
204 headers
205 .get("x-api-key")
206 .and_then(|v| v.to_str().ok())
207 .map(str::to_string)
208 })
209 .unwrap_or_default()
210}
211
212impl Proxy {
213 pub fn new(mut client: Client, wallet: Wallet, settings: Settings, opts: Options) -> Arc<Self> {
214 let traffic: Arc<Mutex<VecDeque<(u64, Observed)>>> = Arc::new(Mutex::new(VecDeque::new()));
215 let log = traffic.clone();
216 let show = settings.show_traffic;
217 client.transport = client.transport.clone().observe(Arc::new(move |o: &Observed| {
218 if show {
219 eprintln!("→ {}: {}", o.server, o.server_sees);
220 }
221 let mut log = log.lock().unwrap();
222 log.push_front((now(), o.clone()));
223 log.truncate(100);
224 }));
225 Arc::new(Self {
226 client,
227 wallet: tokio::sync::Mutex::new(wallet),
228 sessions: Mutex::new(HashMap::new()),
229 threads: Mutex::new(HashMap::new()),
230 traffic,
231 opening: tokio::sync::Mutex::new(()),
232 account_key: Mutex::new(settings.account_key.clone()),
233 refill_backoff: Mutex::new(None),
234 offered: tokio::sync::Mutex::new(None),
235 refused_labels: Mutex::new(HashMap::new()),
236 helper_balance: Mutex::new(String::new()),
237 settings,
238 opts,
239 })
240 }
241
242 fn session_key(&self, path: &str, headers: &HeaderMap, body: &Value) -> String {
243 if let Some(rev) = body["thread"]["rev"].as_str() {
244 if let Some(key) = self.threads.lock().unwrap().get(rev) {
245 return key.clone();
246 }
247 }
248 match self.settings.mode {
249 Mode::Run => "run".to_string(),
250 Mode::Key => format!("key:{}", client_key(headers)),
251 Mode::Conversation => format!(
252 "conv:{}:{}",
253 client_key(headers),
254 conversation_fingerprint(path, body)
255 ),
256 }
257 }
258
259 async fn family_to_spend(&self) -> Family {
260 let wallet = self.wallet.lock().await;
261 if wallet.balance_cents(Family::Paid) == 0 && wallet.balance_cents(Family::Promo) > 0 {
262 Family::Promo
263 } else {
264 Family::Paid
265 }
266 }
267
268 pub async fn refill(&self, urgent: bool) {
274 let Some(key) = self.account_key.lock().unwrap().clone() else {
275 return;
276 };
277 if !urgent {
278 if let Some(at) = *self.refill_backoff.lock().unwrap() {
279 if at.elapsed() < Duration::from_secs(600) {
280 return;
281 }
282 }
283 }
284 let mut wallet = self.wallet.lock().await;
285 let mut failed = false;
286 if wallet.balance_cents(Family::Paid) < self.settings.keep_cents && self.client.seed.is_some() {
289 if let Err(e) = self.client.restore(&mut wallet, Some(&key)).await {
290 tracing::warn!("could not look for the account's other vouchers: {e:#}");
291 }
292 }
293 if wallet.balance_cents(Family::Paid) < self.settings.keep_cents {
294 match self
296 .client
297 .withdraw_up_to(&mut wallet, &key, self.settings.refill_cents, 10)
298 .await
299 {
300 Ok(c) => tracing::info!("topped up the wallet with {} from the account", dollars(c)),
301 Err(e) => {
302 failed = true;
303 tracing::warn!("could not top up the wallet: {e:#}");
304 }
305 }
306 }
307 match self.stock(&mut wallet, &key, None, false).await {
308 Ok(0) => {}
309 Ok(n) => tracing::info!("got {n} passes for this month"),
310 Err(e) => {
311 failed = true;
312 tracing::warn!("could not get passes: {e:#}");
313 }
314 }
315 if self.client.seed.is_some() {
316 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 async fn stock(&self, wallet: &mut Wallet, key: &str, only: Option<&str>, fresh: bool) -> Result<usize> {
329 if self.client.keyset.pass_key.is_none() {
330 return Ok(0);
331 }
332 let mut offered = self.offered.lock().await;
333 if fresh || offered.as_ref().is_none_or(|(_, at)| at.elapsed() >= Duration::from_secs(600)) {
334 *offered = Some((self.client.pass_allowance(key).await?, std::time::Instant::now()));
335 }
336 let Some((allowance, _)) = offered.as_mut() else { return Ok(0) };
337 Ok(self.client.stock_passes(wallet, key, allowance, self.settings.keep_passes, 30, only).await)
338 }
339
340 async fn present_pass(&self, entry: &Entry, label: &str) -> bool {
346 let mut wallet = self.wallet.lock().await;
347 match self.client.present_pass(&mut wallet, &entry.session, label).await {
348 Ok(true) => return true,
349 Ok(false) => {}
350 Err(e) => {
351 tracing::warn!("could not present a {label} pass: {e:#}");
352 return false;
353 }
354 }
355 let Some(key) = self.account_key.lock().unwrap().clone() else { return false };
356 let known = self
357 .offered
358 .lock()
359 .await
360 .as_ref()
361 .filter(|(_, at)| at.elapsed() < Duration::from_secs(600))
362 .and_then(|(a, _)| a.labels.iter().find(|l| l.label == label))
363 .map(|l| l.remaining);
364 let fresh = match known {
365 Some(left) if left <= 0 => return false,
366 Some(_) => false,
367 None => {
368 let mut refused = self.refused_labels.lock().unwrap();
369 if refused.get(label).is_some_and(|at| at.elapsed() < Duration::from_secs(60)) {
370 return false;
371 }
372 refused.insert(label.to_string(), std::time::Instant::now());
373 true
374 }
375 };
376 let _ = self.stock(&mut wallet, &key, Some(label), fresh).await;
377 self.client.present_pass(&mut wallet, &entry.session, label).await.unwrap_or(false)
378 }
379
380 fn learn_account_key(&self, headers: &HeaderMap) {
381 let key = client_key(headers);
382 if !self.settings.account_key_prefix.is_empty() && key.starts_with(&self.settings.account_key_prefix) {
383 let mut known = self.account_key.lock().unwrap();
384 if known.is_none() {
385 *known = Some(key);
386 }
387 }
388 }
389
390 async fn entry(&self, key: &str) -> Result<Arc<Entry>> {
391 if let Some(e) = self.sessions.lock().unwrap().get(key) {
392 return Ok(e.clone());
393 }
394 let _guard = self.opening.lock().await;
395 if let Some(e) = self.sessions.lock().unwrap().get(key) {
396 return Ok(e.clone());
397 }
398 let family = self.family_to_spend().await;
399 let opened = {
400 let mut wallet = self.wallet.lock().await;
401 self.client
402 .open(&mut wallet, family, self.settings.funding_cents)
403 .await
404 };
405 let session = match opened {
406 Ok(s) => s,
407 Err(e) if e.to_string().contains("has no") => {
408 self.refill(true).await;
411 let mut wallet = self.wallet.lock().await;
412 self.client
413 .open(&mut wallet, family, self.settings.funding_cents)
414 .await?
415 }
416 Err(e) => return Err(e),
417 };
418 let entry = Arc::new(Entry {
419 session,
420 last_used: AtomicU64::new(now()),
421 busy: AtomicUsize::new(0),
422 opened_at: now(),
423 requests: AtomicU64::new(0),
424 });
425 self.sessions
426 .lock()
427 .unwrap()
428 .insert(key.to_string(), entry.clone());
429 Ok(entry)
430 }
431
432 pub async fn helper_secret(&self) -> Result<String> {
436 let existing = self.sessions.lock().unwrap().get(HELPER).cloned();
437 if let Some(entry) = existing {
438 match self.client.status(&entry.session).await {
439 Ok(st) if st.closed => self.retire_entry(HELPER).await,
440 Err(e) if gone(&e) => self.retire_entry(HELPER).await,
441 _ => return Ok(entry.session.secret.clone()),
444 }
445 }
446 let entry = self.entry(HELPER).await?;
447 let key = self.account_key.lock().unwrap().clone();
450 let mut wallet = self.wallet.lock().await;
451 if let Some(key) = key {
452 let _ = self.stock(&mut wallet, &key, None, false).await;
453 }
454 let period = unlinkable_inference::pass::current_period();
455 let mut labels: Vec<String> = wallet.passes(&period).into_iter().map(|p| p.label).collect();
456 labels.sort();
457 labels.dedup();
458 for label in labels {
459 if let Err(e) = self.client.present_pass(&mut wallet, &entry.session, &label).await {
460 tracing::warn!("could not present a {label} pass for the helper session: {e:#}");
461 }
462 }
463 Ok(entry.session.secret.clone())
464 }
465
466 pub async fn watch_helper(&self) {
470 let Some(entry) = self.sessions.lock().unwrap().get(HELPER).cloned() else {
471 return;
472 };
473 let st = match self.client.status(&entry.session).await {
474 Ok(st) if !st.closed => st,
475 Ok(_) => return self.retire_entry(HELPER).await,
476 Err(e) if gone(&e) => return self.retire_entry(HELPER).await,
477 Err(_) => return,
478 };
479 let changed = {
480 let mut last = self.helper_balance.lock().unwrap();
481 let changed = *last != st.balance_usd;
482 *last = st.balance_usd.clone();
483 changed
484 };
485 if changed {
486 entry.last_used.store(now(), Ordering::SeqCst);
487 }
488 if unlinkable_inference::net::usd_to_cents_floor(&st.balance_usd) < self.settings.funding_cents {
489 let mut wallet = self.wallet.lock().await;
490 if wallet.balance_cents(entry.session.family) < self.settings.funding_cents {
491 drop(wallet);
492 self.refill(true).await;
493 wallet = self.wallet.lock().await;
494 }
495 if let Err(e) = self
496 .client
497 .topup(&mut wallet, &entry.session, self.settings.funding_cents)
498 .await
499 {
500 tracing::warn!("could not top up the helper session: {e:#}");
501 }
502 }
503 }
504
505 async fn retire_entry(&self, key: &str) {
509 if let Some(old) = self.drop_entry(key) {
510 self.close_entry(&old).await;
511 }
512 }
513
514 fn drop_entry(&self, key: &str) -> Option<Arc<Entry>> {
515 self.sessions.lock().unwrap().remove(key)
516 }
517
518 async fn close_entry(&self, entry: &Entry) {
519 let mut wallet = self.wallet.lock().await;
520 wallet.used_session(&entry.session.secret, entry.last_used.load(Ordering::SeqCst));
522 match self.client.close(&mut wallet, &entry.session).await {
523 Ok(cents) => tracing::info!("closed a session; {} back in the wallet", dollars(cents)),
524 Err(e) => tracing::warn!("could not close a session (will retry at next start): {e}"),
525 }
526 }
527
528 pub async fn close_idle(&self) {
530 let cutoff = now().saturating_sub(self.settings.idle_close.as_secs());
531 let idle: Vec<(String, Arc<Entry>)> = {
532 let mut sessions = self.sessions.lock().unwrap();
533 let keys: Vec<String> = sessions
534 .iter()
535 .filter(|(_, e)| {
536 e.busy.load(Ordering::SeqCst) == 0 && e.last_used.load(Ordering::SeqCst) <= cutoff
537 })
538 .map(|(k, _)| k.clone())
539 .collect();
540 keys.into_iter()
541 .filter_map(|k| sessions.remove(&k).map(|e| (k, e)))
542 .collect()
543 };
544 for (key, entry) in idle {
545 self.threads.lock().unwrap().retain(|_, v| *v != key);
546 self.close_entry(&entry).await;
547 }
548 }
549
550 pub async fn close_all(&self) {
551 let all: Vec<Arc<Entry>> = self.sessions.lock().unwrap().drain().map(|(_, e)| e).collect();
552 self.threads.lock().unwrap().clear();
553 for entry in all {
554 self.close_entry(&entry).await;
555 }
556 }
557
558 async fn send(&self, entry: &Entry, method: &str, path: &str, headers: &[(String, String)], body: &[u8]) -> Result<unlinkable_inference::net::Response> {
559 let mut inner = Inner {
560 method: method.to_string(),
561 path: path.to_string(),
562 headers: headers.to_vec(),
563 body: body.to_vec(),
564 };
565 inner = inner.bearer(&entry.session.secret);
566 self.client.transport.send(inner).await
567 }
568
569 async fn forward(&self, method: &str, path: &str, headers: HeaderMap, body: bytes::Bytes) -> Response {
570 let passed: Vec<(String, String)> = PASSED_HEADERS
571 .iter()
572 .filter_map(|&h| {
573 headers
574 .get(h)
575 .and_then(|v| v.to_str().ok())
576 .map(|v| (h.to_string(), v.to_string()))
577 })
578 .collect();
579
580 if method == "GET" && (path == "/v1/models" || path.starts_with("/v1/models/")) {
582 let req = Inner {
583 method: method.into(),
584 path: path.into(),
585 headers: passed,
586 body: Vec::new(),
587 };
588 return match self.client.transport.send(req).await {
589 Ok(r) => pass_through(r),
590 Err(e) => text(StatusCode::BAD_GATEWAY, &format!("{e:#}")),
591 };
592 }
593
594 self.learn_account_key(&headers);
595 let json_body: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
596 let key = self.session_key(path, &headers, &json_body);
597 let has_thread = json_body["thread"]["rev"].is_string();
598
599 let mut reopened = false;
600 let mut topups = 0;
601 let mut presented = 0;
602 let mut none: Vec<String> = Vec::new();
603 loop {
604 let entry = match self.entry(&key).await {
605 Ok(e) => e,
606 Err(e) => return text(StatusCode::PAYMENT_REQUIRED, &format!("{e:#}")),
607 };
608 entry.busy.fetch_add(1, Ordering::SeqCst);
609 let result = self.send(&entry, method, path, &passed, &body).await;
610 entry.last_used.store(now(), Ordering::SeqCst);
611 entry.requests.fetch_add(1, Ordering::SeqCst);
612 let response = match result {
613 Ok(r) => r,
614 Err(e) => {
615 entry.busy.fetch_sub(1, Ordering::SeqCst);
616 return text(StatusCode::BAD_GATEWAY, &format!("{e:#}"));
617 }
618 };
619 match response.status {
620 402 if topups < 5 => {
621 topups += 1;
624 let cents = self.settings.funding_cents << topups;
625 let result = {
626 let mut wallet = self.wallet.lock().await;
627 self.client.topup(&mut wallet, &entry.session, cents).await
628 };
629 entry.busy.fetch_sub(1, Ordering::SeqCst);
630 if let Err(e) = result {
631 return text(
632 StatusCode::PAYMENT_REQUIRED,
633 &format!("The session ran out and the wallet could not top it up: {e:#}"),
634 );
635 }
636 continue;
637 }
638 403 if presented < 8 && response.header(unlinkable_inference::protocol::PASS_REQUIRED_HEADER).is_some() => {
639 let label = response.header(unlinkable_inference::protocol::PASS_REQUIRED_HEADER).unwrap_or_default().to_string();
643 if self.present_pass(&entry, &label).await {
644 presented += 1;
645 entry.busy.fetch_sub(1, Ordering::SeqCst);
646 continue;
647 }
648 if !none.contains(&label) {
649 none.push(label);
650 entry.busy.fetch_sub(1, Ordering::SeqCst);
651 continue;
652 }
653 }
654 401 if !reopened && !has_thread => {
655 entry.busy.fetch_sub(1, Ordering::SeqCst);
657 reopened = true;
658 self.retire_entry(&key).await;
659 continue;
660 }
661 _ => {}
662 }
663 if let Some(rev) = response.header("x-obscurify-thread") {
664 self.threads
665 .lock()
666 .unwrap()
667 .insert(rev.to_string(), key.clone());
668 }
669 let out = pass_through_tracked(response, entry.clone());
670 return out;
671 }
672 }
673
674 async fn status_json(&self) -> Value {
675 let mut wallet = self.wallet.lock().await;
676 let period = unlinkable_inference::pass::current_period();
677 let passes = wallet.passes(&period);
678 let mut pass_labels = std::collections::BTreeMap::<String, usize>::new();
679 for p in &passes {
680 *pass_labels.entry(p.label.clone()).or_default() += 1;
681 }
682 let sessions: Vec<Value> = self
683 .sessions
684 .lock()
685 .unwrap()
686 .values()
687 .map(|e| {
688 json!({
689 "family": e.session.family,
690 "age_seconds": now() - e.opened_at,
691 "idle_seconds": now() - e.last_used.load(Ordering::SeqCst),
692 "requests": e.requests.load(Ordering::SeqCst),
693 })
694 })
695 .collect();
696 let traffic: Vec<Value> = self
697 .traffic
698 .lock()
699 .unwrap()
700 .iter()
701 .take(40)
702 .map(|(at, o)| {
703 json!({"at": at, "bytes_sent": o.bytes_sent, "server_sees": o.server_sees})
704 })
705 .collect();
706 json!({
707 "server": self.opts.server,
708 "keyset": self.client.keyset.fingerprint(),
709 "wallet": {
710 "paid_cents": wallet.balance_cents(Family::Paid),
711 "promo_cents": wallet.balance_cents(Family::Promo),
712 "vouchers": wallet.vouchers().len(),
713 "passes": passes.len(),
714 "pass_labels": pass_labels,
715 },
716 "settings": {
717 "session_funding_cents": self.settings.funding_cents,
718 "idle_close_seconds": self.settings.idle_close.as_secs(),
719 },
720 "sessions": sessions,
721 "traffic": traffic,
722 })
723 }
724
725 async fn spending_json(&self) -> Value {
728 let (mut spent, open, mut prepaid) = {
729 let wallet = self.wallet.lock().await;
730 (wallet.spending().to_vec(), wallet.sessions().to_vec(), wallet.balance_millicents(Family::Paid))
731 };
732 for o in open.into_iter().filter(|o| o.funded_millicents > 0) {
733 let session = unlinkable_inference::net::Session { secret: o.secret.clone(), family: o.family };
734 if let Ok(status) = self.client.status(&session).await {
735 let left = unlinkable_inference::net::usd_to_millicents_ceil(&status.balance_usd);
736 prepaid += left;
737 if o.funded_millicents > left {
738 spent.push(unlinkable_inference::Spend { at: o.used_at.max(o.opened_at), millicents: o.funded_millicents - left });
739 }
740 }
741 }
742 json!({ "spent": spent, "prepaid_millicents": prepaid })
743 }
744
745 async fn withdraw(&self, api_key: &str, cents: i64) -> Result<i64> {
746 let mut wallet = self.wallet.lock().await;
747 self.client.withdraw(&mut wallet, api_key, cents).await
748 }
749
750 async fn passes(&self, api_key: &str, count: i64) -> Result<usize> {
752 let mut wallet = self.wallet.lock().await;
753 let allowance = self.client.pass_allowance(api_key).await?;
754 let mut got = 0;
755 for l in &allowance.labels {
756 got += self.client.get_passes(&mut wallet, api_key, &l.label, &allowance.period, count.min(l.remaining)).await?;
757 }
758 Ok(got)
759 }
760
761 async fn import(&self, codes: &[String]) -> Result<i64> {
762 let mut added = 0;
763 let mut wallet = self.wallet.lock().await;
764 for code in codes {
765 let voucher = Voucher::parse(code).ok_or_else(|| anyhow!("not a voucher: {code}"))?;
766 let family = unlinkable_inference::blank::verify(&self.client.keyset, &voucher)
767 .ok_or_else(|| anyhow!("this server did not sign {code}"))?;
768 added += voucher.denomination_cents;
769 wallet.add(family, [voucher]);
770 }
771 wallet.save()?;
772 Ok(added)
773 }
774}
775
776fn copy_headers(resp: &unlinkable_inference::net::Response, out: &mut HeaderMap) {
777 for (k, v) in &resp.headers {
778 let k = k.to_ascii_lowercase();
779 if DROPPED_RESPONSE_HEADERS.contains(&k.as_str()) {
780 continue;
781 }
782 if let (Ok(name), Ok(value)) = (
783 axum::http::HeaderName::from_bytes(k.as_bytes()),
784 HeaderValue::from_str(v),
785 ) {
786 out.insert(name, value);
787 }
788 }
789}
790
791fn pass_through(resp: unlinkable_inference::net::Response) -> Response {
792 let mut headers = HeaderMap::new();
793 copy_headers(&resp, &mut headers);
794 let status = StatusCode::from_u16(resp.status).unwrap_or(StatusCode::BAD_GATEWAY);
795 let body = Body::from_stream(resp.body.map(|r| r.map_err(std::io::Error::other)));
796 (status, headers, body).into_response()
797}
798
799fn pass_through_tracked(resp: unlinkable_inference::net::Response, entry: Arc<Entry>) -> Response {
802 let mut headers = HeaderMap::new();
803 copy_headers(&resp, &mut headers);
804 let status = StatusCode::from_u16(resp.status).unwrap_or(StatusCode::BAD_GATEWAY);
805 struct Done(Arc<Entry>);
806 impl Drop for Done {
807 fn drop(&mut self) {
808 self.0.last_used.store(now(), Ordering::SeqCst);
809 self.0.busy.fetch_sub(1, Ordering::SeqCst);
810 }
811 }
812 let done = Done(entry);
813 let body = resp.body.map(move |r| {
814 let _keep = &done;
815 r.map_err(std::io::Error::other)
816 });
817 (status, headers, Body::from_stream(body)).into_response()
818}
819
820fn local_only(headers: &HeaderMap) -> Option<Response> {
823 let host = headers
824 .get("host")
825 .and_then(|v| v.to_str().ok())
826 .unwrap_or("");
827 let host_name = host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host);
828 if !matches!(host_name, "127.0.0.1" | "localhost" | "[::1]" | "") {
829 return Some(text(StatusCode::FORBIDDEN, "local clients only"));
830 }
831 if let Some(origin) = headers.get("origin").and_then(|v| v.to_str().ok()) {
832 let ok = ["http://127.0.0.1", "http://localhost", "http://[::1]"]
833 .iter()
834 .any(|p| origin.starts_with(p));
835 if !ok {
836 return Some(text(StatusCode::FORBIDDEN, "web pages cannot use this proxy"));
837 }
838 }
839 None
840}
841
842async fn handle(State(proxy): State<Arc<Proxy>>, req: Request) -> Response {
843 let (parts, body) = req.into_parts();
844 if let Some(refusal) = local_only(&parts.headers) {
845 return refusal;
846 }
847 let path = parts
848 .uri
849 .path_and_query()
850 .map(|p| p.as_str().to_string())
851 .unwrap_or_else(|| "/".into());
852 let method = parts.method.as_str().to_string();
853 let Ok(body) = axum::body::to_bytes(body, MAX_BODY).await else {
854 return text(StatusCode::PAYLOAD_TOO_LARGE, "request too large");
855 };
856
857 if path.starts_with("/_unlinkable") {
858 return control(&proxy, &method, &path, &parts.headers, &body).await;
859 }
860 if method == "POST" {
861 let json = parts
862 .headers
863 .get("content-type")
864 .and_then(|v| v.to_str().ok())
865 .is_some_and(|v| v.starts_with("application/json"));
866 if !json {
867 return text(StatusCode::UNSUPPORTED_MEDIA_TYPE, "send application/json");
868 }
869 }
870 let path = if path.starts_with("/v1/") {
873 path
874 } else {
875 format!("/v1{path}")
876 };
877 let route = path.split('?').next().unwrap_or("");
880 let api = match method.as_str() {
881 "GET" => route == "/v1/models" || route.starts_with("/v1/models/"),
882 "POST" => FORWARDED_POSTS.iter().any(|p| route == *p || route.starts_with(&format!("{p}/"))),
883 _ => false,
884 };
885 if !api {
886 return text(StatusCode::NOT_FOUND, "not an API path this proxy forwards");
887 }
888 proxy.forward(&method, &path, parts.headers, body).await
889}
890
891async fn control(proxy: &Proxy, method: &str, path: &str, headers: &HeaderMap, body: &[u8]) -> Response {
892 if method == "POST" {
893 let json = headers
894 .get("content-type")
895 .and_then(|v| v.to_str().ok())
896 .is_some_and(|v| v.starts_with("application/json"));
897 if !json {
898 return text(StatusCode::UNSUPPORTED_MEDIA_TYPE, "send application/json");
899 }
900 }
901 let body: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
902 match (method, path) {
903 ("GET", "/_unlinkable") | ("GET", "/_unlinkable/") => Html(PAGE).into_response(),
904 ("GET", "/_unlinkable/status") => Json(proxy.status_json().await).into_response(),
905 ("GET", "/_unlinkable/spending") => Json(proxy.spending_json().await).into_response(),
906 ("GET", "/_unlinkable/key") => match proxy.helper_secret().await {
907 Ok(secret) => secret.into_response(),
908 Err(e) => text(StatusCode::PAYMENT_REQUIRED, &format!("{e:#}")),
909 },
910 ("POST", "/_unlinkable/withdraw") => {
911 let cents = body["amount_cents"].as_i64().unwrap_or(0);
912 let key = body["api_key"].as_str().unwrap_or("");
913 match proxy.withdraw(key, cents).await {
914 Ok(c) => Json(json!({"withdrawn_cents": c})).into_response(),
915 Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
916 }
917 }
918 ("POST", "/_unlinkable/passes") => {
919 let count = body["count"].as_i64().unwrap_or(30);
920 let key = body["api_key"].as_str().unwrap_or("");
921 match proxy.passes(key, count).await {
922 Ok(n) => Json(json!({"got": n})).into_response(),
923 Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
924 }
925 }
926 ("POST", "/_unlinkable/import") => {
927 let codes: Vec<String> = body["vouchers"]
928 .as_array()
929 .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
930 .unwrap_or_default();
931 match proxy.import(&codes).await {
932 Ok(c) => Json(json!({"added_cents": c})).into_response(),
933 Err(e) => text(StatusCode::BAD_REQUEST, &format!("{e:#}")),
934 }
935 }
936 ("POST", "/_unlinkable/close") => {
937 proxy.close_all().await;
938 Json(json!({"closed": true})).into_response()
939 }
940 _ => text(StatusCode::NOT_FOUND, "no such control endpoint"),
941 }
942}
943
944pub fn router(proxy: Arc<Proxy>) -> Router {
945 Router::new().fallback(handle).with_state(proxy)
946}
947
948pub async fn run(
951 listener: tokio::net::TcpListener,
952 proxy: Arc<Proxy>,
953 shutdown: impl std::future::Future<Output = ()> + Send + 'static,
954) -> Result<()> {
955 let closer = proxy.clone();
956 let ticker = tokio::spawn(async move {
957 let mut tick = tokio::time::interval(Duration::from_secs(5));
958 let mut n: u64 = 0;
959 loop {
960 tick.tick().await;
961 closer.watch_helper().await;
962 closer.close_idle().await;
963 if n.is_multiple_of(12) {
964 closer.refill(false).await;
965 }
966 n += 1;
967 }
968 });
969 axum::serve(listener, router(proxy.clone()))
970 .with_graceful_shutdown(shutdown)
971 .await?;
972 ticker.abort();
973 proxy.close_all().await;
974 Ok(())
975}
976
977const PAGE: &str = r#"<!doctype html>
978<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
979<title>unlinkable-inference: what leaves this device</title>
980<style>
981body{font:15px/1.45 system-ui,sans-serif;background:#111;color:#ddd;margin:0;padding:1rem 1rem 6rem}
982h1{font-size:1.2rem;margin:.2rem 0 1rem}h2{font-size:1rem;margin:1.5rem 0 .5rem;color:#aaa}
983.card{background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;padding:.8rem;margin:.5rem 0}
984code{color:#9cf}.peer{color:#fc9}.server{color:#9f9}.warn{color:#f99}
985table{border-collapse:collapse;width:100%}td{padding:.35rem .4rem;border-top:1px solid #2a2a2a;vertical-align:top}
986.dock{position:fixed;right:1rem;bottom:1rem;display:flex;gap:.5rem;flex-wrap:wrap;justify-content:flex-end}
987button,input{font:inherit;border-radius:6px;border:1px solid #444;background:#222;color:#eee;padding:.5rem .8rem}
988button{background:#2d4f7c;border-color:#3d6aa5}
989</style></head><body>
990<h1>What leaves this device</h1>
991<div id="summary" class="card">Loading…</div>
992<h2>Spent</h2><div id="spent" class="card">Loading…</div>
993<h2>Open sessions</h2><div id="sessions" class="card"></div>
994<h2>Last requests</h2><div class="card"><table id="traffic"></table></div>
995<div class="dock">
996<input id="key" placeholder="account API key" size="18">
997<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>
998<button onclick="passes()">Get passes</button>
999<button onclick="withdraw()">Withdraw into wallet</button>
1000</div>
1001<script>
1002const $=id=>document.getElementById(id);
1003const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
1004const usd=c=>'$'+(c/100).toFixed(2);
1005async function load(){
1006 const s=await (await fetch('/_unlinkable/status')).json();
1007 $('summary').innerHTML=`Server <code>${esc(s.server)}</code><br>`+
1008 `The server sees your IP address unless Tor or a VPN hides it. It never sees your account or how you paid.`+
1009 `<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`+
1010 `<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.`;
1011 $('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.';
1012 $('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>';
1013}
1014async function spent(){
1015 const list=(await (await fetch('/_unlinkable/spending')).json()).spent;
1016 const day=t=>new Date(t*1000).toLocaleDateString(undefined,{weekday:'short',month:'short',day:'numeric'});
1017 const m=x=>'$'+(x/100000).toFixed(x&&x<1000?4:2);
1018 const now=new Date(), today=day(now/1000), month=now.getFullYear()*12+now.getMonth();
1019 const days=new Map(); let t=0,mo=0;
1020 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);}
1021 $('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(''))+
1022 '<br><span style="color:#888">Kept on this device only: the server cannot tie these sessions to your account.</span>';
1023}
1024async function withdraw(){
1025 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})});
1026 const j=await r.json(); alert(r.ok?'Added '+usd(j.withdrawn_cents)+' to the wallet':j.error.message); $('key').value=''; load();
1027}
1028async function passes(){
1029 const r=await fetch('/_unlinkable/passes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({api_key:$('key').value.trim(),count:30})});
1030 const j=await r.json(); alert(r.ok?'Got '+j.got+' passes':j.error.message); $('key').value=''; load();
1031}
1032load(); setInterval(load,4000); spent(); setInterval(spent,30000);
1033</script></body></html>"#;