cybertemp 0.1.0

Rust SDK for CyberTemp — disposable email inboxes for testing, automation, OTP flows, and AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! # cybertemp
//!
//! Async Rust SDK for [CyberTemp](https://cybertemp.xyz) — disposable
//! email inboxes for testing, automation, OTP flows, and AI agents.
//!
//! ```no_run
//! use cybertemp::Client;
//! use std::time::Duration;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let client = Client::new("tk_...");
//!     let inbox = client.create_inbox().await?;
//!     let otp = client.wait_for_otp(&inbox.id, Duration::from_secs(30)).await?;
//!     println!("OTP: {otp}");
//!     Ok(())
//! }
//! ```
//!
//! Errors carry full context — when a tier/cap blocks a call you get an
//! `Error::Upgrade` with the same `required_tier` / `upgrade_url`
//! payload the standalone API returns, so you can surface a real CTA.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::collections::HashSet;
use std::time::{Duration, Instant};

use reqwest::{header, Client as Http, Method, Response, StatusCode};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use thiserror::Error;
use tokio::time::sleep;

/// Default base URL for the public CyberTemp API.
pub const DEFAULT_BASE_URL: &str = "https://api.cybertemp.xyz";

/// A disposable inbox.
#[derive(Debug, Clone, Deserialize)]
pub struct Inbox {
    /// Inbox identifier — pass this to subsequent calls.
    pub id: String,
    /// Full email address, e.g. `abc123@cybertemp.xyz`.
    pub address: String,
    /// ISO-8601 creation timestamp.
    #[serde(default)]
    pub created_at: Option<String>,
    /// ISO-8601 expiry timestamp, when retention applies.
    #[serde(default)]
    pub expires_at: Option<String>,
}

/// One message inside an inbox.
#[derive(Debug, Clone, Deserialize)]
pub struct Message {
    /// Message id.
    pub id: String,
    /// Sender address.
    #[serde(alias = "from_addr")]
    pub from: String,
    /// Message subject line.
    pub subject: String,
    /// Plain-text body, if available.
    #[serde(default, alias = "text")]
    pub body_text: Option<String>,
    /// HTML body, if available.
    #[serde(default, alias = "html")]
    pub body_html: Option<String>,
    /// ISO-8601 receive timestamp.
    #[serde(default, alias = "timestamp")]
    pub received_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
struct MessagesList {
    #[serde(default)]
    messages: Vec<Message>,
}

#[derive(Debug, Clone, Deserialize)]
struct InboxesList {
    #[serde(default)]
    inboxes: Vec<Inbox>,
}

/// Optional fields for `create_inbox`.
#[derive(Debug, Default, Clone, Serialize)]
pub struct CreateInboxOptions<'a> {
    /// Custom local part of the address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<&'a str>,
    /// Domain to use (must be one your account has access to).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<&'a str>,
}

/// `{used, limit}` returned on cap-related errors.
#[derive(Debug, Clone, Deserialize)]
pub struct Usage {
    /// Calls used so far this window.
    pub used: i64,
    /// Cap value.
    pub limit: i64,
}

/// SDK error type. Use `matches!` on the variant to handle tier/cap
/// blocks vs. transient rate limits vs. anything else.
#[derive(Debug, Error)]
pub enum Error {
    /// User's plan doesn't include the feature, or they hit a cap.
    #[error("upgrade required ({status}): {message}")]
    Upgrade {
        /// HTTP status (usually 402/403/429).
        status: u16,
        /// Human-readable message from the API.
        message: String,
        /// Trigger key (e.g. `tier_required_otp`).
        trigger: Option<String>,
        /// Tier required to unlock the action.
        required_tier: Option<String>,
        /// URL to send the user to.
        upgrade_url: Option<String>,
        /// Optional contact URL (for Enterprise upsells).
        contact_url: Option<String>,
        /// CTA label suggested by the API.
        cta_label: Option<String>,
        /// `{used, limit}` for cap-related blocks.
        current_usage: Option<Usage>,
        /// Full raw payload.
        payload: Value,
    },
    /// Per-second rate limit. Retry after `retry_after`.
    #[error("rate limited: retry in {retry_after:?}")]
    RateLimited {
        /// Duration the API suggests waiting.
        retry_after: Duration,
        /// Raw payload.
        payload: Value,
    },
    /// Operation timed out (e.g. `wait_for_message` exceeded its budget).
    #[error("timed out after {0:?}")]
    Timeout(Duration),
    /// No OTP code was found in the next message.
    #[error("no OTP found in the latest message ({message_id})")]
    NoOtpFound {
        /// ID of the message that didn't contain a code.
        message_id: String,
    },
    /// Anything else — network errors, unexpected status codes, etc.
    #[error("API error ({status}): {message}")]
    Api {
        /// HTTP status.
        status: u16,
        /// Message from the API or HTTP layer.
        message: String,
        /// Raw payload, if JSON.
        payload: Value,
    },
    /// HTTP / transport error from `reqwest`.
    #[error(transparent)]
    Transport(#[from] reqwest::Error),
}

type Result<T> = std::result::Result<T, Error>;

/// CyberTemp HTTP client.
///
/// Cheap to clone — internally wraps an `Arc<reqwest::Client>`.
#[derive(Debug, Clone)]
pub struct Client {
    http: Http,
    base_url: String,
    api_key: String,
}

impl Client {
    /// Construct a client with the public base URL.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::with_base_url(api_key, DEFAULT_BASE_URL)
    }

