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}
65
66/// v1 shape kept for back-compat parsing. We never write v1.
67#[derive(Debug, Deserialize)]
68struct AuthBlobV1Raw {
69    #[serde(default)]
70    cookies: String,
71    #[serde(default, rename = "localStorage")]
72    local_storage: std::collections::BTreeMap<String, String>,
73    #[serde(default, rename = "sessionStorage")]
74    session_storage: std::collections::BTreeMap<String, String>,
75    #[serde(default)]
76    url: String,
77    #[serde(default)]
78    origin: String,
79}
80
81/// Validate and canonicalize an externally-supplied auth blob (the
82/// `vs auth import` path). Parses it — accepting a v1 or v2 JSON body —
83/// and re-encodes as a canonical v2 blob, so an imported session from a
84/// human's real browser is stored in exactly the shape `load_auth`
85/// expects. Errors if the bytes are not a valid auth blob.
86pub fn normalize(bytes: &[u8]) -> EngineResult<Vec<u8>> {
87    let blob = decode(&AuthBlob {
88        bytes: bytes.to_vec(),
89    })?;
90    Ok(encode(&blob)?.bytes)
91}
92
93/// Serialize a v2 blob to bytes for at-rest storage.
94pub fn encode(blob: &AuthBlobV2) -> EngineResult<AuthBlob> {
95    let json = serde_json::to_string(blob)
96        .map_err(|e| EngineError::Other(format!("encode auth blob: {e}")))?;
97    Ok(AuthBlob {
98        bytes: json.into_bytes(),
99    })
100}
101
102/// Parse bytes into a v2 blob. Accepts v1 (auto-migrating the
103/// document.cookie string into structured cookies with empty
104/// attributes) and v2 (the modern shape).
105pub fn decode(blob: &AuthBlob) -> EngineResult<AuthBlobV2> {
106    let text = std::str::from_utf8(&blob.bytes)
107        .map_err(|e| EngineError::Other(format!("auth blob not utf8: {e}")))?;
108    let value: serde_json::Value = serde_json::from_str(text)
109        .map_err(|e| EngineError::Other(format!("auth blob json: {e}")))?;
110    // v2: `cookies` is an array. v1: `cookies` is a string.
111    if value
112        .get("cookies")
113        .is_some_and(serde_json::Value::is_array)
114    {
115        return serde_json::from_value(value)
116            .map_err(|e| EngineError::Other(format!("auth blob v2 decode: {e}")));
117    }
118    let v1: AuthBlobV1Raw = serde_json::from_value(value)
119        .map_err(|e| EngineError::Other(format!("auth blob v1 decode: {e}")))?;
120    let cookies = parse_document_cookie_string(&v1.cookies);
121    Ok(AuthBlobV2 {
122        version: 2,
123        url: v1.url,
124        origin: v1.origin,
125        cookies,
126        local_storage: v1.local_storage,
127        session_storage: v1.session_storage,
128    })
129}
130
131/// Best-effort parse of a `document.cookie` style string into structured
132/// cookies. v1 only knew name=value pairs; domain/path/attributes are
133/// blank, so on load the engine has to backfill from the page's origin.
134fn parse_document_cookie_string(s: &str) -> Vec<CookieData> {
135    s.split(';')
136        .filter_map(|piece| {
137            let t = piece.trim();
138            if t.is_empty() {
139                return None;
140            }
141            let (name, value) = t.split_once('=').unwrap_or((t, ""));
142            Some(CookieData {
143                name: name.trim().to_string(),
144                value: value.trim().to_string(),
145                domain: String::new(),
146                path: "/".to_string(),
147                expires_unix: None,
148                secure: false,
149                http_only: false,
150                same_site: None,
151            })
152        })
153        .collect()
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn v2_round_trip() {
162        let blob = AuthBlobV2 {
163            version: 2,
164            url: "https://example.com/app".into(),
165            origin: "https://example.com".into(),
166            cookies: vec![CookieData {
167                name: "access_token".into(),
168                value: "abc".into(),
169                domain: "example.com".into(),
170                path: "/".into(),
171                expires_unix: Some(1_800_000_000),
172                secure: true,
173                http_only: true,
174                same_site: Some("Lax".into()),
175            }],
176            local_storage: [("k".to_string(), "v".to_string())].into(),
177            session_storage: std::collections::BTreeMap::new(),
178        };
179        let bytes = encode(&blob).unwrap();
180        let back = decode(&bytes).unwrap();
181        assert_eq!(back.cookies.len(), 1);
182        assert_eq!(back.cookies[0].name, "access_token");
183        assert!(back.cookies[0].http_only);
184        assert_eq!(back.local_storage.get("k").unwrap(), "v");
185    }
186
187    #[test]
188    fn v1_blob_decodes_into_v2_shape() {
189        // v0.1.1 saved this shape — cookies field is a string.
190        let raw = r#"{
191            "version": 1,
192            "url": "https://example.com/",
193            "origin": "https://example.com",
194            "cookies": "session=xyz; pref=dark",
195            "localStorage": {"theme": "dark"},
196            "sessionStorage": {}
197        }"#;
198        let blob = AuthBlob {
199            bytes: raw.as_bytes().to_vec(),
200        };
201        let v2 = decode(&blob).unwrap();
202        assert_eq!(v2.cookies.len(), 2);
203        assert_eq!(v2.cookies[0].name, "session");
204        assert_eq!(v2.cookies[0].value, "xyz");
205        assert!(!v2.cookies[0].http_only, "v1 had no notion of HttpOnly");
206        assert_eq!(v2.local_storage.get("theme").unwrap(), "dark");
207    }
208
209    #[test]
210    fn v1_with_empty_cookies_decodes() {
211        let raw = r#"{"version":1,"cookies":"","localStorage":{},"sessionStorage":{}}"#;
212        let blob = AuthBlob {
213            bytes: raw.as_bytes().to_vec(),
214        };
215        let v2 = decode(&blob).unwrap();
216        assert!(v2.cookies.is_empty());
217    }
218
219    #[test]
220    fn malformed_json_returns_error() {
221        let blob = AuthBlob {
222            bytes: b"not json at all".to_vec(),
223        };
224        let err = decode(&blob).unwrap_err();
225        assert!(format!("{err}").contains("auth blob"));
226    }
227}