qualia_cooperative_core/qapp_package/
pwa.rs1use serde_json::json;
15
16use super::manifest::QappManifest;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum PwaContent {
21 Text(String),
22 Bytes(Vec<u8>),
23}
24
25impl PwaContent {
26 pub fn as_text(&self) -> Option<&str> {
28 match self {
29 PwaContent::Text(s) => Some(s.as_str()),
30 PwaContent::Bytes(_) => None,
31 }
32 }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct PwaFile {
38 pub path: String,
40 pub content: PwaContent,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct PwaBundle {
47 pub files: Vec<PwaFile>,
48}
49
50impl PwaBundle {
51 pub fn get(&self, path: &str) -> Option<&PwaFile> {
53 self.files.iter().find(|f| f.path == path)
54 }
55
56 pub fn text_of(&self, path: &str) -> Option<&str> {
58 self.get(path).and_then(|f| f.content.as_text())
59 }
60}
61
62fn html_escape(s: &str) -> String {
64 let mut out = String::with_capacity(s.len());
65 for c in s.chars() {
66 match c {
67 '&' => out.push_str("&"),
68 '<' => out.push_str("<"),
69 '>' => out.push_str(">"),
70 '"' => out.push_str("""),
71 '\'' => out.push_str("'"),
72 _ => out.push(c),
73 }
74 }
75 out
76}
77
78fn js_string_escape(s: &str) -> String {
82 let mut out = String::with_capacity(s.len() + 2);
83 for c in s.chars() {
84 match c {
85 '\\' => out.push_str("\\\\"),
86 '\'' => out.push_str("\\'"),
87 '\n' => out.push_str("\\n"),
88 '\r' => out.push_str("\\r"),
89 '\t' => out.push_str("\\t"),
90 '<' => out.push_str("\\x3C"),
91 '>' => out.push_str("\\x3E"),
92 '\u{2028}' => out.push_str("\\u2028"),
93 '\u{2029}' => out.push_str("\\u2029"),
94 _ => out.push(c),
95 }
96 }
97 out
98}
99
100fn cache_name(manifest: &QappManifest) -> String {
103 format!("{}-{}", manifest.id, manifest.version)
104}
105
106fn build_webmanifest(manifest: &QappManifest) -> String {
108 let icons: Vec<serde_json::Value> = manifest
109 .icons
110 .iter()
111 .map(|icon| {
112 json!({
113 "src": icon.src,
114 "sizes": icon.sizes,
115 "type": guess_icon_type(&icon.src),
116 "purpose": icon.purpose,
117 })
118 })
119 .collect();
120
121 let value = json!({
122 "id": manifest.id,
123 "name": manifest.name,
124 "short_name": manifest.short_name,
125 "description": manifest.description,
126 "start_url": ".",
127 "scope": ".",
128 "display": manifest.display,
129 "theme_color": manifest.theme_color,
130 "background_color": manifest.background_color,
131 "icons": icons,
132 });
133
134 serde_json::to_string_pretty(&value).expect("web app manifest is always serializable")
136}
137
138fn guess_icon_type(src: &str) -> &'static str {
140 let lower = src.to_ascii_lowercase();
141 if lower.ends_with(".svg") {
142 "image/svg+xml"
143 } else if lower.ends_with(".webp") {
144 "image/webp"
145 } else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
146 "image/jpeg"
147 } else if lower.ends_with(".ico") {
148 "image/x-icon"
149 } else {
150 "image/png"
151 }
152}
153
154fn build_service_worker(manifest: &QappManifest) -> String {
156 let cache = js_string_escape(&cache_name(manifest));
157
158 let mut precache: Vec<String> = vec![
160 "./".to_string(),
161 "./index.html".to_string(),
162 "./loader.js".to_string(),
163 "./manifest.webmanifest".to_string(),
164 manifest.entry_wasm.path.clone(),
165 ];
166 for icon in &manifest.icons {
167 precache.push(icon.src.clone());
168 }
169 precache.dedup();
170
171 let precache_js = precache
172 .iter()
173 .map(|p| format!(" '{}'", js_string_escape(p)))
174 .collect::<Vec<_>>()
175 .join(",\n");
176
177 format!(
178 "// Auto-generated cache-first service worker for qapp '{cache}'.\n\
179 // Offline capability: precache the shell + wasm on install, serve cache-first on fetch.\n\
180 const CACHE = '{cache}';\n\
181 const PRECACHE = [\n{precache_js}\n];\n\
182 \n\
183 self.addEventListener('install', (event) => {{\n\
184 \x20 event.waitUntil(\n\
185 \x20\x20\x20 caches.open(CACHE).then((cache) => cache.addAll(PRECACHE)).then(() => self.skipWaiting())\n\
186 \x20 );\n\
187 }});\n\
188 \n\
189 self.addEventListener('activate', (event) => {{\n\
190 \x20 event.waitUntil(\n\
191 \x20\x20\x20 caches.keys().then((keys) => Promise.all(\n\
192 \x20\x20\x20\x20\x20 keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))\n\
193 \x20\x20\x20 )).then(() => self.clients.claim())\n\
194 \x20 );\n\
195 }});\n\
196 \n\
197 self.addEventListener('fetch', (event) => {{\n\
198 \x20 if (event.request.method !== 'GET') return;\n\
199 \x20 event.respondWith(\n\
200 \x20\x20\x20 caches.match(event.request).then((cached) => {{\n\
201 \x20\x20\x20\x20\x20 if (cached) return cached;\n\
202 \x20\x20\x20\x20\x20 return fetch(event.request).then((response) => {{\n\
203 \x20\x20\x20\x20\x20\x20\x20 if (response && response.ok && response.type === 'basic') {{\n\
204 \x20\x20\x20\x20\x20\x20\x20\x20\x20 const copy = response.clone();\n\
205 \x20\x20\x20\x20\x20\x20\x20\x20\x20 caches.open(CACHE).then((cache) => cache.put(event.request, copy));\n\
206 \x20\x20\x20\x20\x20\x20\x20 }}\n\
207 \x20\x20\x20\x20\x20\x20\x20 return response;\n\
208 \x20\x20\x20\x20\x20 }});\n\
209 \x20\x20\x20 }})\n\
210 \x20 );\n\
211 }});\n",
212 cache = cache,
213 precache_js = precache_js,
214 )
215}
216
217fn build_csp(manifest: &QappManifest) -> String {
230 let wants_sync = manifest
231 .capabilities
232 .iter()
233 .any(|c| matches!(c, super::manifest::Capability::Sync));
234 let connect = if wants_sync { "'self'" } else { "'none'" };
235 format!(
236 "default-src 'none'; \
237 script-src 'self' 'wasm-unsafe-eval'; \
238 style-src 'self' 'unsafe-inline'; \
239 img-src 'self' data:; \
240 font-src 'self'; \
241 manifest-src 'self'; \
242 worker-src 'self'; \
243 connect-src {connect}; \
244 base-uri 'none'; \
245 form-action 'none'; \
246 frame-ancestors 'none'"
247 )
248}
249
250fn build_loader_js(manifest: &QappManifest) -> String {
254 let wasm_path = js_string_escape(&manifest.entry_wasm.path);
255 format!(
256 "// Auto-generated external loader (kept out-of-line so a strict script-src CSP applies).\n\
257 (function () {{\n\
258 \x20 'use strict';\n\
259 \x20 var WASM_PATH = '{wasm_path}';\n\
260 \x20 if ('serviceWorker' in navigator) {{\n\
261 \x20\x20\x20 window.addEventListener('load', function () {{\n\
262 \x20\x20\x20\x20\x20 navigator.serviceWorker.register('./sw.js').catch(function (err) {{\n\
263 \x20\x20\x20\x20\x20\x20\x20 console.warn('service worker registration failed:', err);\n\
264 \x20\x20\x20\x20\x20 }});\n\
265 \x20\x20\x20 }});\n\
266 \x20 }}\n\
267 \x20 var importObject = {{ env: {{}} }};\n\
268 \x20 function fallbackInstantiate() {{\n\
269 \x20\x20\x20 return fetch(WASM_PATH)\n\
270 \x20\x20\x20\x20\x20 .then(function (resp) {{ return resp.arrayBuffer(); }})\n\
271 \x20\x20\x20\x20\x20 .then(function (bytes) {{ return WebAssembly.instantiate(bytes, importObject); }});\n\
272 \x20 }}\n\
273 \x20 var loader;\n\
274 \x20 if (WebAssembly.instantiateStreaming) {{\n\
275 \x20\x20\x20 loader = WebAssembly.instantiateStreaming(fetch(WASM_PATH), importObject)\n\
276 \x20\x20\x20\x20\x20 .catch(fallbackInstantiate);\n\
277 \x20 }} else {{\n\
278 \x20\x20\x20 loader = fallbackInstantiate();\n\
279 \x20 }}\n\
280 \x20 loader.then(function (result) {{\n\
281 \x20\x20\x20 var start = result.instance.exports.start || result.instance.exports.main;\n\
282 \x20\x20\x20 if (typeof start === 'function') {{ start(); }}\n\
283 \x20 }}).catch(function (err) {{\n\
284 \x20\x20\x20 console.error('failed to load qapp wasm:', err);\n\
285 \x20\x20\x20 var el = document.getElementById('app');\n\
286 \x20\x20\x20 if (el) {{ el.textContent = 'Failed to load. Check your connection and reload.'; }}\n\
287 \x20 }});\n\
288 }})();\n",
289 wasm_path = wasm_path,
290 )
291}
292
293fn build_index_html(manifest: &QappManifest) -> String {
296 let title_html = html_escape(&manifest.name);
297 let short_name_html = html_escape(&manifest.short_name);
298 let theme_html = html_escape(&manifest.theme_color);
299 let bg_html = html_escape(&manifest.background_color);
300 let description_html = html_escape(&manifest.description);
301 let csp_html = html_escape(&build_csp(manifest));
302
303 format!(
304 "<!DOCTYPE html>\n\
305 <html lang=\"en\">\n\
306 <head>\n\
307 \x20 <meta charset=\"utf-8\">\n\
308 \x20 <meta http-equiv=\"Content-Security-Policy\" content=\"{csp}\">\n\
309 \x20 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, viewport-fit=cover\">\n\
310 \x20 <title>{title}</title>\n\
311 \x20 <meta name=\"description\" content=\"{description}\">\n\
312 \x20 <link rel=\"manifest\" href=\"manifest.webmanifest\">\n\
313 \x20 <meta name=\"theme-color\" content=\"{theme}\">\n\
314 \x20 <meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n\
315 \x20 <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">\n\
316 \x20 <meta name=\"apple-mobile-web-app-title\" content=\"{short_name}\">\n\
317 \x20 <style>\n\
318 \x20\x20\x20 html, body {{ margin: 0; height: 100%; background: {bg}; color: #e6edf3;\n\
319 \x20\x20\x20\x20\x20 font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; }}\n\
320 \x20\x20\x20 #app {{ display: flex; align-items: center; justify-content: center; height: 100%; }}\n\
321 \x20 </style>\n\
322 </head>\n\
323 <body>\n\
324 \x20 <main id=\"app\">Loading {title}…</main>\n\
325 \x20 <script src=\"loader.js\" defer></script>\n\
326 </body>\n\
327 </html>\n",
328 csp = csp_html,
329 title = title_html,
330 description = description_html,
331 theme = theme_html,
332 short_name = short_name_html,
333 bg = bg_html,
334 )
335}
336
337pub fn generate_pwa(manifest: &QappManifest) -> PwaBundle {
344 let files = vec![
345 PwaFile {
346 path: "manifest.webmanifest".to_string(),
347 content: PwaContent::Text(build_webmanifest(manifest)),
348 },
349 PwaFile {
350 path: "sw.js".to_string(),
351 content: PwaContent::Text(build_service_worker(manifest)),
352 },
353 PwaFile {
354 path: "loader.js".to_string(),
355 content: PwaContent::Text(build_loader_js(manifest)),
356 },
357 PwaFile {
358 path: "index.html".to_string(),
359 content: PwaContent::Text(build_index_html(manifest)),
360 },
361 ];
362 PwaBundle { files }
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368 use crate::qapp_package::manifest::{IconRef, QappManifest, WasmRef};
369
370 fn sample() -> QappManifest {
371 QappManifest::new("coop.qualia.journal", "Qualia Journal")
372 .with_version("1.2.3")
373 .with_description("A private journal")
374 .with_entry(WasmRef {
375 path: "./journal.wasm".to_string(),
376 sha256_hex: "abc123".to_string(),
377 size_bytes: 8192,
378 })
379 .with_icon(IconRef {
380 src: "./icons/icon-192.png".to_string(),
381 sizes: "192x192".to_string(),
382 purpose: "any".to_string(),
383 })
384 }
385
386 #[test]
387 fn generates_the_expected_files() {
388 let bundle = generate_pwa(&sample());
389 assert!(bundle.get("manifest.webmanifest").is_some());
390 assert!(bundle.get("sw.js").is_some());
391 assert!(bundle.get("loader.js").is_some());
392 assert!(bundle.get("index.html").is_some());
393 assert_eq!(bundle.files.len(), 4);
394 }
395
396 #[test]
397 fn get_and_text_of_helpers_work() {
398 let bundle = generate_pwa(&sample());
399 assert!(bundle.text_of("sw.js").is_some());
400 assert!(bundle.get("nope.txt").is_none());
401 assert!(bundle.text_of("nope.txt").is_none());
402 }
403
404 #[test]
405 fn webmanifest_has_required_keys_and_values() {
406 let bundle = generate_pwa(&sample());
407 let text = bundle
408 .text_of("manifest.webmanifest")
409 .expect("manifest present");
410
411 assert!(text.contains("\"display\": \"standalone\""), "text: {text}");
413 assert!(text.contains("\"start_url\": \".\""), "text: {text}");
414 assert!(text.contains("Qualia Journal"));
415 assert!(text.contains("#101418"), "theme color present");
416
417 let v: serde_json::Value = serde_json::from_str(text).expect("valid JSON");
419 assert_eq!(v["display"], "standalone");
420 assert_eq!(v["start_url"], ".");
421 assert_eq!(v["scope"], ".");
422 assert_eq!(v["name"], "Qualia Journal");
423 assert_eq!(v["short_name"], "Qualia Journal");
424 assert_eq!(v["theme_color"], "#101418");
425 assert_eq!(v["background_color"], "#0b0d10");
426 assert_eq!(v["id"], "coop.qualia.journal");
427 let icons = v["icons"].as_array().expect("icons array");
428 assert_eq!(icons.len(), 1);
429 assert_eq!(icons[0]["src"], "./icons/icon-192.png");
430 assert_eq!(icons[0]["type"], "image/png");
431 assert_eq!(icons[0]["sizes"], "192x192");
432 }
433
434 #[test]
435 fn service_worker_references_wasm_and_versioned_cache() {
436 let bundle = generate_pwa(&sample());
437 let sw = bundle.text_of("sw.js").expect("sw present");
438 assert!(sw.contains("coop.qualia.journal-1.2.3"), "sw: {sw}");
440 assert!(sw.contains("./journal.wasm"), "sw: {sw}");
442 assert!(sw.contains("addEventListener('install'"));
444 assert!(sw.contains("addEventListener('fetch'"));
445 assert!(sw.contains("caches.match"));
446 assert!(sw.contains("./icons/icon-192.png"));
448 }
449
450 #[test]
451 fn index_html_references_manifest_and_external_loader() {
452 let bundle = generate_pwa(&sample());
453 let html = bundle.text_of("index.html").expect("index present");
454 assert!(html.contains("manifest.webmanifest"), "html: {html}");
455 assert!(
457 html.contains("<script src=\"loader.js\" defer></script>"),
458 "html: {html}"
459 );
460 assert!(
461 !html.contains("(function ()"),
462 "loader must not be inline: {html}"
463 );
464 assert!(html.contains("apple-mobile-web-app-capable"));
466 assert!(html.contains("apple-mobile-web-app-title"));
467 assert!(html.contains("name=\"theme-color\""));
468 assert!(html.contains("rel=\"manifest\""));
469
470 let loader = bundle.text_of("loader.js").expect("loader present");
472 assert!(loader.contains("./journal.wasm"), "loader: {loader}");
473 assert!(loader.contains("WebAssembly.instantiateStreaming"));
474 assert!(loader.contains("serviceWorker"));
475 assert!(loader.contains("./sw.js"));
476 }
477
478 #[test]
479 fn index_html_carries_strict_capability_derived_csp() {
480 let bundle = generate_pwa(&sample());
482 let html = bundle.text_of("index.html").expect("index present");
483 assert!(
484 html.contains("http-equiv=\"Content-Security-Policy\""),
485 "html: {html}"
486 );
487 assert!(html.contains("default-src 'none'"), "html: {html}");
488 assert!(
489 html.contains("script-src 'self' 'wasm-unsafe-eval'"),
490 "html: {html}"
491 );
492 let csp = super::build_csp(&sample());
494 assert!(!csp.contains("script-src 'self' 'unsafe-inline'"));
495 assert!(csp.contains("connect-src 'none'"), "csp: {csp}");
497
498 let mut synced = sample();
500 synced
501 .capabilities
502 .push(crate::qapp_package::manifest::Capability::Sync);
503 let csp = super::build_csp(&synced);
504 assert!(csp.contains("connect-src 'self'"), "csp: {csp}");
505 assert!(!csp.contains("connect-src 'none'"));
506 }
507
508 #[test]
509 fn service_worker_precaches_the_external_loader() {
510 let bundle = generate_pwa(&sample());
511 let sw = bundle.text_of("sw.js").expect("sw present");
512 assert!(sw.contains("./loader.js"), "sw: {sw}");
513 }
514
515 #[test]
516 fn html_escapes_dangerous_strings() {
517 let m = QappManifest::new(
519 "coop.qualia.evil",
520 "Journal <script>alert('x')</script> & \"co\"",
521 )
522 .with_icon(IconRef {
523 src: "./i.png".to_string(),
524 sizes: "any".to_string(),
525 purpose: "any".to_string(),
526 });
527 let bundle = generate_pwa(&m);
528 let html = bundle.text_of("index.html").unwrap();
529 assert!(
530 !html.contains("<script>alert('x')</script>"),
531 "raw script leaked: {html}"
532 );
533 assert!(html.contains("<script>"));
534 assert!(html.contains("&"));
535 }
536
537 #[test]
538 fn js_escapes_wasm_path_with_quote() {
539 let m = QappManifest::new("coop.qualia.q", "Q")
541 .with_entry(WasmRef {
542 path: "./a'b.wasm".to_string(),
543 sha256_hex: String::new(),
544 size_bytes: 0,
545 })
546 .with_icon(IconRef {
547 src: "./i.png".to_string(),
548 sizes: "any".to_string(),
549 purpose: "any".to_string(),
550 });
551 let bundle = generate_pwa(&m);
552 let loader = bundle.text_of("loader.js").unwrap();
554 assert!(
555 loader.contains("./a\\'b.wasm"),
556 "quote not escaped: {loader}"
557 );
558 }
559
560 #[test]
561 fn custom_display_mode_propagates() {
562 let mut m = sample();
563 m.display = "fullscreen".to_string();
564 let bundle = generate_pwa(&m);
565 let v: serde_json::Value =
566 serde_json::from_str(bundle.text_of("manifest.webmanifest").unwrap()).unwrap();
567 assert_eq!(v["display"], "fullscreen");
568 }
569
570 #[test]
571 fn icon_type_inferred_from_extension() {
572 let m = QappManifest::new("coop.q.svg", "S").with_icon(IconRef {
573 src: "./icon.svg".to_string(),
574 sizes: "any".to_string(),
575 purpose: "maskable".to_string(),
576 });
577 let bundle = generate_pwa(&m);
578 let v: serde_json::Value =
579 serde_json::from_str(bundle.text_of("manifest.webmanifest").unwrap()).unwrap();
580 assert_eq!(v["icons"][0]["type"], "image/svg+xml");
581 }
582}