Skip to main content

unlinkable_inference_cli/
lib.rs

1//! The `unlinkable-inference` proxy: shared setup for the CLI and the local server.
2
3pub mod serve;
4
5use anyhow::{bail, Context as _, Result};
6use std::path::PathBuf;
7use unlinkable_inference::keyset::{Keyset, Pins};
8use unlinkable_inference::net::{Client, Transport};
9use unlinkable_inference::Wallet;
10
11/// Where to find the server and how to reach it.
12#[derive(Debug, Clone)]
13pub struct Options {
14    /// Server origin, e.g. `https://obscurify.ai`
15    pub server: String,
16    pub wallet: Option<PathBuf>,
17    /// Extra keyset fingerprints to accept
18    pub pins: Vec<String>,
19}
20
21impl Options {
22    pub fn host(&self) -> String {
23        self.server
24            .split("://")
25            .nth(1)
26            .unwrap_or(&self.server)
27            .trim_end_matches('/')
28            .to_string()
29    }
30
31    pub fn wallet_path(&self) -> PathBuf {
32        if let Some(p) = &self.wallet {
33            return p.clone();
34        }
35        let base = std::env::var_os("XDG_DATA_HOME")
36            .map(PathBuf::from)
37            .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
38            .unwrap_or_else(|| PathBuf::from("."));
39        let host = self.host().replace([':', '/'], "_");
40        base.join("unlinkable-inference").join(host).join("wallet.json")
41    }
42
43    pub fn transport(&self) -> Transport {
44        Transport::new(&self.server)
45    }
46}
47
48/// An exclusive hold on the wallet for as long as this lives, so two
49/// processes never spend the same vouchers.
50pub struct WalletLock(#[allow(dead_code)] std::fs::File);
51
52pub fn lock_wallet(opts: &Options) -> Result<WalletLock> {
53    let path = opts.wallet_path().with_extension("lock");
54    if let Some(dir) = path.parent() {
55        std::fs::create_dir_all(dir)?;
56    }
57    let file = std::fs::OpenOptions::new()
58        .create(true)
59        .truncate(false)
60        .write(true)
61        .open(&path)
62        .with_context(|| format!("opening {}", path.display()))?;
63    if file.try_lock().is_err() {
64        bail!(
65            "another unlinkable-inference process holds the wallet ({}). If the proxy is running, use its page at /_unlinkable or stop it first.",
66            path.display()
67        );
68    }
69    Ok(WalletLock(file))
70}
71
72/// Fetch the server's keyset and check it against the pins. With no pins at all for this server, pin what we see now and
73/// refuse anything different later (trust on first use).
74pub async fn trusted_keyset(opts: &Options, wallet: &mut Wallet) -> Result<Keyset> {
75    let keyset = opts
76        .transport()
77        .fetch_keyset()
78        .await
79        .context("fetching the server's keys")?;
80    keyset.check()?;
81    let mut pins = Pins::builtin(&opts.host());
82    pins.fingerprints.extend(opts.pins.iter().cloned());
83    if let Some(p) = wallet.pinned() {
84        pins.fingerprints.insert(p.to_string());
85    }
86    let fingerprint = keyset.fingerprint();
87    if pins.fingerprints.is_empty() {
88        eprintln!(
89            "unlinkable-inference: pinned keyset {fingerprint} for {} on first use",
90            opts.host()
91        );
92        wallet.pin(Some(fingerprint));
93        wallet.save()?;
94        return Ok(keyset);
95    }
96    if !pins.accepts(&keyset) {
97        bail!(
98            "{} is serving keyset {fingerprint}, which is not one you pinned ({}). \
99             That is what a server singling you out would look like. If the server \
100             announced a key rotation in its public changelog, run `unlinkable-inference keys --trust`.",
101            opts.host(),
102            pins.fingerprints.iter().cloned().collect::<Vec<_>>().join(", ")
103        );
104    }
105    Ok(keyset)
106}
107
108pub async fn connect(opts: &Options, wallet: &mut Wallet) -> Result<Client> {
109    let keyset = trusted_keyset(opts, wallet).await?;
110    Ok(Client::new(opts.transport(), keyset))
111}
112
113/// The account's API key, from its login key (the number never leaves this
114/// device). Obscurify's `POST /generate_token`.
115pub async fn api_key_for(opts: &Options, login_key: &str) -> Result<String> {
116    let resp = opts
117        .transport()
118        .send(unlinkable_inference::net::Request::post_json(
119            "/generate_token",
120            &serde_json::json!({ "account_key": login_key }),
121        ))
122        .await?;
123    let status = resp.status;
124    let body: serde_json::Value = serde_json::from_slice(&resp.bytes().await?).unwrap_or_default();
125    match body["token"].as_str() {
126        Some(t) if status == 200 => Ok(t.to_string()),
127        _ => anyhow::bail!("signing in with the account number failed ({status}): {}", body["error"]),
128    }
129}
130
131pub fn dollars(cents: i64) -> String {
132    format!("${}.{:02}", cents / 100, cents % 100)
133}