    /// Construct a client pointing at a custom base URL (self-hosted /
    /// staging).
    pub fn with_base_url(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
        let api_key = api_key.into();
        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::USER_AGENT,
            header::HeaderValue::from_static("cybertemp-rust/0.1.0"),
        );
        let http = Http::builder()
            .default_headers(headers)
            .timeout(Duration::from_secs(30))
            .build()
            .expect("reqwest client build");
        Self {
            http,
            base_url: base_url.into().trim_end_matches('/').to_string(),
            api_key,
        }
    }

    async fn send(
        &self,
        method: Method,
        path: &str,
        query: &[(&str, String)],
        body: Option<Value>,
    ) -> Result<Option<Value>> {
        let url = format!("{}{}", self.base_url, path);
        let mut req = self
            .http
            .request(method, &url)
            .header("X-API-KEY", &self.api_key)
            .header(header::AUTHORIZATION, format!("Bearer {}", self.api_key));
        if !query.is_empty() {
            req = req.query(query);
        }
        if let Some(b) = body {
            req = req.json(&b);
        }
        let resp = req.send().await?;
        handle_response(resp).await
    }

    /// Allocate a new disposable inbox.
    pub async fn create_inbox(&self) -> Result<Inbox> {
        self.create_inbox_with(&CreateInboxOptions::default()).await
    }

    /// Allocate a new disposable inbox with custom options.
    ///
    /// CyberTemp materialises inboxes lazily — the first `/getMail` call
    /// against an unused address creates it. We pick a domain (caller's
    /// override or the first public one), generate a random local part
    /// if needed, and warm the inbox with a single read.
    pub async fn create_inbox_with(&self, opts: &CreateInboxOptions<'_>) -> Result<Inbox> {
        let domain = match opts.domain {
            Some(d) => d.to_string(),
            None => {
                let raw = self.send(Method::GET, "/getDomains", &[], None).await?;
                let wrap: serde_json::Value = raw.unwrap_or(json!({}));
                wrap.get("domains")
                    .and_then(|v| v.as_array())
                    .and_then(|arr| arr.first())
                    .and_then(|v| v.as_str())
                    .unwrap_or("cybertemp.xyz")
                    .to_string()
            }
        };
        let username = match opts.username {
            Some(u) => u.to_string(),
            None => random_local_part(),
        };
        let address = format!("{username}@{domain}");
        // Warm the inbox.
        let _ = self.read_messages(&address, 1, 0).await?;
        Ok(Inbox {
            id: address.clone(),
            address,
            created_at: None,
            expires_at: None,
        })
    }

    /// List inboxes — the standalone API doesn't expose a per-user list,
    /// inboxes are addressed by their email. Returns an empty vec so
    /// loop-shaped client code still compiles.
    pub async fn list_inboxes(&self) -> Result<Vec<Inbox>> {
        Ok(Vec::new())
    }

    /// Read messages from an inbox. Most recent first.
    pub async fn read_messages(
        &self,
        inbox_id_or_address: &str,
        limit: usize,
        offset: usize,
    ) -> Result<Vec<Message>> {
        let mut q = vec![("email", inbox_id_or_address.to_string())];
        if limit > 0 {
            q.push(("limit", limit.to_string()));
        }
        if offset > 0 {
            q.push(("offset", offset.to_string()));
        }
        let raw = self.send(Method::GET, "/getMail", &q, None).await?;
        let val = raw.unwrap_or(json!({}));
        // Accept either { messages: [...] }, { emails: [...] }, or a bare array.
        if let Some(arr) = val.get("messages").and_then(|v| v.as_array()) {
            return Ok(serde_json::from_value(json!(arr)).map_err(json_err)?);
        }
        if let Some(arr) = val.get("emails").and_then(|v| v.as_array()) {
            return Ok(serde_json::from_value(json!(arr)).map_err(json_err)?);
        }
        Ok(serde_json::from_value(val).unwrap_or_default())
    }

    /// Block until a new message arrives, or `timeout` elapses.
    pub async fn wait_for_message(
        &self,
        inbox_id_or_address: &str,
        timeout: Duration,
    ) -> Result<Message> {
        self.wait_for_message_with(
            inbox_id_or_address,
            timeout,
            Duration::from_secs(2),
            None,
        )
        .await
    }

    /// Like `wait_for_message` but lets you tune the poll interval and
    /// skip messages newer than `since_message_id`.
    pub async fn wait_for_message_with(
        &self,
        inbox_id_or_address: &str,
        timeout: Duration,
        poll_interval: Duration,
        since_message_id: Option<&str>,
    ) -> Result<Message> {
        let poll_interval = poll_interval.max(Duration::from_millis(500));
        let deadline = Instant::now() + timeout;
        let mut seen: HashSet<String> = HashSet::new();
        if let Some(id) = since_message_id {
            seen.insert(id.to_string());
        }
        while Instant::now() < deadline {
            let msgs = self.read_messages(inbox_id_or_address, 5, 0).await?;
            for m in &msgs {
                if !seen.contains(&m.id) {
                    return Ok(m.clone());
                }
            }
            for m in msgs {
                seen.insert(m.id);
            }
            sleep(poll_interval).await;
        }
        Err(Error::Timeout(timeout))
    }

    /// Wait for the next message and extract a 4–8 digit OTP from it.
    ///
    /// Delegates to the server-side `/extract-otp` endpoint (Pro+).
    /// Free / Eco accounts get an `Error::Upgrade` carrying the
    /// upgrade URL.
    pub async fn wait_for_otp(
        &self,
        inbox_id_or_address: &str,
        timeout: Duration,
    ) -> Result<String> {
        let body = json!({
            "inbox": inbox_id_or_address,
            "timeout_seconds": timeout.as_secs(),
        });
        let raw = self
            .send(Method::POST, "/extract-otp", &[], Some(body))
            .await?;
        let val = raw.unwrap_or(json!({}));
        let code = val
            .get("code")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::Api {
                status: 200,
                message: "extract-otp succeeded but no code in response".into(),
                payload: val.clone(),
            })?;
        Ok(code.to_string())
    }

    /// Delete an inbox.
    pub async fn delete_inbox(&self, inbox_id_or_address: &str) -> Result<()> {
        let path = format!("/inbox/{}", urlencode(inbox_id_or_address));
        self.send(Method::DELETE, &path, &[], None).await?;
        Ok(())
    }
}

