Skip to main content

sk_app/embed/
host_context.rs

1//! Bootstrap services and direct, thread-confined JSC access for an embedding application.
2
3use std::path::PathBuf;
4use std::time::SystemTime;
5
6/// Cookie attributes accepted by the host's HTTP cookie jar.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum SameSite {
9    None,
10    Lax,
11    Strict,
12    Unspecified,
13}
14
15/// A host-provisioned cookie. `url` is its origin; normal HTTP cookie rules apply.
16#[derive(Clone, Debug)]
17pub struct HostCookie {
18    pub url: String,
19    pub name: String,
20    pub value: String,
21    pub domain: Option<String>,
22    pub path: Option<String>,
23    pub secure: bool,
24    pub http_only: bool,
25    pub same_site: SameSite,
26    /// `None` makes this a session cookie.
27    pub expires: Option<SystemTime>,
28}
29
30/// Services available after storage is installed and before any application JS runs.
31/// Cookie and secret operations need the `storages` feature; secrets are sealed by the OS provider, no plaintext fallback.
32pub struct HostContext<'a> {
33    runtime: Option<&'a sk_runtime::JsRuntime>,
34    js: Option<&'a crate::js::Context>,
35    storage_dir: Option<PathBuf>,
36}
37
38impl<'a> HostContext<'a> {
39    pub(super) fn installed(runtime: Option<&'a sk_runtime::JsRuntime>) -> Self {
40        Self {
41            runtime,
42            js: runtime.map(sk_runtime::JsRuntime::ctx),
43            #[cfg(feature = "storages")]
44            storage_dir: sk_storage::cookies::folder(),
45            #[cfg(not(feature = "storages"))]
46            storage_dir: None,
47        }
48    }
49
50    /// Direct JavaScriptCore API; UI/VM thread only.
51    pub fn js(&self) -> &'a crate::js::Context {
52        self.js
53            .expect("HostContext::js is only available inside Builder::setup")
54    }
55
56    /// Installs a native namespace before app code, built with `js.object`, `js.set` and `sk_app::js::function`.
57    pub fn expose(&self, name: &str, value: crate::js::Value) -> crate::js::Result<()> {
58        if name.is_empty()
59            || name.to_ascii_lowercase().starts_with("__sk")
60            || !self.js().global_get(name)?.is_undefined()
61        {
62            return Err(crate::js::Error::BadArg);
63        }
64        self.js().global_set(name, value)
65    }
66
67    /// A bounded worker-to-VM queue. Capture owned Rust data, never JSC values.
68    pub fn dispatcher(&self) -> crate::js::JsDispatcher {
69        crate::js::JsDispatcher::install(self.js())
70    }
71
72    /// The running app's [`super::Handle`], for UI that outlives setup (a tray icon). On macOS it
73    /// is the only way to one: `run_on_main_thread` returns no handle.
74    pub fn handle(&self) -> super::Handle {
75        super::Handle { _private: () }
76    }
77
78    /// The engine's runtime, for an extension built against the same `sk-runtime` that registers
79    /// `__sk_*` host fns, which [`Self::expose`] refuses on purpose. Prefer `expose`.
80    pub fn runtime(&self) -> &'a sk_runtime::JsRuntime {
81        self.runtime
82            .expect("HostContext::runtime is only available inside Builder::setup")
83    }
84
85    /// The surface `<sk-surface name="…">` elements show: present frames to it from any thread.
86    pub fn surface(&self, name: &str) -> super::SurfaceHandle {
87        sk_tree::surface::surface(name)
88    }
89
90    /// Called on the VM thread once per frame before the frame's wave drains: deliver what worker
91    /// threads queued here, so a JS handler never observes a half-applied patch. Keep it bounded;
92    /// it is on the frame's critical path. Runs until shutdown.
93    pub fn on_frame(&self, hook: impl Fn() + 'static) {
94        crate::js::on_frame(hook);
95    }
96
97    /// Called on the VM thread after old-page teardown, before its replacement.
98    /// Clear and unprotect page-owned callbacks here. The namespace remains installed.
99    pub fn on_reload(&self, hook: impl Fn(&crate::js::Context) + 'static) {
100        crate::js::on_reload(hook);
101    }
102
103    /// Called once on the VM thread during orderly shutdown. Release protected callbacks here;
104    /// stopping workers is the embedder's job.
105    pub fn on_shutdown(&self, hook: impl Fn(&crate::js::Context) + 'static) {
106        crate::js::on_shutdown(hook);
107    }
108
109    pub fn storage_dir(&self) -> Result<PathBuf, String> {
110        self.storage_dir.clone().ok_or_else(storage_unavailable)
111    }
112
113    /// Provisions a cookie, including HttpOnly cookies, before the first request.
114    pub fn set_cookie(&self, cookie: HostCookie) -> Result<(), String> {
115        self.storage_dir()?;
116        #[cfg(feature = "storages")]
117        {
118            use sk_runtime::redjs::webapi::cookies as jar;
119            jar::set(jar::HostCookie {
120                url: cookie.url,
121                name: cookie.name,
122                value: cookie.value,
123                domain: cookie.domain,
124                path: cookie.path,
125                secure: cookie.secure,
126                http_only: cookie.http_only,
127                same_site: match cookie.same_site {
128                    SameSite::None => jar::SameSite::None,
129                    SameSite::Lax => jar::SameSite::Lax,
130                    SameSite::Strict => jar::SameSite::Strict,
131                    SameSite::Unspecified => jar::SameSite::Unspecified,
132                },
133                expires: cookie.expires,
134            })
135        }
136        #[cfg(not(feature = "storages"))]
137        {
138            let _ = cookie;
139            Err(storage_unavailable())
140        }
141    }
142
143    pub fn random_bytes(&self, bytes: &mut [u8]) -> Result<(), String> {
144        #[cfg(feature = "storages")]
145        {
146            sk_storage::crypt::random_bytes(bytes)
147        }
148        #[cfg(not(feature = "storages"))]
149        {
150            let _ = bytes;
151            Err(storage_unavailable())
152        }
153    }
154
155    /// Only an absent file returns `Ok(None)`; a corrupt or undecryptable secret is an error.
156    pub fn read_secret(&self, name: &str) -> Result<Option<String>, String> {
157        validate_secret_name(name)?;
158        let folder = self.storage_dir()?;
159        #[cfg(feature = "storages")]
160        {
161            let provider = sk_storage::crypt::provider().ok_or_else(|| {
162                "host secrets: no OS encryption provider on this platform".to_string()
163            })?;
164            let path = folder.join(name);
165            let bytes = match std::fs::read(&path) {
166                Ok(bytes) => bytes,
167                Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
168                Err(e) => return Err(format!("host secrets: could not read {name}: {e}")),
169            };
170            sk_storage::file::unseal(provider, &bytes)
171                .map(Some)
172                .map_err(|e| format!("host secrets: could not decrypt {name}: {e}"))
173        }
174        #[cfg(not(feature = "storages"))]
175        {
176            let _ = folder;
177            Err(storage_unavailable())
178        }
179    }
180
181    pub fn write_secret(&self, name: &str, value: &str) -> Result<(), String> {
182        validate_secret_name(name)?;
183        let folder = self.storage_dir()?;
184        #[cfg(feature = "storages")]
185        {
186            let provider = sk_storage::crypt::provider().ok_or_else(|| {
187                "host secrets: no OS encryption provider on this platform".to_string()
188            })?;
189            let bytes = sk_storage::file::seal(provider, value)?;
190            std::fs::create_dir_all(&folder)
191                .map_err(|e| format!("host secrets: could not create storage directory: {e}"))?;
192            sk_storage::file::write_atomic(&folder.join(name), &bytes)
193                .map_err(|e| format!("host secrets: could not write {name}: {e}"))
194        }
195        #[cfg(not(feature = "storages"))]
196        {
197            let _ = (folder, value);
198            Err(storage_unavailable())
199        }
200    }
201}
202
203fn storage_unavailable() -> String {
204    "host storage services are unavailable: enable sk-app's storages feature and run setup after storage installation".into()
205}
206
207fn validate_secret_name(name: &str) -> Result<(), String> {
208    let stem = name.split('.').next().unwrap_or("").to_ascii_lowercase();
209    let reserved = matches!(stem.as_str(), "con" | "prn" | "aux" | "nul")
210        || (stem.len() == 4
211            && (stem.starts_with("com") || stem.starts_with("lpt"))
212            && matches!(stem.as_bytes()[3], b'1'..=b'9'));
213    if name.is_empty()
214        || name.len() > 128
215        || name == "."
216        || name == ".."
217        || name.ends_with('.')
218        || reserved
219        || !name
220            .bytes()
221            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
222    {
223        return Err(
224            "host secrets: name must be one ordinary filename (letters, digits, '.', '_' or '-')"
225                .into(),
226        );
227    }
228    Ok(())
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn secret_names_cannot_escape_the_storage_directory_or_name_windows_devices() {
237        for name in [
238            "",
239            ".",
240            "..",
241            "../secret",
242            "x/y",
243            r"x\y",
244            "C:secret",
245            "secret:stream",
246            "con",
247            "NUL.sealed",
248            "COM1",
249            "lpt9.txt",
250            "trailing.",
251        ] {
252            assert!(validate_secret_name(name).is_err(), "{name:?}");
253        }
254        assert!(validate_secret_name("device-id.sealed").is_ok());
255    }
256
257    #[test]
258    fn context_without_storage_refuses_credential_operations() {
259        let ctx = HostContext {
260            runtime: None,
261            js: None,
262            storage_dir: None,
263        };
264        assert!(ctx.storage_dir().is_err());
265        assert!(ctx.read_secret("test.sealed").is_err());
266        assert!(ctx.write_secret("test.sealed", "secret").is_err());
267        let cookie = HostCookie {
268            url: "https://host-context.test".into(),
269            name: "bootstrap".into(),
270            value: "value".into(),
271            domain: None,
272            path: Some("/".into()),
273            secure: true,
274            http_only: true,
275            same_site: SameSite::None,
276            expires: None,
277        };
278        assert!(ctx.set_cookie(cookie).is_err());
279        #[cfg(not(feature = "storages"))]
280        assert!(ctx.random_bytes(&mut [0; 8]).is_err());
281    }
282
283    #[test]
284    #[cfg(all(feature = "storages", target_os = "windows"))]
285    fn secrets_preserve_the_existing_sealed_format_and_refuse_corruption() {
286        let folder = std::env::temp_dir().join(format!(
287            "sk-host-secret-{}-{}",
288            std::process::id(),
289            SystemTime::now()
290                .duration_since(SystemTime::UNIX_EPOCH)
291                .unwrap()
292                .as_nanos()
293        ));
294        let ctx = HostContext {
295            runtime: None,
296            js: None,
297            storage_dir: Some(folder.clone()),
298        };
299        let name = "device-id.sealed";
300        assert_eq!(ctx.read_secret(name).unwrap(), None);
301        ctx.write_secret(name, "stable-device-id").unwrap();
302        assert_eq!(
303            ctx.read_secret(name).unwrap().as_deref(),
304            Some("stable-device-id")
305        );
306        let bytes = std::fs::read(folder.join(name)).unwrap();
307        assert!(!bytes.windows(16).any(|b| b == b"stable-device-id"));
308        let provider = sk_storage::crypt::provider().unwrap();
309        assert_eq!(
310            sk_storage::file::unseal(provider, &bytes).unwrap(),
311            "stable-device-id"
312        );
313        let legacy = sk_storage::file::seal(provider, "legacy-device-id").unwrap();
314        std::fs::write(folder.join(name), legacy).unwrap();
315        assert_eq!(
316            ctx.read_secret(name).unwrap().as_deref(),
317            Some("legacy-device-id")
318        );
319        std::fs::write(folder.join(name), b"corrupt").unwrap();
320        assert!(ctx.read_secret(name).is_err());
321        std::fs::remove_file(folder.join(name)).unwrap();
322        std::fs::remove_dir(folder).unwrap();
323    }
324
325    #[test]
326    #[cfg(feature = "storages")]
327    fn generic_cookie_setter_obeys_origin_and_domain_rules() {
328        let ctx = HostContext {
329            runtime: None,
330            js: None,
331            storage_dir: Some(PathBuf::from("unused-cookie-test-folder")),
332        };
333        let mut cookie = HostCookie {
334            url: "https://host-context.test".into(),
335            name: "sk-host-bootstrap-test".into(),
336            value: "value".into(),
337            domain: Some("elsewhere.test".into()),
338            path: Some("/".into()),
339            secure: true,
340            http_only: true,
341            same_site: SameSite::None,
342            expires: None,
343        };
344        assert!(ctx.set_cookie(cookie.clone()).is_err());
345        cookie.domain = None;
346        assert!(ctx.set_cookie(cookie).is_ok());
347        sk_runtime::redjs::webapi::cookies::remove(
348            "https://host-context.test",
349            "sk-host-bootstrap-test",
350        );
351    }
352}