solari-browser 0.6.2

Rust binding for the Solari Browser platform control plane (sessions, profiles, replays, managed proxy).
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Wire types for the Solari Browser control plane. serde field names match the
//! JSON wire EXACTLY (camelCase where the API is camelCase).

use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};

// ---------------------------------------------------------------------------
// Regions
// ---------------------------------------------------------------------------

/// Supported Solari regions. More coming soon.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SolariRegion {
    /// `https://api.getsolari.com`
    #[default]
    UsWest,
}

impl SolariRegion {
    /// The API base URL this region resolves to.
    pub fn base_url(&self) -> &'static str {
        match self {
            SolariRegion::UsWest => "https://api.getsolari.com",
        }
    }
}

// ---------------------------------------------------------------------------
// Storage state (cookies + localStorage)
// ---------------------------------------------------------------------------

/// Cookie `sameSite` policy, as Playwright spells it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SameSite {
    Strict,
    Lax,
    None,
}

/// One cookie in a [`StorageState`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Cookie {
    pub name: String,
    pub value: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_only: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secure: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub same_site: Option<SameSite>,
}

/// One `localStorage` key/value pair.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LocalStorageEntry {
    pub name: String,
    pub value: String,
}

/// One origin's `localStorage` in a [`StorageState`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StorageOrigin {
    pub origin: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub local_storage: Option<Vec<LocalStorageEntry>>,
}

/// A browser profile's persisted state — Playwright's `storageState` shape.
/// Unknown keys round-trip through [`StorageState::extra`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StorageState {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cookies: Option<Vec<Cookie>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origins: Option<Vec<StorageOrigin>>,
    /// Any additional keys the wire carried (TS index signature).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

// ---------------------------------------------------------------------------
// Managed proxy
// ---------------------------------------------------------------------------

/// Managed proxy tier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProxyTier {
    /// Rotating residential IPs (default).
    Residential,
    /// Fixed ISP IP.
    Static,
    /// Carrier / mobile IPs.
    Mobile,
}

/// Managed proxy egress request.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProxyRequest {
    /// ISO-3166-1 alpha-2, lowercase. Defaults to `"us"` server-side.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    /// Proxy tier. Defaults to [`ProxyTier::Residential`] server-side.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<ProxyTier>,
    /// Pin egress to a specific ASN (e.g. `"20057"` for AT&T Mobility).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub asn: Option<String>,
    /// Sticky-session id (alnum + dash, <=32 chars). Pins the egress IP for
    /// `session_duration` minutes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,
    /// Sticky lifetime in minutes (1-30, default 10). Only with `session`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_duration: Option<u32>,
    /// US-only geo narrowing (e.g. `"california"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    /// US-only city pin (e.g. `"los_angeles"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub city: Option<String>,
}

impl ProxyRequest {
    /// A request pinned to a country code.
    pub fn country(code: impl Into<String>) -> Self {
        ProxyRequest {
            country: Some(code.into()),
            ..Default::default()
        }
    }

    pub fn tier(mut self, tier: ProxyTier) -> Self {
        self.tier = Some(tier);
        self
    }

    pub fn asn(mut self, asn: impl Into<String>) -> Self {
        self.asn = Some(asn.into());
        self
    }

    /// Pin the egress IP under a sticky-session id.
    pub fn session(mut self, id: impl Into<String>) -> Self {
        self.session = Some(id.into());
        self
    }

    pub fn session_duration(mut self, minutes: u32) -> Self {
        self.session_duration = Some(minutes);
        self
    }

    pub fn state(mut self, state: impl Into<String>) -> Self {
        self.state = Some(state.into());
        self
    }

    pub fn city(mut self, city: impl Into<String>) -> Self {
        self.city = Some(city.into());
        self
    }
}

