Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.
Rust chatgptclaudeclidesktopdesktop-appelectron-alternativegeminilinuxmacosnativefierno-electronrusttauriweb-to-desktopwebsite-to-appwebviewwindowsyoutube
feat(runtime): serve a runtime app's own pages from pake-runtime/site
Tw93d98261b8477f
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.mdindex b5d12bd5..b6158f76 100644--- a/.claude/rules/tauri-runtime.md+++ b/.claude/rules/tauri-runtime.md@@ -13,6 +13,7 @@ paths:- Passkeys on macOS (2026-11-19): WKWebView refuses WebAuthn in an app that neither lists the site under `webcredentials` nor holds Apple's browser entitlement, which an ad hoc signed app never can, so `create` and `get` failed in 30 ms with `NotAllowedError`. `src-tauri/src/inject/passkey.js` (main frame; not incognito, nor with `ignore_certificate_errors`, where a stand-in on the network would get a signature for the real origin; `passkey::enabled`) hands a `publicKey` request to the `pakePasskey` `WKScriptMessageHandlerWithReply` in `src-tauri/src/app/passkey/macos.rs`, which takes the origin from WebKit's `WKFrameInfo` (main frames only, never from the page), checks the rpId against the public suffix list (`resolve_rp_id`), makes a non-permanent Secure Enclave P-256 key gated by `userPresence` (Touch ID, or the login password), keeps its token (`toid`) in `<app data>/passkeys.json`, and writes `none` attestation itself; no keychain entitlement is needed. The passkeys stay in that app on that Mac, outside iCloud Keychain; a sign-in with none shows a sheet saying so. Any process of the same user can read the store and sign after a prompt that names that process, as with Chrome's profile authenticator. Only the key window of the active app may start a ceremony, and a Mac without an enclave refuses without a sheet. One ceremony runs at a time under a token (`OWNER`); leaving the page (`pagehide`) cancels it like an abort; the page's abort or timeout (5 minutes when the site gives none) sends `cancel`, which counts only from the webview that started it, frees it at once, invalidates the LAContext and ends the sheet; a key made after that is not saved; a sheet left on a closed or close-hidden window (not a minimized one, nor while the app is hidden) gives way to the next request, since the sheet keeps its `Reply` alive. The credential object must read as a browser's: its fields are enumerable getters with no setter and its methods writable, one prototype step up (`shaped`), so `Object.keys` is empty, `for...in` lists the fields (FIDO's webauthn-demo serialises that way) and a page may replace a method, because GitHub's webauthn-json assigns `credential.toJSON = ...` in strict mode and a read-only property made every registration fail after the key was saved (found on github.com with a probe that reported `unhandledrejection`; GitHub's error said only "Passkey registration failed"). Verify on a real bundle: a localhost page backed by py_webauthn for register, sign-in with and without `allowCredentials`, the account picker, cancel then retry; then add and use a passkey on github.com. Cover it with the `app::passkey` Rust tests and `tests/unit/passkey-bridge.test.js`.- `navigation_buttons` is a runtime-only macOS window field (no CLI flag; the paid apps set it, off by default): `src-tauri/src/app/nav_buttons.rs` adds Back and Forward to the title bar in a leading accessory beside the traffic lights, for people with a plain mouse who have neither the swipe nor Cmd-[. The buttons call `history_step`, the native step the Navigation menu uses, so they work on a blank error page; their action lives on the window's class as `tab_bar.rs`'s does. Enabled state follows the WKWebView's `canGoBack` and `canGoForward` by key-value observing; do not poll. The webview owns the observer through an associated object, which means the observer drops only while the webview is deallocating, when a weak reference to it already reads nil: removal in `Drop` never runs, so the observer unregisters on `NSWindowWillCloseNotification`, behind one flag because removing an unregistered observer raises (`auth.rs`'s delegate still has only the `Drop` removal). Alignment is to ink, checked on a 2x capture: each chevron's middle goes on the close button's centre line, read from `standardWindowButton:` (the lights sit 16 points down a 32 point bar on macOS 26) and from the cell's `imageRectForBounds:` (NSButton sets a 16 point image half a point above a 22 point button's middle), and redone on resize and around full screen. The chevrons are drawn, not `chevron.left`, because that symbol sits on a text baseline 1.5 points high. Labels are the system's own, 返回 and 前进, 上一頁 and 下一頁, through `UiLanguage`. A real-bundle check measures the rows of the red light and of each chevron in a `screencapture -l` PNG, whose centres must be equal, and opens then closes a Cmd+N window with the app still running. Under `hide_title_bar` the buttons sit over the page beside the lights, and the per-site `immersive` paddings in `style.js` clear only the lights' width. Cover it with `tests/unit/macos-navigation-buttons.test.ts` and the `navigation_buttons_are_opt_in` Rust test.- `transparent_title_bar` is a runtime-only macOS window field (no CLI flag; the paid apps set it): Tauri's `Transparent` title bar keeps the page below the bar, and `src-tauri/src/inject/title_bar.js` paints the window background with the page's top-edge color through `set_title_bar_color`. `hide_title_bar` keeps precedence and its overlay behavior. The color is the majority of three top-edge samples, resolved through a canvas so `oklch()`/`color()` values work; do not skip sampling for `document.hidden`, or windows revealed after load stay uncolored. Cover it with `tests/unit/title-bar-color.test.js`; when checking a real bundle, window captures carry the display profile, so convert the sRGB page color before comparing pixels.+- A runtime app can carry its own pages (2026-11-25): with `url_type: "local"` the window's `url` names a file inside `pake-runtime/site/` (`tool.html`, `index.html`), and `apply_runtime_override` sets `PakeConfig::runtime_site` only when that file exists, refusing an empty, absolute or `..` path. `run_app` then swaps the context's assets for `src-tauri/src/app/local_site.rs`, which reads files from that folder on each request and refuses any path, `..` or symbolic link, that resolves outside it, so the pages keep the origin and local-page behaviour of a CLI local app (`tauri://localhost`, `http://tauri.localhost` on Windows) without a compiler. Covered by `runtime_override_serves_a_local_window_from_its_site_folder` and the `local_site` tests; measured on the test Mac with a page, a script in a subfolder, a `fetch` of a JSON file and localStorage across a relaunch.- `site_styles` is a runtime-only window field (no CLI flag; default true): the paid apps write false when the app carries a browser extension that restyles its site (Minimal Theme for Twitter on X), and `style.js` then leaves out that site's `content` rules, keeping the global and `immersive` ones. On X the runtime's 700 px column, `!important` under `#react-root`, overrode the extension's own width setting. `page_config` in `window.rs` forces it back to true wherever the app's extensions do not run (no `pake-runtime/extensions`, macOS before 15.4, Linux), so a site never loses both. Covered by `site_styles_stay_on_unless_the_builder_turns_them_off`, `site_styles_turn_off_only_where_extensions_run` and `tests/unit/site-styles.test.js`.- Window/runtime options with platform-sensitive behavior include `--incognito`, `--new-window`, `--min-width`, `--min-height`, `--maximize`, multi-window behavior, notification click handling, and Linux/Wayland WebKit compositing defaults.- `--incognito` intentionally trades persistence for clean private sessions; be careful around login, cookies, local storage, and sites that detect the WebView.diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rsindex 25d5baf5..487abef7 100644--- a/src-tauri/src/app/config.rs+++ b/src-tauri/src/app/config.rs@@ -164,6 +164,10 @@ pub struct PakeConfig {/// browser extension. macOS 15.4 and later and Windows load what is in it.#[serde(skip)]pub runtime_extensions: Option<std::path::PathBuf>,+ /// The `site` folder of a runtime override whose window is `local`: the+ /// app serves its pages from there instead of the template's own assets.+ #[serde(skip)]+ pub runtime_site: Option<std::path::PathBuf>,/// Set when a runtime override supplied the app identity, so per-app/// directories follow the identifier rather than the product name.#[serde(skip)]diff --git a/src-tauri/src/app/local_site.rs b/src-tauri/src/app/local_site.rsnew file mode 100644index 00000000..00099b20--- /dev/null+++ b/src-tauri/src/app/local_site.rs@@ -0,0 +1,139 @@+//! Serves a runtime app's own pages from `pake-runtime/site`.+//!+//! A CLI build bakes a local page into the binary's assets. A prebuilt runtime+//! template cannot, so a builder copies the user's files into the `site`+//! folder and the runtime swaps Tauri's assets for this reader. The pages keep+//! the origin a CLI-built local app has (`tauri://localhost`, or+//! `http://tauri.localhost` on Windows), so everything Pake does for local+//! pages applies unchanged.++use std::borrow::Cow;+use std::path::{Component, Path, PathBuf};++use tauri::utils::assets::{AssetKey, AssetsIter, CspHash};+use tauri::{Assets, Runtime};++/// `raw` as a path of plain names, or None when it is empty, absolute, or+/// steps out with `..`. Asset keys arrive percent-decoded, so a request for+/// `/%2e%2e/secret` reaches this as `../secret`.+pub fn relative_path(raw: &str) -> Option<PathBuf> {+ let mut path = PathBuf::new();+ for component in Path::new(raw.trim_start_matches(['/', '\\'])).components() {+ match component {+ Component::Normal(name) => path.push(name),+ Component::CurDir => {}+ Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,+ }+ }+ (!path.as_os_str().is_empty()).then_some(path)+}++pub struct LocalSite {+ root: PathBuf,+}++impl LocalSite {+ pub fn new(root: PathBuf) -> Self {+ let root = root.canonicalize().unwrap_or(root);+ Self { root }+ }++ /// The file a key names, only when it resolves inside the site folder:+ /// a symbolic link that points out of it is refused like `..`.+ fn resolve(&self, key: &str) -> Option<PathBuf> {+ let file = self.root.join(relative_path(key)?).canonicalize().ok()?;+ (file.starts_with(&self.root) && file.is_file()).then_some(file)+ }+}++impl<R: Runtime> Assets<R> for LocalSite {+ fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {+ std::fs::read(self.resolve(key.as_ref())?)+ .ok()+ .map(Cow::Owned)+ }++ fn iter(&self) -> Box<AssetsIter<'_>> {+ Box::new(std::iter::empty())+ }++ // The app ships with no CSP (`csp: null`), so there are no hashes to add.+ fn csp_hashes(&self, _html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {+ Box::new(std::iter::empty())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::fs;++ fn site() -> (PathBuf, LocalSite) {+ let base = std::env::temp_dir().join(format!(+ "pake-local-site-{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let root = base.join("site");+ fs::create_dir_all(root.join("assets")).unwrap();+ fs::write(root.join("index.html"), "<h1>hi</h1>").unwrap();+ fs::write(root.join("assets/app.js"), "1").unwrap();+ fs::write(base.join("secret.txt"), "no").unwrap();+ let site = LocalSite::new(root);+ (base, site)+ }++ fn read(site: &LocalSite, key: &str) -> Option<Vec<u8>> {+ <LocalSite as Assets<tauri::Wry>>::get(site, &AssetKey::from(key)).map(Cow::into_owned)+ }++ #[test]+ fn serves_files_inside_the_site_folder() {+ let (base, site) = site();+ assert_eq!(+ read(&site, "index.html").as_deref(),+ Some(&b"<h1>hi</h1>"[..])+ );+ assert_eq!(read(&site, "/assets/app.js").as_deref(), Some(&b"1"[..]));+ assert_eq!(read(&site, "./assets/app.js").as_deref(), Some(&b"1"[..]));+ // Missing files and folders are None, so Tauri's own fallbacks apply.+ assert!(read(&site, "missing.html").is_none());+ assert!(read(&site, "assets").is_none());+ fs::remove_dir_all(base).unwrap();+ }++ #[test]+ fn refuses_paths_that_leave_the_site_folder() {+ let (base, site) = site();+ assert!(read(&site, "../secret.txt").is_none());+ assert!(read(&site, "assets/../../secret.txt").is_none());+ assert!(site+ .resolve(&base.join("secret.txt").to_string_lossy())+ .is_none());+ #[cfg(unix)]+ {+ std::os::unix::fs::symlink(base.join("secret.txt"), base.join("site/link.txt"))+ .unwrap();+ assert!(read(&site, "link.txt").is_none());+ }+ fs::remove_dir_all(base).unwrap();+ }++ #[test]+ fn relative_path_accepts_only_plain_names() {+ assert_eq!(+ relative_path("index.html"),+ Some(PathBuf::from("index.html"))+ );+ assert_eq!(+ relative_path("/tools/a b.html"),+ Some(PathBuf::from("tools/a b.html"))+ );+ for raw in ["", "/", "..", "../x.html", "a/../../x.html"] {+ assert_eq!(relative_path(raw), None, "{raw:?}");+ }+ }+}diff --git a/src-tauri/src/app/mod.rs b/src-tauri/src/app/mod.rsindex 3daedbc9..6e3adeca 100644--- a/src-tauri/src/app/mod.rs+++ b/src-tauri/src/app/mod.rs@@ -13,6 +13,7 @@ pub mod extensions;#[cfg(target_os = "linux")]pub mod header_bar;pub mod invoke;+pub mod local_site;#[cfg(target_os = "linux")]pub mod media_permission;#[cfg(target_os = "macos")]diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 5ef0fec9..069a06e9 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -319,6 +319,10 @@ pub fn run_app() {context.package_info_mut().name = name.clone();}}+ // A runtime app made from local files serves them from its own folder.+ if let Some(site) = pake_config.runtime_site.clone() {+ context.set_assets(Box::new(app::local_site::LocalSite::new(site)));+ }let tauri_app = tauri::Builder::default();#[cfg(target_os = "macos")]let tauri_app = tauri_app.on_web_content_process_terminate(|webview| {diff --git a/src-tauri/src/util.rs b/src-tauri/src/util.rsindex 22c50ace..e0e086f6 100644--- a/src-tauri/src/util.rs+++ b/src-tauri/src/util.rs@@ -118,6 +118,7 @@ fn apply_runtime_override(.into_owned();}pake_config.runtime_extensions = runtime_extensions(dir);+ pake_config.runtime_site = runtime_site(dir, &pake_config.windows[0])?;pake_config.runtime_app = true;tauri_config.identifier = app.identifier;tauri_config.product_name = Some(app.product_name);@@ -138,6 +139,29 @@ fn runtime_extensions(dir: &Path) -> Option<PathBuf> {.then_some(directory)}+/// `pake-runtime/site` for a window whose `url_type` is `local`, None for a+/// web page. A local window's `url` names its entry file inside that folder, a+/// plain relative path, and the folder must hold it.+fn runtime_site(+ dir: &Path,+ window: &crate::app::config::WindowConfig,+) -> Result<Option<PathBuf>, String> {+ if window.url_type != "local" {+ return Ok(None);+ }+ let site = dir.join("site");+ let entry = crate::app::local_site::relative_path(&window.url).ok_or_else(|| {+ format!(+ "local url {:?} is not a path inside the site folder",+ window.url+ )+ })?;+ if !site.join(&entry).is_file() {+ return Err(format!("{} has no {}", site.display(), entry.display()));+ }+ Ok(Some(site))+}+/// Same rule as the CLI's --identifier check, capped at the 128 characters an/// AppUserModelID allows.fn is_valid_identifier(id: &str) -> bool {@@ -941,6 +965,48 @@ mod tests {fs::remove_dir_all(dir.parent().unwrap()).unwrap();}+ #[test]+ fn runtime_override_serves_a_local_window_from_its_site_folder() {+ let mut runtime: serde_json::Value =+ serde_json::from_str(include_str!("../pake.json")).unwrap();+ runtime["windows"][0]["url_type"] = "local".into();+ runtime["windows"][0]["url"] = "tool.html".into();+ let dir = runtime_dir(&[+ ("pake.json", &runtime.to_string()),+ ("app.json", RUNTIME_APP),+ ]);++ // No site folder, or one without the entry file, is an error rather+ // than a window showing the template's own assets.+ let (pake, tauri) = compiled_configs();+ let error = apply_runtime_override(pake, tauri, Some(&dir)).unwrap_err();+ assert!(error.contains("tool.html"), "{error}");+ fs::create_dir_all(dir.join("site")).unwrap();+ let (pake, tauri) = compiled_configs();+ assert!(apply_runtime_override(pake, tauri, Some(&dir)).is_err());++ fs::write(dir.join("site/tool.html"), "<p>tool</p>").unwrap();+ let (pake, tauri) = compiled_configs();+ let (pake, _) = apply_runtime_override(pake, tauri, Some(&dir)).unwrap();+ assert_eq!(pake.runtime_site, Some(dir.join("site")));+ assert!(!pake.windows[0].remembers_last_url());++ // The entry must stay inside the folder.+ runtime["windows"][0]["url"] = "../app.json".into();+ fs::write(dir.join("pake.json"), runtime.to_string()).unwrap();+ let (pake, tauri) = compiled_configs();+ assert!(apply_runtime_override(pake, tauri, Some(&dir)).is_err());++ // A web window ignores a site folder.+ runtime["windows"][0]["url_type"] = "web".into();+ runtime["windows"][0]["url"] = "https://example.com".into();+ fs::write(dir.join("pake.json"), runtime.to_string()).unwrap();+ let (pake, tauri) = compiled_configs();+ let (pake, _) = apply_runtime_override(pake, tauri, Some(&dir)).unwrap();+ assert!(pake.runtime_site.is_none());+ fs::remove_dir_all(dir.parent().unwrap()).unwrap();+ }+#[test]fn runtime_override_replaces_config_identity_script_and_tray() {let mut runtime: serde_json::Value =