Skip to main content

vs_engine_webkit/backend/
auth.rs

1//! Auth-blob schema and JSON codec shared across backends.
2//!
3//! v1 (shipped through v0.1.1) was a JSON object with `cookies` as a
4//! single `document.cookie`-style string. JavaScript's `document.cookie`
5//! API cannot see or write cookies marked `HttpOnly`; the bug report
6//! at v0.1.2 was that every modern web app's auth cookie silently
7//! dropped on save and load.
8//!
9//! v2 carries cookies as a structured array. The per-backend code now
10//! reads and writes those via the host-side cookie store
11//! (`WKHTTPCookieStore` on macOS, `WebKitCookieManager` on Linux,
12//! `ICoreWebView2CookieManager` on Windows), which sees `HttpOnly`
13//! cookies because the attribute hides them from JS, not from the
14//! engine. `localStorage` and `sessionStorage` are still pulled and
15//! pushed via the JS shim; those buckets are JS-accessible by design.
16//!
17//! Loaders accept both v1 and v2 so saved blobs from v0.1.1 (no
18//! `HttpOnly` cookies in them anyway) still round-trip.
19
20use serde::{Deserialize, Serialize};
21
22use crate::engine::{AuthBlob, EngineError, EngineResult};
23
24/// On-wire representation of one cookie. Field names use snake_case
25/// for the JSON; the engines convert to and from their native cookie
26/// types.
27#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
28pub struct CookieData {
29    pub name: String,
30    pub value: String,
31    pub domain: String,
32    pub path: String,
33    /// Seconds-since-epoch expiration. `None` means a session cookie
34    /// (`Discard` in NSHTTPCookie / no `expires` attribute).
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub expires_unix: Option<i64>,
37    #[serde(default)]
38    pub secure: bool,
39    #[serde(default)]
40    pub http_only: bool,
41    /// `Strict` / `Lax` / `None`. `None` here means "absent in source";
42    /// most engines treat that as Lax under modern defaults.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub same_site: Option<String>,
45}
46
47#[derive(Debug, Default, Clone, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub struct AuthBlobV2 {
50    /// Schema version. Always `2` on save in v0.1.2+.
51    pub version: u32,
52    /// URL the blob was captured against. Informational; loaders do
53    /// not consult it.
54    #[serde(default)]
55    pub url: String,
56    #[serde(default)]
57    pub origin: String,
58    #[serde(default)]
59    pub cookies: Vec<CookieData>,
60    #[serde(default, rename = "localStorage")]
61    pub local_storage: std::collections::BTreeMap<String, String>,
62    #[serde(default, rename = "sessionStorage")]
63    pub session_storage: std::collections::BTreeMap<String, String>,
64    /// IndexedDB contents, captured per database. Sites that keep the
65    /// session there (Firebase, Supabase, anything using a local-first
66    /// store) are not restorable from cookies and web storage alone.
67    #[serde(default, rename = "indexedDb", skip_serializing_if = "Vec::is_empty")]
68    pub indexed_db: Vec<IdbDatabase>,
69    /// Records the capture could not carry (see `idb_save.js`). Kept
70    /// in the blob so a restore can say what it is missing instead of
71    /// looking complete.
72    #[serde(
73        default,
74        rename = "indexedDbSkipped",
75        skip_serializing_if = "u32_is_zero"
76    )]
77    pub indexed_db_skipped: u32,
78    /// The capture ran out of budget with databases still unread, so
79    /// this blob is missing some. Kept out of the JSON when false.
80    #[serde(
81        default,
82        rename = "indexedDbIncomplete",
83        skip_serializing_if = "not_set"
84    )]
85    pub indexed_db_incomplete: bool,
86}
87
88#[allow(clippy::trivially_copy_pass_by_ref)] // serde requires &T here
89fn u32_is_zero(n: &u32) -> bool {
90    *n == 0
91}
92
93#[allow(clippy::trivially_copy_pass_by_ref)] // serde requires &T here
94fn not_set(b: &bool) -> bool {
95    !*b
96}
97
98/// One IndexedDB database, as captured from an origin.
99#[derive(Debug, Default, Clone, Serialize, Deserialize)]
100pub struct IdbDatabase {
101    pub name: String,
102    #[serde(default)]
103    pub version: u32,
104    #[serde(default)]
105    pub stores: Vec<IdbStore>,
106}
107
108/// One object store and its records. `key_path` is absent for an
109/// out-of-line store, where each record carries its own key.
110#[derive(Debug, Default, Clone, Serialize, Deserialize)]
111pub struct IdbStore {
112    pub name: String,
113    #[serde(default, rename = "keyPath")]
114    pub key_path: Option<serde_json::Value>,
115    #[serde(default, rename = "autoIncrement")]
116    pub auto_increment: bool,
117    #[serde(default)]
118    pub records: Vec<IdbRecord>,
119}
120
121#[derive(Debug, Default, Clone, Serialize, Deserialize)]
122pub struct IdbRecord {
123    #[serde(default)]
124    pub key: serde_json::Value,
125    #[serde(default)]
126    pub value: serde_json::Value,
127}
128
129/// v1 shape kept for back-compat parsing. We never write v1.
130#[derive(Debug, Deserialize)]
131struct AuthBlobV1Raw {
132    #[serde(default)]
133    cookies: String,
134    #[serde(default, rename = "localStorage")]
135    local_storage: std::collections::BTreeMap<String, String>,
136    #[serde(default, rename = "sessionStorage")]
137    session_storage: std::collections::BTreeMap<String, String>,
138    #[serde(default)]
139    url: String,
140    #[serde(default)]
141    origin: String,
142}
143
144/// Validate and canonicalize an externally-supplied auth blob (the
145/// `vs auth import` path). Parses it — accepting a v1 or v2 JSON body —
146/// and re-encodes as a canonical v2 blob, so an imported session from a
147/// human's real browser is stored in exactly the shape `load_auth`
148/// expects. Errors if the bytes are not a valid auth blob.
149pub fn normalize(bytes: &[u8]) -> EngineResult<Vec<u8>> {
150    let blob = decode(&AuthBlob {
151        bytes: bytes.to_vec(),
152    })?;
153    Ok(encode(&blob)?.bytes)
154}
155
156/// Serialize a v2 blob to bytes for at-rest storage.
157pub fn encode(blob: &AuthBlobV2) -> EngineResult<AuthBlob> {
158    let json = serde_json::to_string(blob)
159        .map_err(|e| EngineError::Other(format!("encode auth blob: {e}")))?;
160    Ok(AuthBlob {
161        bytes: json.into_bytes(),
162    })
163}
164
165/// Parse bytes into a v2 blob. Accepts v1 (auto-migrating the
166/// document.cookie string into structured cookies with empty
167/// attributes) and v2 (the modern shape).
168pub fn decode(blob: &AuthBlob) -> EngineResult<AuthBlobV2> {
169    let text = std::str::from_utf8(&blob.bytes)
170        .map_err(|e| EngineError::Other(format!("auth blob not utf8: {e}")))?;
171    let value: serde_json::Value = serde_json::from_str(text)
172        .map_err(|e| EngineError::Other(format!("auth blob json: {e}")))?;
173    // v2: `cookies` is an array. v1: `cookies` is a string.
174    if value
175        .get("cookies")
176        .is_some_and(serde_json::Value::is_array)
177    {
178        return serde_json::from_value(value)
179            .map_err(|e| EngineError::Other(format!("auth blob v2 decode: {e}")));
180    }
181    let v1: AuthBlobV1Raw = serde_json::from_value(value)
182        .map_err(|e| EngineError::Other(format!("auth blob v1 decode: {e}")))?;
183    let cookies = parse_document_cookie_string(&v1.cookies);
184    Ok(AuthBlobV2 {
185        version: 2,
186        url: v1.url,
187        origin: v1.origin,
188        cookies,
189        local_storage: v1.local_storage,
190        session_storage: v1.session_storage,
191        // v1 predates IndexedDB capture; nothing to migrate.
192        indexed_db: Vec::new(),
193        indexed_db_skipped: 0,
194        indexed_db_incomplete: false,
195    })
196}
197
198/// Best-effort parse of a `document.cookie` style string into structured
199/// cookies. v1 only knew name=value pairs; domain/path/attributes are
200/// blank, so on load the engine has to backfill from the page's origin.
201fn parse_document_cookie_string(s: &str) -> Vec<CookieData> {
202    s.split(';')
203        .filter_map(|piece| {
204            let t = piece.trim();
205            if t.is_empty() {
206                return None;
207            }
208            let (name, value) = t.split_once('=').unwrap_or((t, ""));
209            Some(CookieData {
210                name: name.trim().to_string(),
211                value: value.trim().to_string(),
212                domain: String::new(),
213                path: "/".to_string(),
214                expires_unix: None,
215                secure: false,
216                http_only: false,
217                same_site: None,
218            })
219        })
220        .collect()
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn v2_round_trip() {
229        let blob = AuthBlobV2 {
230            version: 2,
231            url: "https://example.com/app".into(),
232            origin: "https://example.com".into(),
233            indexed_db: Vec::new(),
234            indexed_db_skipped: 0,
235            indexed_db_incomplete: false,
236            cookies: vec![CookieData {
237                name: "access_token".into(),
238                value: "abc".into(),
239                domain: "example.com".into(),
240                path: "/".into(),
241                expires_unix: Some(1_800_000_000),
242                secure: true,
243                http_only: true,
244                same_site: Some("Lax".into()),
245            }],
246            local_storage: [("k".to_string(), "v".to_string())].into(),
247            session_storage: std::collections::BTreeMap::new(),
248        };
249        let bytes = encode(&blob).unwrap();
250        let back = decode(&bytes).unwrap();
251        assert_eq!(back.cookies.len(), 1);
252        assert_eq!(back.cookies[0].name, "access_token");
253        assert!(back.cookies[0].http_only);
254        assert_eq!(back.local_storage.get("k").unwrap(), "v");
255    }
256
257    #[test]
258    fn v1_blob_decodes_into_v2_shape() {
259        // v0.1.1 saved this shape — cookies field is a string.
260        let raw = r#"{
261            "version": 1,
262            "url": "https://example.com/",
263            "origin": "https://example.com",
264            "cookies": "session=xyz; pref=dark",
265            "localStorage": {"theme": "dark"},
266            "sessionStorage": {}
267        }"#;
268        let blob = AuthBlob {
269            bytes: raw.as_bytes().to_vec(),
270        };
271        let v2 = decode(&blob).unwrap();
272        assert_eq!(v2.cookies.len(), 2);
273        assert_eq!(v2.cookies[0].name, "session");
274        assert_eq!(v2.cookies[0].value, "xyz");
275        assert!(!v2.cookies[0].http_only, "v1 had no notion of HttpOnly");
276        assert_eq!(v2.local_storage.get("theme").unwrap(), "dark");
277    }
278
279    #[test]
280    fn v1_with_empty_cookies_decodes() {
281        let raw = r#"{"version":1,"cookies":"","localStorage":{},"sessionStorage":{}}"#;
282        let blob = AuthBlob {
283            bytes: raw.as_bytes().to_vec(),
284        };
285        let v2 = decode(&blob).unwrap();
286        assert!(v2.cookies.is_empty());
287    }
288
289    #[test]
290    fn malformed_json_returns_error() {
291        let blob = AuthBlob {
292            bytes: b"not json at all".to_vec(),
293        };
294        let err = decode(&blob).unwrap_err();
295        assert!(format!("{err}").contains("auth blob"));
296    }
297}