/// What to send as the `proxy` field of `POST /sessions`.
///
/// Mirrors the TS union `string | ProxyRequest | "off" | "smart"`:
///
/// ```
/// # use solari_browser::{ProxySpec, ProxyRequest, ProxyTier};
/// ProxySpec::country("us");                                    // proxy: "us"
/// ProxySpec::off();                                            // proxy: "off"
/// ProxySpec::smart();                                          // proxy: "smart"
/// ProxySpec::from(ProxyRequest::country("us").tier(ProxyTier::Static));
/// ```
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum ProxySpec {
    /// A bare string: a country code, or the literals `"off"` / `"smart"`.
    Shorthand(String),
    /// A full egress request object.
    Request(ProxyRequest),
}

impl ProxySpec {
    /// Shorthand country pin, e.g. `ProxySpec::country("gb")`.
    pub fn country(code: impl Into<String>) -> Self {
        ProxySpec::Shorthand(code.into())
    }

    /// Explicitly disable managed proxy egress (`proxy: "off"`).
    pub fn off() -> Self {
        ProxySpec::Shorthand("off".to_string())
    }

    /// Let the gateway sweep proxy strategies on block (`proxy: "smart"`).
    pub fn smart() -> Self {
        ProxySpec::Shorthand("smart".to_string())
    }
}

impl From<ProxyRequest> for ProxySpec {
    fn from(r: ProxyRequest) -> Self {
        ProxySpec::Request(r)
    }
}

/// Coarse confirmation of the proxy the gateway resolved for a session.
///
/// Carries NO credentials by design: egress is applied server-side (the pool
/// attaches the upstream to your session), so a caller never dials the proxy
/// and never needs its address or account.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolvedProxyConfig {
    pub timezone_id: String,
    pub country: String,
    #[serde(default)]
    pub tier: Option<ProxyTier>,
}

/// `GET /proxy/countries` — supported egress countries, plus whether the
/// gateway actually has residential credentials configured.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ProxyCountries {
    /// False when this gateway has no residential proxy credentials — sending a
    /// `proxy` spec will fail.
    #[serde(default)]
    pub enabled: bool,
    /// Supported ISO-3166-1 alpha-2 country codes, lowercase.
    #[serde(default)]
    pub countries: Vec<String>,
}

// ---------------------------------------------------------------------------
// Sessions
// ---------------------------------------------------------------------------

/// A live browser session.
///
/// `Debug` hides the path and query of the endpoints: they carry the session's credential.
#[derive(Clone)]
pub struct Session {
    pub id: String,
    /// Playwright wire-protocol endpoint (upstream, as returned by the API).
    pub ws_endpoint: String,
    /// Raw CDP endpoint — for `chromiumoxide` / Puppeteer. Derived from
    /// `ws_endpoint` when the API does not return one.
    pub cdp_endpoint: String,
    /// Plan-tier deadline (ISO 8601 UTC); the session auto-releases at this point.
    pub expires_at: String,
    /// Three-state, mirroring the TS `storageState?: StorageState | null`:
    /// - `None` — no profile attached to this session.
    /// - `Some(None)` — a profile is attached but has no saved state yet.
    /// - `Some(Some(state))` — the profile's state.
    pub storage_state: Option<Option<StorageState>>,
    /// Present only when a managed proxy was requested.
    pub proxy: Option<ResolvedProxyConfig>,
    /// Echo of the `user_metadata` sent at create; `None` when none was sent.
    pub user_metadata: Option<Map<String, Value>>,
}

impl std::fmt::Debug for Session {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Session")
            .field("id", &"<redacted>")
            .field("ws_endpoint", &crate::http::redact_url(&self.ws_endpoint))
            .field("cdp_endpoint", &crate::http::redact_url(&self.cdp_endpoint))
            .field("expires_at", &self.expires_at)
            .field("storage_state", &self.storage_state)
            .field("proxy", &self.proxy)
            .field("user_metadata", &self.user_metadata)
            .finish()
    }
}