/// Generate 10 random url-safe characters for an email local part.
fn random_local_part() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
    let mut out = String::with_capacity(10);
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    let mut state = nanos.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
    for _ in 0..10 {
        state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
        out.push(ALPHABET[(state >> 33) as usize % ALPHABET.len()] as char);
    }
    out
}

fn urlencode(s: &str) -> String {
    // Minimal percent-encoding for path components — enough for email
    // addresses (the `@` is the only reserved character we hit).
    s.bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                (b as char).to_string()
            }
            _ => format!("%{b:02X}"),
        })
        .collect()
}

fn json_err(e: serde_json::Error) -> Error {
    Error::Api {
        status: 0,
        message: e.to_string(),
        payload: Value::Null,
    }
}

async fn handle_response(resp: Response) -> Result<Option<Value>> {
    let status = resp.status();
    let retry_after = resp
        .headers()
        .get(header::RETRY_AFTER)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<u64>().ok())
        .map(Duration::from_secs)
        .unwrap_or(Duration::from_secs(1));

    if status == StatusCode::NO_CONTENT {
        return Ok(None);
    }

    let text = resp.text().await?;
    let payload: Value = serde_json::from_str(&text).unwrap_or(Value::Null);

    if status.is_success() {
        return Ok(Some(payload));
    }

    let message = payload
        .get("message")
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .unwrap_or_else(|| format!("HTTP {}", status.as_u16()));

    let trigger = payload
        .get("trigger")
        .and_then(|v| v.as_str())
        .map(str::to_string);

    let is_upgrade_status = matches!(status, StatusCode::FORBIDDEN | StatusCode::PAYMENT_REQUIRED);
    let is_429_upgrade = status == StatusCode::TOO_MANY_REQUESTS
        && matches!(
            trigger.as_deref(),
            Some("rate_limit_daily") | Some("elite_soft_cap")
        );

    if is_upgrade_status || is_429_upgrade {
        return Err(Error::Upgrade {
            status: status.as_u16(),
            message,
            trigger,
            required_tier: payload
                .get("required_tier")
                .and_then(|v| v.as_str())
                .map(str::to_string),
            upgrade_url: payload
                .get("upgrade_url")
                .and_then(|v| v.as_str())
                .map(str::to_string),
            contact_url: payload
                .get("contact_url")
                .and_then(|v| v.as_str())
                .map(str::to_string),
            cta_label: payload
                .get("cta_label")
                .and_then(|v| v.as_str())
                .map(str::to_string),
            current_usage: payload
                .get("current_usage")
                .and_then(|v| serde_json::from_value::<Usage>(v.clone()).ok()),
            payload,
        });
    }

    if status == StatusCode::TOO_MANY_REQUESTS {
        return Err(Error::RateLimited {
            retry_after,
            payload,
        });
    }

    Err(Error::Api {
        status: status.as_u16(),
        message,
        payload,
    })
}