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