/// `GET /sessions/:id`. Fields the gateway adds later land in [`SessionView::extra`].
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionView {
    /// The session id (the same composite id `Sessions::create` returned).
    #[serde(default)]
    pub id: Option<String>,
    /// Older pool-proxied payloads used this key instead of `id`.
    #[serde(default)]
    pub session_id: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    /// Pool flavour that served the session (`"fast"` or `"stealth"`).
    #[serde(default)]
    pub kind: Option<String>,
    /// Owning organisation id.
    #[serde(default)]
    pub org: Option<String>,
    #[serde(default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub expires_at: Option<String>,
    /// What was sent as `user_metadata` at create; `None` when none was.
    #[serde(default)]
    pub user_metadata: Option<Map<String, Value>>,
    /// Present while the session is active.
    #[serde(default)]
    pub ws_endpoint: Option<String>,
    #[serde(default)]
    pub cdp_endpoint: Option<String>,
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// One row of [`Sessions::list`](crate::Sessions::list). It never carries the
/// websocket endpoints (they are bearer capabilities): use `Sessions::get`.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionSummary {
    pub id: String,
    #[serde(default)]
    pub status: String,
    #[serde(default)]
    pub kind: Option<String>,
    #[serde(default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub expires_at: Option<String>,
    #[serde(default)]
    pub user_metadata: Option<Map<String, Value>>,
}

/// One page of [`Sessions::list`](crate::Sessions::list).
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionList {
    #[serde(default)]
    pub sessions: Vec<SessionSummary>,
    /// `None` on the last page; pass it as `ListSessionsOptions::cursor`.
    #[serde(default)]
    pub next_cursor: Option<String>,
}

/// Presigned URL for a session's replay.
#[derive(Debug, Clone)]
pub struct ReplayUrl {
    pub url: String,
    /// Lifetime of the presigned URL. `0` when the API omits it.
    pub expires_in_seconds: u64,
    /// Content encoding of the object behind `url`. `"gzip"` when omitted.
    pub content_encoding: String,
}

// ---------------------------------------------------------------------------
// Profiles
// ---------------------------------------------------------------------------

/// A stored browser profile (cookies + localStorage).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
    pub id: String,
    #[serde(default)]
    pub name: String,
    /// Increases on every save. 0 when the gateway omits it.
    #[serde(default)]
    pub version: u64,
    /// Any additional keys the wire carried (TS index signature).
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// Result of `POST /profiles/:id/save`.
#[derive(Debug, Clone, Default)]
pub struct ProfileSaveResult {
    /// Monotonic version of the saved state. `0` when the API omits it.
    pub version: u64,
    /// Size of the saved state in bytes. `0` when the API omits it.
    pub size_bytes: u64,
}

// ---------------------------------------------------------------------------
// Internal wire shapes
// ---------------------------------------------------------------------------

/// Wire body for `POST /sessions`. Falsy/unset fields are omitted; when every
/// field is omitted the request is sent with no body at all.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CreateSessionRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    #[serde(skip_serializing_if = "is_false")]
    pub recording: bool,
    #[serde(skip_serializing_if = "is_false")]
    pub stealth: bool,
    #[serde(skip_serializing_if = "is_false")]
    pub captcha: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proxy: Option<ProxySpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<u32>,
    #[serde(skip_serializing_if = "is_false")]
    pub keep_alive: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_metadata: Option<Map<String, Value>>,
}

fn is_false(b: &bool) -> bool {
    !*b
}

/// Presigned pointer to a profile's storage state, returned on session create.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct StorageStateUrl {
    #[serde(default)]
    pub url: Option<String>,
    #[allow(dead_code)]
    #[serde(default)]
    pub expires_in_seconds: Option<u64>,
}

/// `201` response from `POST /sessions`.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CreateSessionResponse {
    #[serde(default)]
    pub session_id: Option<String>,
    #[serde(default)]
    pub ws_endpoint: Option<String>,
    #[serde(default)]
    pub cdp_endpoint: Option<String>,
    #[serde(default)]
    pub expires_at: Option<String>,
    /// Absent vs explicit `null` are distinguished.
    #[serde(default, deserialize_with = "double_option")]
    pub storage_state_url: Option<Option<StorageStateUrl>>,
    /// Legacy inline state, for gateways that predate `storageStateUrl`.
    #[serde(default, deserialize_with = "double_option")]
    pub storage_state: Option<Option<StorageState>>,
    #[serde(default)]
    pub proxy: Option<ResolvedProxyConfig>,
    #[serde(default)]
    pub user_metadata: Option<Map<String, Value>>,
}

