1use anyhow::{Result, bail, ensure};
2use reqwest::Url;
3use rust_decimal::Decimal;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use sha2::{Digest, Sha256};
7use std::{collections::BTreeMap, fs, path::Path, str::FromStr};
8
9include!(concat!(env!("OUT_DIR"), "/providers.rs"));
10
11#[derive(Clone, Deserialize, Serialize)]
12#[serde(deny_unknown_fields)]
13pub struct Provider {
14 pub id: String,
15 pub name: String,
16 pub base_url: String,
17 #[serde(default)]
18 pub path: String,
19 #[serde(default, skip_serializing_if = "RequestMethod::is_get")]
20 pub method: RequestMethod,
21 pub unsupported_reason: Option<String>,
22 #[serde(default)]
23 pub auth: Auth,
24 pub key_url: String,
25 pub billing_url: String,
26 pub credential_help: String,
27 pub source: String,
28 #[serde(default)]
29 pub experimental: bool,
30 pub balance: Option<BalanceMap>,
31 #[serde(default, skip_serializing_if = "Vec::is_empty")]
32 pub response_checks: Vec<ResponseCheck>,
33 #[serde(default)]
34 pub quotas: Vec<QuotaMap>,
35}
36#[derive(Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
37#[serde(rename_all = "UPPERCASE")]
38pub enum RequestMethod {
39 #[default]
40 Get,
41 Post,
42}
43impl RequestMethod {
44 pub fn is_get(&self) -> bool {
45 *self == Self::Get
46 }
47}
48impl From<RequestMethod> for reqwest::Method {
49 fn from(method: RequestMethod) -> Self {
50 match method {
51 RequestMethod::Get => Self::GET,
52 RequestMethod::Post => Self::POST,
53 }
54 }
55}
56#[derive(Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
57#[serde(rename_all = "snake_case")]
58pub enum ResetFormat {
59 #[default]
60 Text,
61 UnixSeconds,
62 UnixMilliseconds,
63}
64impl ResetFormat {
65 pub fn is_text(&self) -> bool {
66 *self == Self::Text
67 }
68}
69
70#[derive(Clone, Deserialize, Serialize)]
71#[serde(default, deny_unknown_fields)]
72pub struct Auth {
73 pub header: String,
74 pub prefix: String,
75}
76impl Default for Auth {
77 fn default() -> Self {
78 Self {
79 header: "Authorization".into(),
80 prefix: "Bearer ".into(),
81 }
82 }
83}
84
85#[derive(Clone, Deserialize, Serialize)]
86#[serde(deny_unknown_fields)]
87pub struct ResponseCheck {
88 pub path: String,
89 pub equals: Value,
90}
91
92#[derive(Clone, Deserialize, Serialize)]
93#[serde(deny_unknown_fields)]
94pub struct BalanceMap {
95 pub rows: String,
96 pub currency: Option<String>,
97 pub currency_path: Option<String>,
98 pub remaining: Option<String>,
99 pub total: Option<String>,
100 pub used: Option<String>,
101}
102#[derive(Clone, Deserialize, Serialize)]
103#[serde(deny_unknown_fields)]
104pub struct QuotaMap {
105 pub label: String,
106 pub percent: Option<String>,
107 #[serde(skip_serializing_if = "Option::is_none")]
108 pub used: Option<String>,
109 #[serde(skip_serializing_if = "Option::is_none")]
110 pub limit: Option<String>,
111 #[serde(skip_serializing_if = "Option::is_none")]
112 pub unit: Option<String>,
113 pub reset_at: Option<String>,
114 #[serde(default, skip_serializing_if = "ResetFormat::is_text")]
115 pub reset_format: ResetFormat,
116 #[serde(skip_serializing_if = "Option::is_none")]
117 pub unavailable_when: Option<String>,
118}
119#[derive(Clone, Deserialize, Serialize, Debug, PartialEq)]
120pub struct Balance {
121 pub currency: String,
122 pub remaining: String,
123 pub used: Option<String>,
124}
125#[derive(Clone, Deserialize, Serialize, Debug, PartialEq)]
126pub struct Quota {
127 pub label: String,
128 pub used: Option<String>,
129 pub limit: Option<String>,
130 pub unit: Option<String>,
131 pub used_percent: Option<String>,
132 pub reset_at: Option<String>,
133}
134#[derive(Clone, Default, Deserialize, Serialize, Debug, PartialEq)]
135pub struct AccountData {
136 pub balances: Vec<Balance>,
137 pub quotas: Vec<Quota>,
138}
139pub fn identifier(value: &str) -> bool {
140 !value.is_empty()
141 && value.len() <= 64
142 && value
143 .bytes()
144 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
145}
146fn pointer(value: &str) -> bool {
147 value.is_empty() || value.starts_with('/')
148}
149fn money(value: &Value, path: &str) -> Result<Decimal> {
150 let item = value
151 .pointer(path)
152 .ok_or_else(|| anyhow::anyhow!("required response field missing"))?;
153 let text = match item {
154 Value::String(s) => s.clone(),
155 Value::Number(n) => n.to_string(),
156 _ => bail!("expected a decimal response field"),
157 };
158 Decimal::from_str(&text).map_err(|_| anyhow::anyhow!("invalid decimal response field"))
159}
160impl Provider {
161 pub fn fingerprint(&self) -> String {
162 format!(
163 "{:x}",
164 Sha256::digest(serde_json::to_vec(self).expect("serializable provider"))
165 )
166 }
167 pub fn endpoint(&self, allow_local_http: bool) -> Result<Url> {
168 let base = Url::parse(&self.base_url)?;
169 ensure!(
170 base.username().is_empty()
171 && base.password().is_none()
172 && base.query().is_none()
173 && base.fragment().is_none(),
174 "provider URL must not contain credentials, query or fragment"
175 );
176 let local = matches!(base.host_str(), Some("127.0.0.1" | "[::1]"));
177 ensure!(
178 base.scheme() == "https" || (allow_local_http && local && base.scheme() == "http"),
179 "providers require HTTPS; local fixture HTTP needs --allow-local-http"
180 );
181 ensure!(
182 self.path.starts_with('/') && !self.path.starts_with("//"),
183 "provider path must be an absolute same-origin path"
184 );
185 let endpoint = base.join(&self.path)?;
186 ensure!(
187 endpoint.origin() == base.origin() && endpoint.fragment().is_none(),
188 "provider request must stay on its origin"
189 );
190 Ok(endpoint)
191 }
192 pub fn validate(&self, allow_local_http: bool) -> Result<()> {
193 ensure!(identifier(&self.id), "invalid provider ID");
194 ensure!(
195 reqwest::header::HeaderName::from_bytes(self.auth.header.as_bytes()).is_ok(),
196 "invalid authentication header name"
197 );
198 ensure!(
199 self.auth.prefix.len() <= 64
200 && self
201 .auth
202 .prefix
203 .bytes()
204 .all(|b| b.is_ascii() && !b.is_ascii_control()),
205 "invalid authentication header prefix"
206 );
207 ensure!(
208 !self.name.is_empty()
209 && self.name.len() <= 80
210 && !self.name.chars().any(char::is_control),
211 "invalid provider name"
212 );
213 if self.unsupported_reason.is_none() {
214 self.endpoint(allow_local_http)?;
215 } else {
216 ensure!(
217 self.path.is_empty()
218 && self.balance.is_none()
219 && self.quotas.is_empty()
220 && self.method.is_get(),
221 "unsupported providers must not declare request mappings"
222 );
223 }
224 for link in [&self.key_url, &self.billing_url] {
225 let url = Url::parse(link)?;
226 ensure!(
227 url.scheme() == "https" && url.username().is_empty() && url.password().is_none(),
228 "console links must be HTTPS without credentials"
229 );
230 }
231 ensure!(
232 self.unsupported_reason.is_some() || self.balance.is_some() || !self.quotas.is_empty(),
233 "provider has no account-data mapping"
234 );
235 ensure!(self.response_checks.len() <= 8, "too many response checks");
236 for check in &self.response_checks {
237 ensure!(
238 pointer(&check.path)
239 && matches!(
240 check.equals,
241 Value::String(_) | Value::Number(_) | Value::Bool(_)
242 ),
243 "response checks require a pointer and scalar expected value"
244 );
245 }
246 ensure!(self.quotas.len() <= 16, "too many quota mappings");
247 if let Some(map) = &self.balance {
248 ensure!(pointer(&map.rows), "invalid rows JSON pointer");
249 ensure!(
250 map.currency.is_some() ^ map.currency_path.is_some(),
251 "choose currency or currency_path"
252 );
253 ensure!(
254 map.remaining.is_some() || (map.total.is_some() && map.used.is_some()),
255 "balance needs remaining or total and used"
256 );
257 for field in [&map.currency_path, &map.remaining, &map.total, &map.used]
258 .into_iter()
259 .flatten()
260 {
261 ensure!(pointer(field), "invalid balance JSON pointer");
262 }
263 }
264 for quota in &self.quotas {
265 ensure!(
266 !quota.label.is_empty()
267 && quota.label.len() <= 40
268 && !quota.label.chars().any(char::is_control),
269 "invalid quota label"
270 );
271 ensure!(
272 quota.used.is_some() == quota.limit.is_some(),
273 "quota used/limit must be paired"
274 );
275 ensure!(
276 quota.percent.is_some() || quota.used.is_some(),
277 "quota requires percent or used/limit"
278 );
279 ensure!(
280 quota.unit.as_ref().is_none_or(|unit| !unit.is_empty()
281 && unit.len() <= 24
282 && unit.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')),
283 "invalid quota unit"
284 );
285 ensure!(
286 quota.used.is_none() || quota.unit.is_some(),
287 "absolute quotas require an explicit unit"
288 );
289 for path in [
290 "a.percent,
291 "a.used,
292 "a.limit,
293 "a.reset_at,
294 "a.unavailable_when,
295 ]
296 .into_iter()
297 .flatten()
298 {
299 ensure!(pointer(path), "invalid quota JSON pointer");
300 }
301 }
302 Ok(())
303 }
304 pub fn extract(&self, value: &Value) -> Result<AccountData> {
305 for check in &self.response_checks {
306 ensure!(
307 value.pointer(&check.path) == Some(&check.equals),
308 "provider response check failed"
309 );
310 }
311 let mut result = AccountData::default();
312 if let Some(map) = &self.balance {
313 let rows = value
314 .pointer(&map.rows)
315 .ok_or_else(|| anyhow::anyhow!("balance data missing"))?;
316 let rows: Vec<&Value> = match rows {
317 Value::Object(_) => vec![rows],
318 Value::Array(rows) => rows.iter().collect(),
319 _ => bail!("balance rows must be object or array"),
320 };
321 ensure!(
322 !rows.is_empty() && rows.len() <= 32,
323 "missing or excessive balance rows"
324 );
325 for row in rows {
326 let currency = match &map.currency {
327 Some(c) => c.clone(),
328 None => row
329 .pointer(map.currency_path.as_ref().unwrap())
330 .and_then(Value::as_str)
331 .ok_or_else(|| anyhow::anyhow!("currency missing"))?
332 .to_owned(),
333 };
334 ensure!(
335 !currency.is_empty()
336 && currency.len() <= 8
337 && currency.bytes().all(|b| b.is_ascii_uppercase()),
338 "invalid currency"
339 );
340 let remaining = match &map.remaining {
341 Some(p) => money(row, p)?,
342 None => money(row, map.total.as_ref().unwrap())?
343 .checked_sub(money(row, map.used.as_ref().unwrap())?)
344 .ok_or_else(|| anyhow::anyhow!("balance arithmetic overflow"))?,
345 };
346 let used = map
347 .used
348 .as_ref()
349 .map(|p| money(row, p).map(|n| n.normalize().to_string()))
350 .transpose()?;
351 result.balances.push(Balance {
352 currency,
353 remaining: remaining.normalize().to_string(),
354 used,
355 });
356 }
357 }
358 for quota in &self.quotas {
359 let optional_number = |path: &Option<String>| -> Result<Option<Decimal>> {
361 match path {
362 Some(path) if value.pointer(path).is_some_and(|v| !v.is_null()) => {
363 let number = money(value, path)?;
364 ensure!(number >= Decimal::ZERO, "negative quota counter");
365 Ok(Some(number))
366 }
367 _ => Ok(None),
368 }
369 };
370 let unavailable = match quota
371 .unavailable_when
372 .as_ref()
373 .and_then(|path| value.pointer(path))
374 {
375 None | Some(Value::Null) => false,
376 Some(Value::Bool(value)) => *value,
377 _ => bail!("quota unavailable flag must be boolean"),
378 };
379 let used = if unavailable {
380 None
381 } else {
382 optional_number("a.used)?
383 };
384 let limit = optional_number("a.limit)?;
385 let percent = if unavailable {
386 None
387 } else if quota.percent.is_some() {
388 optional_number("a.percent)?
389 } else if let (Some(used), Some(limit)) = (used, limit) {
390 if limit.is_zero() {
391 None
392 } else {
393 Some(
394 used.checked_div(limit)
395 .and_then(|v| v.checked_mul(Decimal::from(100)))
396 .ok_or_else(|| anyhow::anyhow!("quota arithmetic overflow"))?,
397 )
398 }
399 } else {
400 None
401 };
402 let used_percent = percent.map(|p| p.normalize().to_string());
403 let raw_reset = quota.reset_at.as_ref().and_then(|path| value.pointer(path));
404 let reset_at = if unavailable {
405 None
406 } else {
407 match raw_reset {
408 None | Some(Value::Null) => None,
409 Some(value) => Some(match quota.reset_format {
410 ResetFormat::Text => value
411 .as_str()
412 .ok_or_else(|| anyhow::anyhow!("reset must be text"))?
413 .to_owned(),
414 format => {
415 let timestamp = value
416 .as_i64()
417 .or_else(|| value.as_str().and_then(|v| v.parse().ok()))
418 .ok_or_else(|| {
419 anyhow::anyhow!("reset must be integer epoch time")
420 })?;
421 ensure!(timestamp >= 0, "reset epoch time must be nonnegative");
422 let date = if format == ResetFormat::UnixMilliseconds {
423 chrono::DateTime::from_timestamp_millis(timestamp)
424 } else {
425 chrono::DateTime::from_timestamp(timestamp, 0)
426 }
427 .ok_or_else(|| anyhow::anyhow!("reset epoch time out of range"))?;
428 date.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
429 }
430 }),
431 }
432 };
433 ensure!(
434 reset_at
435 .as_ref()
436 .is_none_or(|s| s.len() <= 64 && !s.chars().any(char::is_control)),
437 "invalid quota reset field"
438 );
439 result.quotas.push(Quota {
440 label: quota.label.clone(),
441 used: used.map(|n| n.normalize().to_string()),
442 limit: limit.map(|n| n.normalize().to_string()),
443 unit: quota.unit.clone(),
444 used_percent,
445 reset_at,
446 });
447 }
448 ensure!(
449 !result.balances.is_empty()
450 || result
451 .quotas
452 .iter()
453 .any(|q| q.used_percent.is_some() || q.used.is_some() || q.limit.is_some()),
454 "no supported account data in response"
455 );
456 Ok(result)
457 }
458}
459pub fn providers(directory: &Path, allow_local_http: bool) -> Result<BTreeMap<String, Provider>> {
460 let mut result = BTreeMap::new();
461 for text in BUILTIN_PROVIDERS {
462 let provider: Provider = toml::from_str(text)?;
463 provider.validate(false)?;
464 ensure!(
465 result.insert(provider.id.clone(), provider).is_none(),
466 "duplicate built-in provider ID"
467 );
468 }
469 let mut custom_ids = std::collections::HashSet::new();
470 if directory.exists() {
471 for entry in fs::read_dir(directory)? {
472 let path = entry?.path();
473 if path.extension().is_none_or(|s| s != "toml") {
474 continue;
475 }
476 ensure!(
477 !path.is_symlink() && path.metadata()?.len() <= 65536,
478 "provider file must be a bounded regular file"
479 );
480 let provider: Provider = toml::from_str(&fs::read_to_string(path)?)
481 .map_err(|_| anyhow::anyhow!("invalid custom provider TOML"))?;
482 provider.validate(allow_local_http)?;
483 ensure!(
484 custom_ids.insert(provider.id.clone()),
485 "duplicate custom provider ID"
486 );
487 result.insert(provider.id.clone(), provider);
488 }
489 }
490 Ok(result)
491}