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