/// `GET /sessions/:id/replay-url`.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ReplayUrlResponse {
    #[serde(default)]
    pub url: Option<String>,
    #[serde(default)]
    pub expires_in_seconds: Option<u64>,
    #[serde(default)]
    pub content_encoding: Option<String>,
}

/// `POST /profiles/:id/save`.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ProfileSaveResponse {
    #[serde(default)]
    pub version: Option<u64>,
    #[serde(default)]
    pub size_bytes: Option<u64>,
}

/// Distinguish "key absent" (`None`) from "key present and null" (`Some(None)`).
/// Requires `#[serde(default)]` alongside it.
fn double_option<'de, T, D>(de: D) -> Result<Option<Option<T>>, D::Error>
where
    T: serde::Deserialize<'de>,
    D: Deserializer<'de>,
{
    serde::Deserialize::deserialize(de).map(Some)
}

// ---------------------------------------------------------------------------

#[cfg(test)]
mod resolved_proxy_tests {
    use super::*;

    /// REGRESSION GUARD for the shipped fix: the resolved-proxy type carries NO
    /// credentials.
    ///
    /// `ResolvedProxyConfig` used to carry `server`/`username`/`password`. The
    /// gateway stopped sending them (they disclose the proxy vendor's account),
    /// so this binding deserialized empty strings forever — a contract that was
    /// not merely dead but misleading: a caller could read `proxy.server`, get
    /// `""`, and conclude no proxy was applied.
    ///
    /// Rust has no reflection, so the field set is read back out of the derived
    /// `Debug` output. That is exactly the surface that matters anyway: whatever
    /// `{:?}` prints is what ends up in somebody's log.
    fn debug_field_names(dbg: &str) -> Vec<String> {
        let inner = dbg
            .split_once('{')
            .and_then(|(_, rest)| rest.rsplit_once('}'))
            .map(|(inner, _)| inner)
            .unwrap_or("");
        let mut names = Vec::new();
        let mut depth = 0usize;
        for part in inner.split(',') {
            // Only split on top-level commas (Some(..) / nested braces).
            if depth == 0 {
                if let Some((name, _)) = part.split_once(':') {
                    let name = name.trim();
                    if !name.is_empty() {
                        names.push(name.to_string());
                    }
                }
            }
            depth += part.matches(['(', '{', '[']).count();
            depth = depth.saturating_sub(part.matches([')', '}', ']']).count());
        }
        names
    }

    #[test]
    fn resolved_proxy_config_has_exactly_the_confirmation_fields() {
        let wire = r#"{"timezoneId":"America/Los_Angeles","country":"us","tier":"mobile"}"#;
        let rp: ResolvedProxyConfig = serde_json::from_str(wire).unwrap();

        let names = debug_field_names(&format!("{rp:?}"));
        assert_eq!(
            names,
            vec!["timezone_id", "country", "tier"],
            "ResolvedProxyConfig must stay a COARSE CONFIRMATION: egress is applied \
             server-side, so a caller never dials the proxy and must never receive \
             its address or account. Got: {names:?}"
        );
    }

    #[test]
    fn legacy_credential_keys_are_dropped_not_resurrected() {
        let wire = r#"{
            "timezoneId":"America/Los_Angeles",
            "country":"us",
            "tier":"mobile",
            "server":"http://resi.vendor.example:8000",
            "username":"acct-12345",
            "password":"hunter2"
        }"#;
        let rp: ResolvedProxyConfig = serde_json::from_str(wire).unwrap();

        assert_eq!(rp.timezone_id, "America/Los_Angeles");
        assert_eq!(rp.country, "us");

        let rendered = format!("{rp:?}");
        for secret in ["resi.vendor.example", "acct-12345", "hunter2", "server", "username", "password"] {
            assert!(
                !rendered.contains(secret),
                "resolved proxy leaks {secret:?}: {rendered}"
            );
        }
    }
}