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