Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "obscuravpn-api"
version = "0.0.0"
edition = "2021"
edition = "2024"

description = "API client for Obscura VPN."
homepage = "https://github.com/Sovereign-Engineering/obscuravpn-api"
Expand All @@ -23,6 +23,7 @@ semver = "1.0.26"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.140"
serde_with = { version = "3.12.0", features = ["base64"] }
sha2 = "0.10.9"
static_assertions = "1.1.0"
strum = { version = "0.27.1", features = ["derive"] }
thiserror = "2.0.12"
Expand Down
4 changes: 2 additions & 2 deletions examples/api_cli.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use anyhow::bail;
use base64::{engine::general_purpose::STANDARD, Engine as _};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use clap::{Parser, Subcommand};
use obscuravpn_api::Client;
use obscuravpn_api::cmd::*;
use obscuravpn_api::types::{AccountId, TunnelConfig, WgPubkey};
use obscuravpn_api::wg_conf::build_wg_conf;
use obscuravpn_api::Client;
use qrcode::QrCode;
use rand::rngs::OsRng;
use x25519_dalek::{PublicKey, StaticSecret};
Expand Down
32 changes: 27 additions & 5 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::cmd::{parse_response, ApiError, ApiErrorKind, Cmd, ETagCmd, ProtocolError};
use crate::cmd::{ApiError, ApiErrorBody, ApiErrorKind, Cmd, ETagCmd, ProtocolError, parse_response};
use crate::resolver_fallback::{GaiResolverWithFallback, NoResolverFallbackCache, ResolverFallbackCache};
use crate::response::Response;
use crate::token::{AcquireToken, AcquireToken2Output};
use crate::types::{AccountId, AuthToken};
use anyhow::{anyhow, Context};
use anyhow::{Context, anyhow};
use http::HeaderValue;
use itertools::Itertools;
use reqwest::ClientBuilder;
Expand Down Expand Up @@ -128,9 +128,31 @@ impl Client {
});
}
let account_id = self.account_id.clone();
let request = AcquireToken { account_id }.to_request2(&self.base_url)?;
let res = self.send_http(request).await?;
let res = parse_response::<AcquireToken2Output>(res).await?;
let mut pow = None;
let res = loop {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs to terminate.

let request = AcquireToken {
account_id: account_id.clone(),
pow: pow.clone(),
}
.to_request2(&self.base_url)?;
let res = self.send_http(request).await?;
let res = parse_response::<AcquireToken2Output>(res).await;
if let Err(ClientError::ApiError(ApiError {
status: _,
body:
ApiErrorBody {
error: ApiErrorKind::RateLimitExceeded { pow_input: Some(pow_input) },
msg: _,
detail: _,
},
})) = &res
&& pow.is_none()
{
pow = Some(pow_input.solve(&account_id));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the hard part of this is that we should be giving client feedback. But we can add that later. There are basically two cases:

  1. We return trivial PoW challenges, deterring lazy people. UI change is not necessary.
  2. We return difficult challenges, hopefully adding notable cost. UI change seems pretty important.

continue;
}
break res;
}?;
let body = res.into_body().context("No auth token in response")?;
self.set_auth_token(Some(body.auth_token.clone().into()));

Expand Down
9 changes: 6 additions & 3 deletions src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@ pub use tunnel::*;

use std::any::Any;

use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;
use tokio_stream::StreamExt;
use url::Url;

use crate::ClientError;
use crate::pow::PowInput;
use crate::response::Response;
use crate::types::AuthToken;
use crate::ClientError;

pub trait Cmd: Serialize + DeserializeOwned + std::fmt::Debug {
type Output: Serialize + DeserializeOwned + 'static + std::fmt::Debug;
Expand Down Expand Up @@ -98,7 +99,9 @@ pub enum ApiErrorKind {
NoApiRoute {},
NoLongerSupported {},
NoMatchingExit {},
RateLimitExceeded {},
RateLimitExceeded {
pow_input: Option<PowInput>,
},
SaleNotFound {},
SignupLimitExceeded {},
TunnelLimitExceeded {},
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod wg_conf;
mod client;
#[cfg(feature = "client")]
pub mod notices;
mod pow;
pub mod relay_protocol;
#[cfg(feature = "client")]
mod resolver_fallback;
Expand Down
59 changes: 59 additions & 0 deletions src/pow.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use crate::types::AccountId;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct PowInput {
pub nonce: u128,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

decided to use string

pub difficulty: u8,
pub puzzles: u16,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PowOutput {
pub nonce: u128,
pub solutions: Vec<u128>,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

decided to use strings

}

impl PowInput {
pub fn solve(&self, account_id: &AccountId) -> PowOutput {
let account_id = account_id.to_string();
let mut solutions = Vec::with_capacity(self.puzzles.into());
for puzzle in 0..self.puzzles {
let mut candidate = 0u128;
loop {
let mut hasher = Sha256::new();
hasher.update(self.nonce.to_be_bytes());
hasher.update(&account_id);
hasher.update(candidate.to_be_bytes());
hasher.update(puzzle.to_be_bytes());
let hash = hasher.finalize();
if is_solution(self.difficulty, hash.as_ref()) {
solutions.push(candidate);
break;
}
candidate = candidate.wrapping_add(1);
}
}
PowOutput {
solutions,
nonce: self.nonce,
}
}
}

fn is_solution(difficulty: u8, hash: &[u8; 32]) -> bool {
let mut difficulty: u32 = difficulty.into();
for chunk in hash.as_chunks::<8>().0 {
let chunk = u64::from_be_bytes(*chunk);
let chunk_zeros = chunk.leading_zeros();
if chunk_zeros >= difficulty {
return true;
}
if chunk_zeros < 64 {
return false;
}
difficulty -= 64;
}
true
}
5 changes: 3 additions & 2 deletions src/token.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::pow::PowOutput;
use crate::types::AccountId;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::types::AccountId;

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UrlOverride {
pub api: String,
Expand All @@ -18,6 +18,7 @@ pub struct AcquireToken2Output {
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AcquireToken {
pub account_id: AccountId,
pub pow: Option<PowOutput>,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Expand this or at least add a doc comment.

}

impl AcquireToken {
Expand Down
4 changes: 2 additions & 2 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ pub struct WgPubkey(#[serde_as(as = "Base64")] pub [u8; WG_PUBKEY_LENGTH]);

impl std::fmt::Debug for WgPubkey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
use base64::{engine::general_purpose::STANDARD, Engine as _};
use base64::{Engine as _, engine::general_purpose::STANDARD};
f.debug_tuple("WgPubKey").field(&STANDARD.encode(self.0)).finish()
}
}
Expand All @@ -260,7 +260,7 @@ pub enum ParseWgPubkeyError {
impl FromStr for WgPubkey {
type Err = ParseWgPubkeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use base64::{engine::general_purpose::STANDARD, Engine as _};
use base64::{Engine as _, engine::general_purpose::STANDARD};
let decoded = STANDARD.decode(s)?;
let bytes = decoded.try_into().map_err(|d: Vec<u8>| ParseWgPubkeyError::InvalidLength(d.len()))?;
Ok(WgPubkey(bytes))
Expand Down
Loading