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 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
200const DROPPED_BODY_FIELDS: &[&str] = &[
204 "metadata",
205 "client_metadata",
206 "user",
207 "safety_identifier",
208 "prompt_cache_key",
209];
210
211fn 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 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 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 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 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 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 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 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 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 _ => return Ok(entry.session.secret.clone()),
470 }
471 }
472 let entry = self.entry(HELPER).await?;
473 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 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 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 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 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 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 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 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 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 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 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
826fn 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
847fn 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 let path = if path.starts_with("/v1/") {
900 path
901 } else {
902 format!("/v1{path}")
903 };
904 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
975pub 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=>({'&':'&','<':'<','>':'>','"':'"'}[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>"#;