1use std::path::PathBuf;
4use std::time::SystemTime;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum SameSite {
9 None,
10 Lax,
11 Strict,
12 Unspecified,
13}
14
15#[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 pub expires: Option<SystemTime>,
28}
29
30pub 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 pub fn js(&self) -> &'a crate::js::Context {
52 self.js
53 .expect("HostContext::js is only available inside Builder::setup")
54 }
55
56 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 pub fn dispatcher(&self) -> crate::js::JsDispatcher {
69 crate::js::JsDispatcher::install(self.js())
70 }
71
72 pub fn handle(&self) -> super::Handle {
75 super::Handle { _private: () }
76 }
77
78 pub fn runtime(&self) -> &'a sk_runtime::JsRuntime {
81 self.runtime
82 .expect("HostContext::runtime is only available inside Builder::setup")
83 }
84
85 pub fn surface(&self, name: &str) -> super::SurfaceHandle {
87 sk_tree::surface::surface(name)
88 }
89
90 pub fn on_frame(&self, hook: impl Fn() + 'static) {
94 crate::js::on_frame(hook);
95 }
96
97 pub fn on_reload(&self, hook: impl Fn(&crate::js::Context) + 'static) {
100 crate::js::on_reload(hook);
101 }
102
103 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 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 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}