diff --git a/README.md b/README.md index 7dcf9ea..034df1d 100644 --- a/README.md +++ b/README.md @@ -40,40 +40,152 @@ License: GPL-3.0-or-later. Built something on wayBetter? Add it to this list with a pull request: name and link, what it extends, one line on what it does. +## Build your own + +```sh +npm create waybetter plugin # a *.plugin.js (or --ts: a TypeScript project) on the real plugin API +npm create waybetter theme # a theme JSON with "$schema", a derived palette and font roles +npm create waybetter app -- --site kick.com # a whole app: Tauri 2 + waybetter-host + runtime + shell +``` + +`create-waybetter` (in `packages/create-waybetter`) asks for what it needs in a terminal, and +takes every answer as a flag (`--help`). The app skeleton is this README in code: the native +`SiteSpec`, the page `SiteAdapter`, the app on `waybetter_host::app` (its config, site hooks and +its own commands), the three capability files and a `tests/security.rs` on `waybetter_host::testkit`, +the shell (the framework's shell frame through `createShell`, with the site's pages and a plugins +panel), the plugin store, one site-only command, the +runtime bundled with `waybetter/build` and a `waybetter.release.json` for `waybetter release`, with presets for +youtube.com, kick.com and twitch.tv and every site selector marked as a placeholder. Its tests +generate each kind into a temp folder and check it against the real contracts: plugin headers with +`plugins::parse_meta`, plugin code against `createCorePluginApi`'s members, themes against +`theme.schema.json`, the app's TypeScript with `tsc` against the built package and its Rust with +`cargo check`/`cargo test` against this crate. + ## Layout ``` -crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfix, updates, tab payloads +crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfix, updates, tab payloads, + and the generic native features every app gets (below) + tab-bridge.js the tab bridge every tab gets (served by src/bridge.rs) src/site.rs SiteSpec + AccountRules (the native half of the adapter) src/policy.rs webview labels, origin checks, tab rect clamp src/profiles.rs profiles, per-profile data dirs, native-owned accounts src/plugins.rs *.plugin.js store, custom CSS, bundled-plugin upgrades + src/plugins/commands.rs palette commands site tabs report, and the script that runs one src/hotfix.rs signed data-only hotfix channel (minisign) src/update.rs silent-update scheduling and crash handshake - src/tabs.rs TabLayout/TabState/OpenRequest, link modes, shortcut and drag validation + src/tabs.rs TabLayout/TabState/OpenRequest, link modes, shortcut and drag validation, + deck ColumnConfig bounds and unread caps + src/bridge.rs the tab bridge script (reports; shortcut/link-drag forwarding opt-in) + src/backup.rs settings backup envelope, secret scrubbing, plugin/account sections + src/sync.rs encrypted folder sync (Argon2id + XChaCha20-Poly1305 snapshots) + src/workspaces.rs saved tab/pane/deck layouts, bounded and well-formed + src/devmode.rs developer mode: debounced file watcher, reload order, error positions + src/alerts.rs keyword alerts: keywords, snippets, rate limits; native notifications + src/media.rs gallery folders (path containment), clipboard history, PNG encoding + src/media/clipboard.rs (feature "tauri") opt-in clipboard polling, private copies skipped + src/gfonts.rs self-hosted Google Fonts: CSS parsing, URL/woff2 checks, cache format + src/fonts.rs (feature "net") font downloads and the font cache + src/updater.rs (features "tauri" + "net") signed native updates and the hotfix channel + src/store/ install links, download allow-list, signed multi-app store catalog, staging + and installs; downloads with feature "net" (docs/STORE.md) src/host.rs (feature "tauri") webview helpers, shell events, system menu + src/app.rs (feature "app") the whole app around a site: run_app / App, AppConfig, + SiteHooks, the window, shell and tab webviews, the generic commands + src/commands.rs the commands the host serves and who may call them; manifest() for build.rs + src/testkit.rs capability/caller-check assertions for an app's tests/security.rs packages/runtime/src/ page runtime core (TypeScript, no dependencies) site.ts SiteAdapter (the page half of the adapter) + configureRuntime domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page - pluginApi.ts core of window..api for plugins + pluginApi.ts core of window..api for plugins (incl. ui and theme) + ui.ts plugin UI kit: toasts, alert/confirm/prompt, dialogs (shadow DOM, themed) + themeApi.ts the active theme as values + --wb-* CSS variables (api.theme) themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis paneNav.ts split view: park the site's navigation rail in redundant panes + column.ts deck columns: hide site chrome, fill the width, filters, unread count linkRouting.ts divert in-page clicks to a pane/tab/browser per setting accountReport.ts report the signed-in account of this tab's profile -packages/shell/src/ shell core (TypeScript, no dependencies) +packages/shell/src/ shell core (TypeScript) and the shell frame (React) addressModel.ts address bar chips (site pages named by the adapter) paneModel.ts beside-pane reuse, redundant rails, navRedundant for tabs_sync + deckModel.ts decks of site columns: bounded storage model, paging layout, focus linkDrop.ts dropping links into the dock profileModel.ts profiles and account labels palette.ts command palette scoring/ranking updateModel.ts titlebar update chip windowControls.ts caption buttons, resize grips, system menu (Tauri API injected) chrome.ts titlebar/toolbar/resize-border sizes (match policy.rs) + storeModel.ts storeMessages.ts Store wire types, item states, permission words; wb.store/install/permission.* + installController.ts the install screen's state machine (links, drops, store items, confirm) + InstallDialog.tsx StoreView.tsx store.css the install screen and the Store view (React peer, --wb-* tokens) + frame/ the shell frame: createShell(site) (see "The shell frame" below) +packages/waybetter/ the published npm package (runtime + shell as ESM + .d.ts, theme.schema.json, + store-catalog.schema.json, the `waybetter store build|sign|verify` and + `waybetter release windows|macos` commands, `waybetter/build`) +docs/STORE.md the Store: shared catalog format, signing and keys, tooling, trust model, how to add it +packages/create-waybetter/ `npm create waybetter`: plugin, theme and app scaffolds (no dependencies) ``` Both TypeScript packages are plain source (`.ts`, ESM, `type: module`) with no runtime dependencies, so an app can bundle them with esbuild/Vite and run their tests with Node's type -stripping. Anything that needs the Tauri API (window controls) takes it as a parameter. +stripping. Anything that needs the Tauri API (window controls, the shell frame) takes it as a +parameter. The React parts (the Store screens, the shell frame) have React, and the frame dockview, +as optional peers: the app's copies are used. + +## The shell frame + +`packages/shell/src/frame` (`waybetter/shell/frame`) is the whole shell of a wayBetter app. An app +describes its site and gets tabs in the titlebar row, split panes and link drags into the dock, the +smart address bar, the new-tab page, the command palette, the account switcher, decks of site +columns, workspaces, the developer-mode and sync chips, the gallery/clipboard panel, pane themes, +its own panel tab, keyboard shortcuts, overlays that raise the shell above the tab webviews, the +one-layout-in-flight `tabs_sync` and session restore: + +```tsx +import { invoke } from '@tauri-apps/api/core'; // or window.__TAURI__ (withGlobalTauri) +import { listen } from '@tauri-apps/api/event'; +import { getCurrentWindow } from '@tauri-apps/api/window'; +import { createShell, type ShellSite } from 'waybetter/shell/frame'; + +const site: ShellSite = { name: 'Kick', product: 'wayBetter for Kick', homeUrl, loginUrl, logoutUrl, + isSiteUrl, accounts, searchUrl, address, panel: { id, title, component }, newTab, palette, + deck, media, themes, overlays, features, start }; +const Shell = createShell(site, { native: { invoke, listen, currentWindow: getCurrentWindow }, i18n }); +createRoot(root).render(); +``` + +What the site supplies (`frame/site.ts`, every field documented there): + +- names and pages: `name` (in messages as `{site}`), `product`, `logo`, `homeUrl`, `loginUrl`, + `logoutUrl`, `isSiteUrl`, the account rules, `searchUrl` for typed text; +- the address bar: `address(url)` (chips, usually `parseAddress` with an `AddressSite`) and an + optional `addressCompleter` (inline completions, e.g. search operators); +- slots: `panel` (the app's own tab and its sections), `newTab` (search label, quick links), + `palette` (placeholder, the literal search, completions, the panel's sections, the site's pages), + `deck` (column kinds with labels and icons, the page each loads, titles, value parsing and + completions, column flags and presets, an optional compose dock), `media` (which pages have a + composer), `themes` (a `createThemeStore(adapter)`: the app's theme documents, chrome colors via + `chromeVars`, pane themes), `overlays` (the app's own dialogs), `start()` (read site settings, + call `siteChanged()` when site text changes); +- `features`: the native features the app wires up (workspaces, sync, developer mode, plugin + palette commands); an app without them shows nothing of them. + +The frame's words are `wb.*` messages in the framework catalogs (51 languages; English source in +`frame/frameMessages.ts`): the app passes its i18n instance with the framework catalogs merged in. +Styles come with the components (dockview's, then `shell.css`, `deck.css`, `workspaces.css`, +`accountSwitcher.css`, `paneTheme.css`); colors are `--wb-c-*` tokens with Night Ink fallbacks, +set by the theme store (the chrome and each pane group) and cached for the first frame: +`bootScript()` (`frame/boot.ts`) is the `boot.js` an app serves before its modules (a Vite plugin or +a build step writes it). `installPreviewMocks(handlers)` answers native commands from memory, so +the real shell renders in a plain browser for development previews and screenshots. + +Native commands the frame calls: the host's (`tabs_sync`, `tab_navigate`, `tab_action`, +`shell_focus`, `shell_raise`, `open_external_url`, `window_system_menu`, `profiles_*`), and for the +features an app turns on `settings_get`, `column_configure`, `workspaces_*`, `sync_*`, `dev_*`, +`plugins_list`, `tab_run_command`, `media_get`/`gallery_*`/`clip_*`/`tab_attach_image`/ +`tab_insert_text`, `theme_scopes_*` and `gfonts_*`, `app_ready`/`update_status`/`apply_update`. It +listens to `tab-state`, `tab-open`, `tab-shortcut`, `link-drag`, `open-panel`, `profiles-changed`, +`tab-commands`, `dev-event`, `update-status`, `tab-still` and `clipboard-changed`. ## The site adapter @@ -140,7 +252,7 @@ The security model is the same for every app and must stay keyed by webview labe | webview | may call | | --- | --- | -| `shell` (local assets only) | app, settings, vault, tab management (`tabs_sync`, `tab_navigate`, `tab_action`, ...) | +| `shell` (local assets only) | app, settings, vault, and the host's `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `shell_raise`, `profiles_*`, `i18n_*`, ...) | | `tab-*` (any site) | only tab chrome about itself: `tab_report`, `tab_shortcut`, `tab_link_drag` | | `tab-*` on the exact site origin | the app's short, reviewed list of site-only commands | | other local webviews (`popover-*`, ...) | their own narrow capability | @@ -162,8 +274,36 @@ caller's label, the webview's own URL (never the page's claim), payload bounds. about itself; the account it reports is recorded only for its own profile, only while it is on the site, and a shell save can never change it (`ProfileSettings::keep_accounts_from`). +`waybetter_host::testkit` checks this in an app's own tests: `Capabilities::from_dir` reads every +capability file, `assert_host_commands` keeps the host's commands shell-only / tab-only, +`assert_shell_only` / `assert_tab_only` do the same for the app's, `assert_no_plugin_apis` refuses +Tauri plugin JS APIs, and `assert_guarded` / `assert_host_guards` check that each command's first +statement checks its caller. + ## What the host gives an app +- `app` (feature `app`): the whole app. `App::new(AppConfig, hooks).setup(..).run(context, + handler)` (or `run_app`) registers single-instance, deep-link (opt-in), window-state, opener, + updater (opt-in), process, notification and dialog; makes the app-data folder (0700 on Unix), + loads the profiles and the language, runs the app's setup, then builds the window (frameless + with the shell's titlebar, or the OS frame), restores its geometry (lost geometry reset), + routes helper-window closes (Windows), follows window resizes natively and adds the shell + webview (transparent: it can rise above the tabs; macOS needs the `macos-private-api` feature). + It serves `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `open_external_url`, + `shell_focus`, `shell_ready`, `tab_still_ready`, `shell_raise`, `window_system_menu`, `profiles_get`/`profiles_set`, + `i18n_get`/`i18n_set`) and `commands::TAB` (`tab_shortcut`, `tab_link_drag`), each checking its + caller first, and dispatches every other command to the app's handler. Tab webviews get their + profile's data folder, the app's document-start scripts, navigation/pop-up/load/title/download + handling, stills and memory targets; `SiteHooks` is where the app says what only it knows (page + scripts, legacy domains, link routing, per-tab state, what a finished site page gets). Helpers: + `profiles`, `tab_profile`, `account_seen`, `tr`/`trf`, `i18n_page_script`, `notify`, + `open_external`. + To show the first window only after restored panes are placed, opt in on both sides: + `AppConfig::defer_window_show = true` and `ShellSite.deferWindowShow = true`, and grant the + shell `allow-shell-ready`. The default still shows the window immediately. An opted-in app + shows it after initial `tabs_sync`, with a three-second fallback if shell startup fails. +- `commands`: the host's command list and `manifest(&[..])` for the app's `build.rs`. +- `testkit`: see the capabilities section. - `policy`: `SHELL_LABEL`, `tab_id`, `require_local`, `require_site_tab`, `clamp_tab_rect` (tabs never cover the titlebar or, while restored, the resize band). - `profiles`: `ProfileSettings` (validated, default profile required, profiles with open tabs cannot be @@ -173,21 +313,60 @@ site, and a shell save can never change it (`ProfileSettings::keep_accounts_from - `hotfix`: minisign-verified, schema-checked, monotonic, expiring data; delivered frozen as data. - `update`: check schedule with jitter, crash handshake (automatic apply off after two failed boots). - `tabs`: shell payloads and validation; `deliver_script` hands JSON to a runtime member or parks it. +- `bridge`: the tab bridge (`SOURCE`, or `script(BridgeOptions)` to leave shortcut and link-drag + forwarding off when the shell does not handle them). +- `backup` + `sync`: the `.waybetter` settings backup (the app registers its sections and files; + secret-looking keys are scrubbed both ways) and encrypted snapshots in a folder the owner syncs. +- `workspaces`: validation of saved layouts (slug ids, known tab kinds, http(s) URLs, size caps). +- `devmode`: the live-reload watcher (plugins, `custom.css`, one theme file; the app turns the theme + document into its own state through a callback). +- `alerts`: keyword settings, snippets, `Throttle`, `AlertGate` over any `KeywordMatch`; + `alerts::notify` (feature `tauri`) shows a native notification. +- `media`: gallery folders and the opt-in clipboard history; `media::clipboard::watch` (feature + `tauri`) polls the OS clipboard and never reads a copy a password manager marked private. +- `gfonts` + `fonts` (feature `net`): Google Fonts downloaded natively from the two Google hosts + only, cached with a sha256 manifest and handed to site pages as bytes (`page_script(&SITE, ..)`). +- `updater` (features `tauri` + `net`): the update loop, the signed hotfix channel and + `status`/`apply`/`ready` for the app's commands, configured by an `UpdaterConfig`. +- `plugins::commands`: palette commands a site tab reports, and `run_script(&SITE, id)`. +- `store`: the wayBetter Store for any app from a `StoreConfig` (app id, link scheme, store URL, + public keys with rotation, download hosts): `waybetter://install` link parsing, the allow-list, + size caps, catalog verification (Ed25519, strict schema, each app sees only its items), `Store` + (pending links, staged installs, commit of exactly the staged bytes, records, offline catalog), + and with feature `net` no-redirect/no-cookie downloads. The shell half is `waybetter/shell`'s + `InstallHost`, `StoreView` and install controller; the tooling is `waybetter store` + (docs/STORE.md). - `host` (feature `tauri`): `shell_only`, `tab_only`, `site_tab_only`, `emit_shell`, `tab_webview`, `eval_in_site_tabs`, `navigate_tab`, `tab_action`, `forward_shortcut`, `forward_link_drag`, `read_json`/`write_json`, `remove_profile_dirs`, `prune_profile_dirs`, `migrate_identifier`, `system_menu`. -The app keeps its own `#[tauri::command]` wrappers, so IPC command names, the build-time command -manifest and the capability files stay in the app. +The app keeps its own `#[tauri::command]` wrappers for everything else, and its capability files; +its `build.rs` lists its commands through `commands::manifest`, which adds the host's. + +The npm package adds the app-side tooling: + +- `waybetter/build`: `buildRuntime({ entry, outfile, catalog, prefixes, ... })` bundles a page + runtime into one IIFE with the app's esbuild (`?inline` CSS as text, other CSS dropped, only the + runtime's own catalog prefixes compiled in). +- `waybetter release windows|macos`: signed native releases and the update manifest from the + app's `waybetter.release.json` (product and file names, key folder, CDN and API URLs, an optional + manifest validator). Windows: the signed NSIS build, the installer and `.sig` in + `/upload`, `latest.json` (other platforms of the version kept); macOS: signs a universal + build's updater bundle and adds both darwin platforms. It never uploads: it prints the steps. + The key is read only into the build's environment or handed to the Tauri signer by path. ## Consuming it wayBetter for X adds this repository as a git submodule at `waybetter/` and consumes it from source: - Rust: a path dependency, `waybetter-host = { path = "../../../waybetter/crates/waybetter-host" }`, - with `features = ["tauri"]` enabled by the app's desktop feature. -- TypeScript: relative imports of `waybetter/packages/*/src/*.ts` from a few adapter modules. The + with `features = ["app", "net", "macos-private-api"]` enabled by the app's desktop feature (and + as a build-dependency for `commands::manifest`). +- TypeScript: relative imports of `waybetter/packages/*/src/*.ts`: the X site for the shell frame + (`src/shell/site.tsx`), the page runtime's adapter and a few X modules. Its Vite config dedupes + React, dockview and the Tauri API (the frame's imports use the app's copies) and serves + `bootScript()` as `/boot.js`. The packages are not Bun workspace members of the app on purpose: the app's server CI clones without submodules and runs `bun i`, which fails when a declared workspace package is missing; and Node's type stripping refuses `.ts` files under `node_modules`, while sources outside it work with Bun's @@ -197,12 +376,16 @@ wayBetter for X adds this repository as a git submodule at `waybetter/` and cons ```sh bun install # typescript + @types/node for the checks -bun run typecheck # tsc over both packages and their tests -bun run test # node --test (runtime + shell) and cargo test (headless host) +bun run typecheck # tsc over both packages and their tests, and create-waybetter (checkJs) +bun run test # node --test (runtime + shell), cargo test (headless host), create-waybetter bun run test:ts bun run test:rust -bun run check:tauri # cargo check with the tauri feature (slow: builds Tauri) +bun run test:create # scaffolds into temp dirs; its cargo check of an app is ~1 min cold + # (WAYBETTER_SKIP_CARGO_CHECK=1 skips it; needs the local crate cache) +bun run check # typecheck + build:packages + test +bun run check:tauri # cargo check with the app feature (slow: builds Tauri and its plugins) bun run build # typecheck + cargo build +bun run pack:check # npm pack --dry-run of waybetter and create-waybetter ``` Requires Bun 1.4.2+, Node 24+ and Rust 1.88+. diff --git a/bun.lock b/bun.lock index 501b592..13e2f4a 100644 --- a/bun.lock +++ b/bun.lock @@ -6,9 +6,20 @@ "name": "waybetter", "devDependencies": { "@types/node": "^24.0.0", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "acorn": "^8.15.0", + "dockview": "^4", "typescript": "^5.9.0", }, }, + "packages/create-waybetter": { + "name": "create-waybetter", + "version": "0.1.0", + "bin": { + "create-waybetter": "bin/create-waybetter.js", + }, + }, "packages/runtime": { "name": "@waybetter/runtime", "version": "0.1.0", @@ -17,16 +28,59 @@ "name": "@waybetter/shell", "version": "0.1.0", }, + "packages/waybetter": { + "name": "waybetter", + "version": "0.4.0", + "bin": { + "waybetter": "bin/waybetter.mjs", + }, + "devDependencies": { + "@types/node": "^24.0.0", + "typescript": "^5.9.0", + }, + "peerDependencies": { + "acorn": ">=8.0.0", + "dockview": ">=4.0.0", + "esbuild": ">=0.20.0", + "react": ">=18.0.0", + "react-dom": ">=18.0.0", + }, + "optionalPeers": [ + "acorn", + "dockview", + "esbuild", + "react", + "react-dom", + ], + }, }, "packages": { "@types/node": ["@types/node@24.19.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-zY+5tKxXdhGh1PYI0ac+7juvEu4OI6vWtVVoj5i2m42jxAY1U+zHGt6QCyOFwykdP62sM3MJ9stoYYUw5aCWew=="], + "@types/react": ["@types/react@19.3.0", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="], + + "@types/react-dom": ["@types/react-dom@19.3.0", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="], + "@waybetter/runtime": ["@waybetter/runtime@workspace:packages/runtime"], "@waybetter/shell": ["@waybetter/shell@workspace:packages/shell"], + "acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="], + + "create-waybetter": ["create-waybetter@workspace:packages/create-waybetter"], + + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + + "dockview": ["dockview@4.13.1", "", { "dependencies": { "dockview-core": "^4.13.1" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-K8xnYt3Rvkx8MYKHaEsb8aFaPyQclKRRkXS9JcpQPZUgqxumTLnSidgdd6uIfzEps6yJsXoZGQGJ9PtcaKyDcQ=="], + + "dockview-core": ["dockview-core@4.13.1", "", {}, "sha512-+7vR0ZEoL8CNck6NqDVUMqBT22niwBu5CMMI137dZ3c8NDc7c5Si+3dGEqQgM4lNtHBLAtvypo1C4p21J2wkiQ=="], + + "react": ["react@19.3.0", "", {}, "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog=="], + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], + + "waybetter": ["waybetter@workspace:packages/waybetter"], } } diff --git a/crates/waybetter-host/Cargo.lock b/crates/waybetter-host/Cargo.lock index 0e05bdd..e3b77c8 100644 --- a/crates/waybetter-host/Cargo.lock +++ b/crates/waybetter-host/Cargo.lock @@ -8,6 +8,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -47,6 +57,178 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "arboard" +version = "3.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "parking_lot", + "percent-encoding", + "windows-sys 0.60.2", + "x11rb", +] + +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "atk" version = "0.18.2" @@ -100,6 +282,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bit-set" version = "0.8.0" @@ -130,6 +318,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -148,6 +345,19 @@ dependencies = [ "objc2", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "brotli" version = "9.0.0" @@ -196,6 +406,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -289,6 +505,17 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" +[[package]] +name = "cfb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + [[package]] name = "cfb" version = "0.14.0" @@ -316,6 +543,30 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.45" @@ -325,7 +576,27 @@ dependencies = [ "iana-time-zone", "num-traits", "serde", - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", ] [[package]] @@ -338,6 +609,41 @@ dependencies = [ "memchr", ] +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + [[package]] name = "cookie" version = "0.18.2" @@ -348,6 +654,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -371,7 +687,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics-types", "foreign-types", "libc", @@ -384,7 +700,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "libc", ] @@ -421,6 +737,12 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -460,6 +782,33 @@ version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "darling" version = "0.24.1" @@ -536,6 +885,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.8" @@ -545,6 +904,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -574,6 +944,16 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", ] [[package]] @@ -643,6 +1023,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "dlv-list" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f" +dependencies = [ + "const-random", +] + [[package]] name = "dom_query" version = "0.28.0" @@ -694,6 +1083,30 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + [[package]] name = "embed-resource" version = "3.0.11" @@ -714,6 +1127,33 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -741,12 +1181,44 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + [[package]] name = "fdeflate" version = "0.3.7" @@ -756,6 +1228,12 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "field-offset" version = "0.3.6" @@ -766,6 +1244,16 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -863,6 +1351,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.34" @@ -1011,6 +1512,27 @@ dependencies = [ "version_check", ] +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link 0.2.1", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1182,12 +1704,29 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + [[package]] name = "hashbrown" version = "0.17.1" @@ -1206,6 +1745,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + [[package]] name = "hex" version = "0.4.3" @@ -1281,6 +1826,21 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.21" @@ -1300,9 +1860,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry 0.6.1", ] [[package]] @@ -1317,7 +1879,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -1449,6 +2011,20 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -1472,13 +2048,31 @@ dependencies = [ "serde_core", ] +[[package]] +name = "infer" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" +dependencies = [ + "cfb 0.7.3", +] + [[package]] name = "infer" version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" dependencies = [ - "cfb", + "cfb 0.14.0", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", ] [[package]] @@ -1487,6 +2081,25 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1530,7 +2143,7 @@ dependencies = [ "portable-atomic", "portable-atomic-util", "serde_core", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1586,6 +2199,36 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + [[package]] name = "jni-sys" version = "0.3.1" @@ -1742,6 +2385,20 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "mac-notification-sys" +version = "0.6.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca" +dependencies = [ + "cc", + "log", + "objc2", + "objc2-foundation", + "time", + "uuid", +] + [[package]] name = "markup5ever" version = "0.39.0" @@ -1811,6 +2468,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "muda" version = "0.20.0" @@ -1868,6 +2535,20 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "notify-rust" +version = "4.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe430c879247371c47fdedd328ad4e301e6b30b533c5fd5db1c06d75253d0e46" +dependencies = [ + "futures-lite", + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -1925,6 +2606,7 @@ dependencies = [ "block2", "objc2", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation", "objc2-quartz-core", ] @@ -2029,6 +2711,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", "block2", + "libc", "objc2", "objc2-core-foundation", ] @@ -2044,6 +2727,18 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-osa-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + [[package]] name = "objc2-quartz-core" version = "0.3.2" @@ -2107,12 +2802,69 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "open" +version = "5.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc" +dependencies = [ + "dunce", + "is-wsl", + "libc", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + [[package]] name = "option-ext" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordered-multimap" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79" +dependencies = [ + "dlv-list", + "hashbrown 0.14.5", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "osakit" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" +dependencies = [ + "objc2", + "objc2-foundation", + "objc2-osa-kit", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "pango" version = "0.18.3" @@ -2138,6 +2890,12 @@ dependencies = [ "system-deps", ] +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -2158,7 +2916,18 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", ] [[package]] @@ -2226,6 +2995,27 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -2271,6 +3061,31 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -2301,6 +3116,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "precomputed-hash" version = "0.1.1" @@ -2369,6 +3193,18 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quick-xml" version = "0.42.0" @@ -2399,6 +3235,44 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -2487,15 +3361,20 @@ dependencies = [ "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", "serde", "serde_json", "sync_wrapper", "tokio", + "tokio-rustls", "tokio-util", "tower", "tower-http", @@ -2507,6 +3386,54 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfd" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672" +dependencies = [ + "block2", + "dispatch2", + "glib-sys", + "gobject-sys", + "gtk-sys", + "js-sys", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.60.2", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rust-ini" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7" +dependencies = [ + "cfg-if", + "ordered-multimap", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2535,6 +3462,79 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni 0.22.4", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2550,6 +3550,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "0.8.22" @@ -2607,6 +3616,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "selectors" version = "0.38.0" @@ -2812,12 +3844,47 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "siphasher" version = "1.0.4" @@ -2894,6 +3961,16 @@ dependencies = [ "system-deps", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2930,6 +4007,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "swift-rs" version = "1.0.8" @@ -2993,6 +4076,36 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "libc", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "system-deps" version = "6.2.2" @@ -3014,7 +4127,7 @@ checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400" dependencies = [ "bitflags 2.13.2", "block2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics", "crossbeam-channel", "dbus", @@ -3024,7 +4137,7 @@ dependencies = [ "gdkwayland-sys", "gdkx11-sys", "gtk", - "jni", + "jni 0.21.1", "libc", "log", "ndk", @@ -3040,8 +4153,8 @@ dependencies = [ "tao-macros", "unicode-segmentation", "url", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", "windows-version", "x11-dl", ] @@ -3057,6 +4170,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "target-lexicon" version = "0.12.16" @@ -3072,7 +4196,7 @@ dependencies = [ "anyhow", "bytes", "cookie", - "dirs", + "dirs 7.0.0", "dunce", "embed_plist", "getrandom 0.3.4", @@ -3080,7 +4204,7 @@ dependencies = [ "gtk", "heck 0.5.0", "http", - "jni", + "jni 0.21.1", "libc", "log", "mime", @@ -3111,7 +4235,7 @@ dependencies = [ "webkit2gtk", "webview2-com", "window-vibrancy", - "windows", + "windows 0.62.2", ] [[package]] @@ -3122,7 +4246,7 @@ checksum = "5b5ae674f48836f5dd2eeaf9e221c095bd3e78a8d0439c77ca93b48740a1b644" dependencies = [ "anyhow", "cargo_toml", - "dirs", + "dirs 7.0.0", "glob", "heck 0.5.0", "json-patch", @@ -3176,6 +4300,201 @@ dependencies = [ "tauri-utils", ] +[[package]] +name = "tauri-plugin" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9ff3ebb9fda56ceb93d46f6cbb126bae82951bf43498543a5163dde5def49a1" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "walkdir", +] + +[[package]] +name = "tauri-plugin-deep-link" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77cb298007f2f26977c9ff1799d1983a453945d646a47ba2ae3c58c663a2458f" +dependencies = [ + "dunce", + "plist", + "rust-ini", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "tracing", + "url", + "windows-registry 0.5.3", + "windows-result 0.3.4", +] + +[[package]] +name = "tauri-plugin-dialog" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7527c5fd1678032d116c1a82e5d609c67370e56f858ae6cfd376bbca37fe0490" +dependencies = [ + "log", + "raw-window-handle", + "rfd", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "tauri-plugin-fs", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "tauri-plugin-fs" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "466eb32466fe5021b6728b06862f9ff14a9f7e1af890047654e03a96d7c0e1bb" +dependencies = [ + "anyhow", + "dunce", + "glob", + "log", + "objc2-foundation", + "percent-encoding", + "schemars 0.8.22", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "tauri-utils", + "thiserror 2.0.21", + "toml 1.1.6+spec-1.1.0", + "url", +] + +[[package]] +name = "tauri-plugin-notification" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9237e5cc1458bf1b31ad3c8c2c8480e86b6ecf133d00648fe6c36f25821f2f79" +dependencies = [ + "log", + "notify-rust", + "rand", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "time", + "url", +] + +[[package]] +name = "tauri-plugin-opener" +version = "2.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60d60366174b745b4ef5824b8bbc1c457fd08f0ce101ff643c0a49181a9f4e91" +dependencies = [ + "dunce", + "glob", + "objc2-app-kit", + "objc2-foundation", + "open", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "url", + "windows 0.61.3", + "zbus", +] + +[[package]] +name = "tauri-plugin-process" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74ae3d8549ae564c0397377373e262f340908eb23a5b9fbe03f2a00007dc0038" +dependencies = [ + "tauri", + "tauri-plugin", +] + +[[package]] +name = "tauri-plugin-single-instance" +version = "2.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db817fe9295e19b7d8357e900af31edb93703dd9fb6de524b007b47b6afc63b0" +dependencies = [ + "serde", + "serde_json", + "tauri", + "tauri-plugin-deep-link", + "thiserror 2.0.21", + "tokio", + "tracing", + "windows-sys 0.60.2", + "zbus", +] + +[[package]] +name = "tauri-plugin-updater" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fae4783480c5d97373b98ae9f2e70158ca992cdf29e04b236a42b1f82b1b3804" +dependencies = [ + "base64 0.22.1", + "dirs 6.0.0", + "flate2", + "futures-util", + "http", + "infer 0.19.0", + "log", + "minisign-verify", + "osakit", + "percent-encoding", + "reqwest", + "rustls", + "semver", + "serde", + "serde_json", + "tar", + "tauri", + "tauri-plugin", + "tempfile", + "thiserror 2.0.21", + "time", + "tokio", + "url", + "windows-sys 0.60.2", + "zip", +] + +[[package]] +name = "tauri-plugin-window-state" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73736611e14142408d15353e21e3cca2f12a3cfb523ad0ce85999b6d2ef1a704" +dependencies = [ + "bitflags 2.13.2", + "log", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", +] + [[package]] name = "tauri-runtime" version = "2.12.0" @@ -3186,7 +4505,7 @@ dependencies = [ "dpi", "gtk", "http", - "jni", + "jni 0.21.1", "objc2", "objc2-ui-kit", "objc2-web-kit", @@ -3198,7 +4517,7 @@ dependencies = [ "url", "webkit2gtk", "webview2-com", - "windows", + "windows 0.62.2", ] [[package]] @@ -3209,7 +4528,7 @@ checksum = "fa829eb69860cf1fb0bedb21d2d5f1effce3527d054a68ca1cd7355c654400a3" dependencies = [ "gtk", "http", - "jni", + "jni 0.21.1", "log", "objc2", "objc2-app-kit", @@ -3223,7 +4542,7 @@ dependencies = [ "url", "webkit2gtk", "webview2-com", - "windows", + "windows 0.62.2", "wry", ] @@ -3241,7 +4560,7 @@ dependencies = [ "dunce", "glob", "http", - "infer", + "infer 0.22.0", "json-patch", "log", "memchr", @@ -3276,6 +4595,17 @@ dependencies = [ "toml 1.1.6+spec-1.1.0", ] +[[package]] +name = "tauri-winrt-notification" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" +dependencies = [ + "thiserror 2.0.21", + "windows 0.62.2", + "windows-version", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -3338,6 +4668,20 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + [[package]] name = "time" version = "0.3.55" @@ -3368,6 +4712,15 @@ dependencies = [ "time-core", ] +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -3398,6 +4751,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -3559,9 +4922,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tracing-core" version = "0.1.36" @@ -3578,7 +4953,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" dependencies = [ "crossbeam-channel", - "dirs", + "dirs 7.0.0", "libappindicator", "muda", "objc2", @@ -3611,6 +4986,17 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + [[package]] name = "unicode-ident" version = "1.0.26" @@ -3623,6 +5009,22 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -3805,17 +5207,38 @@ dependencies = [ name = "waybetter-host" version = "0.1.0" dependencies = [ + "arboard", + "argon2", "base64 0.22.1", + "chacha20poly1305", "chrono", + "clipboard-win", + "ed25519-dalek", + "getrandom 0.2.17", + "gtk", + "image", "minisign-verify", + "objc2-app-kit", + "reqwest", + "rustls", "serde", "serde_json", "sha2", + "sys-locale", "tauri", + "tauri-plugin-deep-link", + "tauri-plugin-dialog", + "tauri-plugin-notification", + "tauri-plugin-opener", + "tauri-plugin-process", + "tauri-plugin-single-instance", + "tauri-plugin-updater", + "tauri-plugin-window-state", "tempfile", + "tokio", "url", "webview2-com", - "windows", + "windows 0.62.2", ] [[package]] @@ -3894,6 +5317,15 @@ dependencies = [ "system-deps", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webview2-com" version = "0.39.1" @@ -3902,8 +5334,8 @@ checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" dependencies = [ "webview2-com-macros", "webview2-com-sys", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -3924,10 +5356,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" dependencies = [ "thiserror 2.0.21", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "winapi" version = "0.3.9" @@ -3975,16 +5413,38 @@ dependencies = [ "windows-version", ] +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections 0.2.0", + "windows-core 0.61.2", + "windows-future 0.2.1", + "windows-link 0.1.3", + "windows-numerics 0.2.0", +] + [[package]] name = "windows" version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ - "windows-collections", - "windows-core", - "windows-future", - "windows-numerics", + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", ] [[package]] @@ -3993,7 +5453,20 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" dependencies = [ - "windows-core", + "windows-core 0.62.2", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", ] [[package]] @@ -4004,9 +5477,20 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", - "windows-link", - "windows-result", - "windows-strings", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading 0.1.0", ] [[package]] @@ -4015,9 +5499,9 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "windows-core", - "windows-link", - "windows-threading", + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -4042,20 +5526,67 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + [[package]] name = "windows-numerics" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ - "windows-core", - "windows-link", + "windows-core 0.62.2", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-registry" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" +dependencies = [ + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -4064,7 +5595,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -4073,7 +5613,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4085,6 +5625,15 @@ dependencies = [ "windows-targets 0.42.2", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.59.0" @@ -4094,13 +5643,22 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4127,20 +5685,46 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-threading" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4149,7 +5733,7 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4164,6 +5748,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -4176,6 +5766,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -4188,12 +5784,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -4206,6 +5814,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -4218,6 +5832,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -4230,6 +5850,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -4242,6 +5868,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.5.40" @@ -4292,7 +5924,7 @@ dependencies = [ "block2", "cookie", "crossbeam-channel", - "dirs", + "dirs 7.0.0", "dom_query", "dpi", "dunce", @@ -4300,7 +5932,7 @@ dependencies = [ "gtk", "http", "javascriptcore-rs", - "jni", + "jni 0.21.1", "libc", "ndk", "objc2", @@ -4320,8 +5952,8 @@ dependencies = [ "webkit2gtk", "webkit2gtk-sys", "webview2-com", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", "windows-version", "x11-dl", ] @@ -4347,6 +5979,33 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "yoke" version = "0.8.3" @@ -4370,6 +6029,96 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.4", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.6", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +dependencies = [ + "serde", + "winnow 1.0.4", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -4391,6 +6140,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + [[package]] name = "zerotrie" version = "0.2.5" @@ -4424,6 +6179,18 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "zip" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +dependencies = [ + "arbitrary", + "crc32fast", + "indexmap 2.14.2", + "memchr", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -4435,3 +6202,59 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 1.0.4", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.6", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.6", + "winnow 1.0.4", +] diff --git a/crates/waybetter-host/Cargo.toml b/crates/waybetter-host/Cargo.toml index 365c53b..bee6c18 100644 --- a/crates/waybetter-host/Cargo.toml +++ b/crates/waybetter-host/Cargo.toml @@ -14,7 +14,15 @@ path = "src/lib.rs" [features] default = [] # Tauri glue (webview helpers, window system menu). Off for headless tests. -tauri = ["dep:tauri", "dep:windows", "dep:webview2-com"] +tauri = ["dep:tauri", "dep:tauri-plugin-notification", "dep:tauri-plugin-updater", "dep:tokio", "dep:arboard", "dep:clipboard-win", "dep:windows", "dep:webview2-com", "dep:gtk", "dep:objc2-app-kit"] +# Store downloads (`store::net`): allow-listed https, no redirects or cookies, size caps. +net = ["dep:reqwest", "dep:rustls"] +# The whole app (`app::run_app`): window, shell and tab webviews, the generic commands and the +# Tauri plugins every wayBetter app registers. +app = ["tauri", "dep:tauri-plugin-single-instance", "dep:tauri-plugin-deep-link", "dep:tauri-plugin-window-state", "dep:tauri-plugin-opener", "dep:tauri-plugin-process", "dep:tauri-plugin-dialog"] +# macOS: the shell webview is transparent (it can rise above the tabs for its overlays); needs +# `"macOSPrivateApi": true` in the app's tauri.conf.json. Other platforms always are. +macos-private-api = ["tauri?/macos-private-api"] [dependencies] serde = { version = "1", features = ["derive"] } @@ -24,12 +32,52 @@ sha2 = "0.10" chrono = { version = "0.4", default-features = false, features = ["clock"] } minisign-verify = "0.2" base64 = "0.22" +# PNG encoding of clipboard images (media::encode_png). +image = { version = "0.25", default-features = false, features = ["png"] } +# Store catalog signatures (Ed25519 over the exact catalog bytes). +ed25519-dalek = "2" +# The OS language preference (first run, "Follow system"); no dependencies of its own on desktop. +sys-locale = "0.3" +# Encrypted settings sync (a folder the owner picks): Argon2id key from the passphrase, +# XChaCha20-Poly1305 per snapshot. Pure Rust (RustCrypto), no server, no account. +argon2 = { version = "0.5", default-features = false, features = ["alloc"] } +chacha20poly1305 = { version = "0.10", default-features = false, features = ["alloc"] } +getrandom = "0.2" tauri = { version = "2", features = ["unstable"], optional = true } +# Native OS notifications (alerts::notify); the app registers the plugin. +tauri-plugin-notification = { version = "2", optional = true } +# Signed native updates (updater, with `net`); the app registers the plugin with its endpoint and key. +tauri-plugin-updater = { version = "2", optional = true } +# The updater loop's waits. +tokio = { version = "1", features = ["time"], optional = true } +# Opt-in local clipboard history (media::clipboard), polled natively. +arboard = { version = "3", optional = true } +# `app`: single-instance (a second launch focuses the window and hands over its link), install +# links, window geometry, external links, relaunch after an update, and native dialogs. +tauri-plugin-single-instance = { version = "2", optional = true, features = ["deep-link"] } +tauri-plugin-deep-link = { version = "2", optional = true } +tauri-plugin-window-state = { version = "2", optional = true } +tauri-plugin-opener = { version = "2", optional = true } +tauri-plugin-process = { version = "2", optional = true } +tauri-plugin-dialog = { version = "2", optional = true } +reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"], optional = true } +rustls = { version = "0.23", default-features = false, features = ["ring"], optional = true } [target.'cfg(windows)'.dependencies] -windows = { version = "0.62", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging"], optional = true } +windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"], optional = true } # The WebView2 COM interfaces wry already links (hidden tabs: low memory target). webview2-com = { version = "0.39", optional = true } +# Clipboard sequence number (skip unchanged polls) and password-manager exclusion formats. +clipboard-win = { version = "5", optional = true } + +[target.'cfg(target_os = "linux")'.dependencies] +# The GTK version tauri/wry link: child webviews are laid out in a GtkOverlay (host::place_child). +gtk = { version = "0.18", optional = true } + +[target.'cfg(target_os = "macos")'.dependencies] +# The AppKit bindings wry already links (host::raise_shell re-orders the shell's WKWebView). +objc2-app-kit = { version = "0.3", optional = true, default-features = false, features = ["std", "NSGraphics", "NSResponder", "NSView", "NSWindow"] } [dev-dependencies] tempfile = "3" +tokio = { version = "1", features = ["rt"] } diff --git a/crates/waybetter-host/examples/plugin_meta.rs b/crates/waybetter-host/examples/plugin_meta.rs new file mode 100644 index 0000000..536d977 --- /dev/null +++ b/crates/waybetter-host/examples/plugin_meta.rs @@ -0,0 +1,32 @@ +//! Prints what the plugin store reads from `*.plugin.js` files, one JSON object per line: +//! `parse_meta` (name, description, version, author) and `valid_file_name`. create-waybetter's +//! tests run it on generated plugins so they are checked with the store's own rules. +//! +//! cargo run --example plugin_meta -- path/to/one.plugin.js [more.plugin.js ...] + +use std::{env, fs, path::Path, process::ExitCode}; +use waybetter_host::plugins::{parse_meta, valid_file_name}; + +fn main() -> ExitCode { + for arg in env::args().skip(1) { + let path = Path::new(&arg); + let file = path.file_name().and_then(|name| name.to_str()).unwrap_or_default(); + let Ok(source) = fs::read_to_string(path) else { + eprintln!("cannot read {arg}"); + return ExitCode::FAILURE; + }; + let meta = parse_meta(file, &source); + println!( + "{}", + serde_json::json!({ + "file": meta.file, + "name": meta.name, + "description": meta.description, + "version": meta.version, + "author": meta.author, + "validFileName": valid_file_name(file), + }) + ); + } + ExitCode::SUCCESS +} diff --git a/crates/waybetter-host/src/alerts.rs b/crates/waybetter-host/src/alerts.rs new file mode 100644 index 0000000..d3a1708 --- /dev/null +++ b/crates/waybetter-host/src/alerts.rs @@ -0,0 +1,256 @@ +//! Local-only keyword alerts: the owner's keyword list, keyword matching, snippets and rate +//! limiting, plus (with the `tauri` feature) the native notification itself. Nothing here touches +//! the network; matches come from what the site's own UI already fetched, reported by the page and +//! re-checked by the app (what a match is about, e.g. a post id or an author, is the app's). + +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::time::{Duration, Instant}; + +pub const MAX_KEYWORDS: usize = 32; +pub const MIN_KEYWORD_CHARS: usize = 2; +pub const MAX_KEYWORD_CHARS: usize = 64; +pub const MAX_SNIPPET_CHARS: usize = 280; +/// One notification per keyword per this interval. +pub const PER_KEY_INTERVAL: Duration = Duration::from_secs(60); +/// At most `GLOBAL_LIMIT` keyword notifications per `GLOBAL_WINDOW`. +pub const GLOBAL_WINDOW: Duration = Duration::from_secs(600); +pub const GLOBAL_LIMIT: usize = 6; +/// Items (posts, messages...) remembered as already notified. +const SEEN_ITEMS: usize = 2_048; + +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase", default)] +pub struct AlertSettings { + pub enabled: bool, + pub keywords: Vec, +} + +fn collapse_spaces(value: &str) -> String { + value.split_whitespace().collect::>().join(" ") +} + +pub fn normalize_keyword(value: &str) -> String { + collapse_spaces(value).to_lowercase() +} + +impl AlertSettings { + /// Trims, lowercases and de-duplicates keywords; rejects oversized lists or odd keywords. + pub fn validated(self) -> Result { + let mut seen = HashSet::new(); + let mut keywords = Vec::new(); + for raw in self.keywords { + let keyword = normalize_keyword(&raw); + if keyword.is_empty() { + continue; + } + let chars = keyword.chars().count(); + if !(MIN_KEYWORD_CHARS..=MAX_KEYWORD_CHARS).contains(&chars) || keyword.chars().any(char::is_control) { + return Err(format!( + "VALIDATION: keywords must be {MIN_KEYWORD_CHARS}-{MAX_KEYWORD_CHARS} characters" + )); + } + if seen.insert(keyword.clone()) { + keywords.push(keyword); + } + } + if keywords.len() > MAX_KEYWORDS { + return Err(format!("VALIDATION: at most {MAX_KEYWORDS} keywords")); + } + Ok(Self { enabled: self.enabled, keywords }) + } + + /// Keywords the site page should watch for; empty when alerts are off. + pub fn active_keywords(&self) -> &[String] { + if self.enabled { + &self.keywords + } else { + &[] + } + } + + /// The configured keyword a page-reported `keyword` stands for (normalized), if alerts are on. + pub fn configured(&self, keyword: &str) -> Result { + let keyword = normalize_keyword(keyword); + if !self.active_keywords().contains(&keyword) { + return Err("FORBIDDEN: keyword is not configured".into()); + } + Ok(keyword) + } +} + +/// The notification snippet for page-reported `text`: control characters and runs of white space +/// collapsed, at most [`MAX_SNIPPET_CHARS`]. The text must really contain the (normalized) keyword. +pub fn snippet(text: &str, keyword: &str) -> Result { + if text.len() > MAX_SNIPPET_CHARS * 8 { + return Err("VALIDATION: text too long".into()); + } + let text = collapse_spaces(&text.chars().map(|ch| if ch.is_control() { ' ' } else { ch }).collect::()); + if !text.to_lowercase().contains(keyword) { + return Err("VALIDATION: text does not contain the keyword".into()); + } + Ok(text.chars().take(MAX_SNIPPET_CHARS).collect()) +} + +/// Per-key minimum interval plus a global sliding-window cap. +pub struct Throttle { + per_key: Duration, + window: Duration, + limit: usize, + last: HashMap, + recent: VecDeque, +} + +impl Throttle { + pub fn new(per_key: Duration, window: Duration, limit: usize) -> Self { + Self { per_key, window, limit, last: HashMap::new(), recent: VecDeque::new() } + } + + pub fn allow(&mut self, key: &str, now: Instant) -> bool { + while self.recent.front().is_some_and(|at| now.duration_since(*at) >= self.window) { + self.recent.pop_front(); + } + if self.recent.len() >= self.limit { + return false; + } + if self.last.get(key).is_some_and(|at| now.duration_since(*at) < self.per_key) { + return false; + } + if self.last.len() > 256 { + let per_key = self.per_key; + self.last.retain(|_, at| now.duration_since(*at) < per_key); + } + self.last.insert(key.to_owned(), now); + self.recent.push_back(now); + true + } +} + +/// A keyword match about one item of the site (a post, a message...). +pub trait KeywordMatch { + /// The item's id: each item notifies at most once. + fn item_id(&self) -> &str; + /// The keyword it matched, as the page reported it. + fn keyword(&self) -> &str; +} + +/// Keyword alerts: each item notifies at most once, then the throttle applies (per keyword, and +/// at most [`GLOBAL_LIMIT`] per [`GLOBAL_WINDOW`]). +pub struct AlertGate { + seen: HashSet, + order: VecDeque, + throttle: Throttle, +} + +impl Default for AlertGate { + fn default() -> Self { + Self { + seen: HashSet::new(), + order: VecDeque::new(), + throttle: Throttle::new(PER_KEY_INTERVAL, GLOBAL_WINDOW, GLOBAL_LIMIT), + } + } +} + +impl AlertGate { + pub fn allow(&mut self, hit: &impl KeywordMatch, now: Instant) -> bool { + if !self.seen.insert(hit.item_id().to_owned()) { + return false; + } + self.order.push_back(hit.item_id().to_owned()); + if self.order.len() > SEEN_ITEMS { + if let Some(old) = self.order.pop_front() { + self.seen.remove(&old); + } + } + self.throttle.allow(&normalize_keyword(hit.keyword()), now) + } +} + +/// Shows a native OS notification (the app registers `tauri-plugin-notification`); a failure is +/// logged under the product name and otherwise ignored. +#[cfg(feature = "tauri")] +pub fn notify(app: &tauri::AppHandle, product: &str, title: &str, body: &str) { + use tauri_plugin_notification::NotificationExt; + if let Err(error) = app.notification().builder().title(title).body(body).show() { + eprintln!("{product}: notification failed: {error}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Hit(&'static str, &'static str); + + impl KeywordMatch for Hit { + fn item_id(&self) -> &str { + self.0 + } + fn keyword(&self) -> &str { + self.1 + } + } + + fn settings(words: &[&str]) -> AlertSettings { + AlertSettings { enabled: true, keywords: words.iter().map(|w| w.to_string()).collect() } + .validated() + .unwrap() + } + + #[test] + fn settings_normalize_and_dedupe() { + let s = settings(&[" Rust Lang ", "rust lang", "", "Tauri"]); + assert_eq!(s.keywords, vec!["rust lang".to_string(), "tauri".to_string()]); + } + + #[test] + fn settings_reject_bad_keywords() { + assert!(AlertSettings { enabled: true, keywords: vec!["a".into()] }.validated().is_err()); + assert!(AlertSettings { enabled: true, keywords: vec!["x".repeat(65)] }.validated().is_err()); + let many = AlertSettings { enabled: true, keywords: (0..33).map(|i| format!("kw{i}")).collect() }; + assert!(many.validated().is_err()); + assert!(AlertSettings { enabled: true, keywords: vec!["a\u{7}b".into()] }.validated().is_err()); + } + + #[test] + fn only_configured_keywords_while_enabled() { + let mut s = settings(&["tauri"]); + assert_eq!(s.configured(" TAURI ").unwrap(), "tauri"); + assert!(s.configured("electron").is_err()); + s.enabled = false; + assert!(s.active_keywords().is_empty()); + assert!(s.configured("tauri").is_err()); + } + + #[test] + fn snippets_are_plain_bounded_and_contain_the_keyword() { + assert_eq!(snippet("I love\nTauri 2", "tauri").unwrap(), "I love Tauri 2"); + assert!(snippet("nothing here", "tauri").is_err()); + let long = format!("tauri {}", "a".repeat(500)); + assert_eq!(snippet(&long, "tauri").unwrap().chars().count(), MAX_SNIPPET_CHARS); + assert!(snippet(&"tauri ".repeat(MAX_SNIPPET_CHARS * 2), "tauri").unwrap_err().contains("too long")); + } + + #[test] + fn throttle_limits_per_key_and_globally() { + let mut t = Throttle::new(Duration::from_secs(60), Duration::from_secs(600), 3); + let now = Instant::now(); + assert!(t.allow("a", now)); + assert!(!t.allow("a", now + Duration::from_secs(30))); + assert!(t.allow("a", now + Duration::from_secs(61))); + assert!(t.allow("b", now + Duration::from_secs(62))); + assert!(!t.allow("c", now + Duration::from_secs(63))); + assert!(t.allow("c", now + Duration::from_secs(601))); + } + + #[test] + fn gate_notifies_each_item_once_and_throttles_per_keyword() { + let mut gate = AlertGate::default(); + let now = Instant::now(); + assert!(gate.allow(&Hit("1", "tauri"), now)); + assert!(!gate.allow(&Hit("1", "tauri"), now + Duration::from_secs(120))); + assert!(gate.allow(&Hit("2", "Tauri"), now + Duration::from_secs(120))); + assert!(!gate.allow(&Hit("3", "TAURI "), now + Duration::from_secs(130)), "same keyword within a minute"); + } +} diff --git a/crates/waybetter-host/src/app.rs b/crates/waybetter-host/src/app.rs new file mode 100644 index 0000000..eb151e3 --- /dev/null +++ b/crates/waybetter-host/src/app.rs @@ -0,0 +1,905 @@ +//! The whole wayBetter app around one site: [`run_app`] (or [`App`]) makes the window, the trusted +//! local shell webview and one child webview per tab, registers the Tauri plugins every app uses, +//! and serves the generic commands ([`crate::commands`]): tab layout and actions, the shell's +//! focus and raise, external links, the window menu, account profiles and the language. +//! +//! The app hands it an [`AppConfig`] (its site, window title and size, which plugins it +//! configures) and a [`SiteHooks`] implementation for what only it knows (the page scripts of a +//! new tab, what happens when a site page loads, its own per-tab state), plus its own commands. +//! +//! ```ignore +//! pub fn run() { +//! waybetter_host::app::App::new(CONFIG, MySite) +//! .setup(|app| { app.manage(MyState::load(app)); Ok(()) }) +//! .run(tauri::generate_context!(), tauri::generate_handler![my_command]); +//! } +//! ``` + +use crate::{ + commands, + host::{self, emit_shell, emit_tab_state, read_json, shell_only, tab_only, tab_webview, write_json}, + i18n::{self, NativeStrings}, + layout, policy, + profiles::{self, AccountSeen, ProfileSettings}, + site::SiteSpec, + tabs::{self, parse_web_url, OpenRequest, TabLayout, TabState}, +}; +use serde::Serialize; +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use tauri::webview::{DownloadEvent, NewWindowResponse, PageLoadEvent}; +use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, Webview, WebviewBuilder, WebviewUrl, Wry}; +use tauri_plugin_opener::OpenerExt; +use url::Url; + +/// The account profiles (app data), see [`profiles`]. +pub const PROFILES_FILE: &str = "profiles.json"; +/// The owner's language and the strings native code needs (app data), see [`i18n`]. +pub const I18N_FILE: &str = "i18n.json"; + +/// What differs between wayBetter apps at the window level. +#[derive(Clone, Copy, Debug)] +pub struct AppConfig { + pub site: &'static SiteSpec, + /// Window title (and the name in "failed to launch" messages). + pub title: &'static str, + /// A previous bundle identifier whose data folders are moved over once ([`host::migrate_identifier`]). + pub legacy_identifier: Option<&'static str>, + /// First-launch window size and the smallest size, in logical px. + pub window_size: (f64, f64), + pub min_window_size: (f64, f64), + /// The window's color before the shell paints (no white flash). + pub background: (u8, u8, u8), + /// Wait for the shell's `shell_ready` command before showing the first window. + pub defer_window_show: bool, + /// The shell draws the titlebar (Windows/Linux: frameless; macOS: an overlay titlebar with the + /// traffic lights over the shell). Off: the OS frame, for a shell without one. + pub custom_titlebar: bool, + /// Register the deep-link plugin (`plugins.deep-link` in tauri.conf.json: install links). + pub deep_link: bool, + /// Register the updater plugin (`plugins.updater` in tauri.conf.json: endpoint and key). + pub updater: bool, + /// The language strings site tabs receive (key prefixes, e.g. `["x.", "kit.", "plugin."]`). + pub page_string_prefixes: &'static [&'static str], +} + +impl AppConfig { + /// The defaults: 1360x900 (at least 900x560), a near-black background, the shell's own + /// titlebar, no deep links or updater, the UI kit's and plugins' strings for site tabs. + pub const fn new(site: &'static SiteSpec, title: &'static str) -> Self { + Self { + site, + title, + legacy_identifier: None, + window_size: (1360.0, 900.0), + min_window_size: (900.0, 560.0), + background: (7, 8, 12), + defer_window_show: false, + custom_titlebar: true, + deep_link: false, + updater: false, + page_string_prefixes: &["kit.", "plugin."], + } + } +} + +/// A tab webview about to be created ([`SiteHooks::init_scripts`]). +pub struct NewTab<'a> { + pub id: &'a str, + /// `tab-` + pub label: &'a str, + /// Its account profile (fixed for the webview's life). + pub profile: &'a str, + /// The shell's layout entry it is created for (role, navigation rail, ...). + pub item: &'a TabLayout, +} + +/// Why a tab webview was closed ([`SiteHooks::tab_closed`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TabClosed { + /// Its tab moved to another account profile: a fresh webview replaces it. + Replaced, + /// Its tab is gone. + Removed, +} + +/// What only the app knows. Every method has a harmless default except the page scripts. +/// Called without any host lock held, so an implementation may use the host's helpers. +pub trait SiteHooks: Send + Sync + 'static { + /// The document-start scripts of a new tab webview, in order, the tab bridge included + /// (`waybetter_host::bridge`), then the app's page runtime. + fn init_scripts(&self, app: &AppHandle, tab: &NewTab) -> Vec; + + /// The new tab webview's background until the page paints. + fn tab_background(&self, _app: &AppHandle, _label: &str) -> Option { + None + } + + /// The URL a navigation to `url` should load instead (legacy domains), if any. + fn canonical_url(&self, _url: &Url) -> Option { + None + } + + /// Pages that stay "on the site" for link routing besides its exact origin (login routes). + fn site_navigation(&self, _url: &Url) -> bool { + false + } + + /// A navigation starts in tab `label`. Returns whether links to other sites go to the + /// system browser (the owner's setting), or None when the app's state is unavailable (the + /// navigation is refused). + fn navigation_started(&self, _app: &AppHandle, _label: &str) -> Option { + Some(false) + } + + /// Where a new-window request (target=_blank, window.open) for `url` opens: "tab", "pane" or + /// "browser". + fn new_window_mode(&self, _app: &AppHandle, _url: &Url) -> String { + "tab".into() + } + + /// A new document started loading in `tab`. + fn page_started(&self, _app: &AppHandle, _tab: &Webview) {} + + /// A document on the site finished loading in `tab` (evaluate settings, plugins, themes). + fn site_page_loaded(&self, _app: &AppHandle, _tab: &Webview, _url: &Url) {} + + /// A tab webview was created. + fn tab_created(&self, _app: &AppHandle) {} + + /// `tab` was laid out for `item` (existing or new), before it is placed. + fn tab_placed(&self, _app: &AppHandle, _tab: &Webview, _item: &TabLayout) {} + + /// Every tab's placement after a layout: (id, rect, visible). + fn layout_changed(&self, _app: &AppHandle, _layout: &[(String, layout::Rect, bool)]) {} + + /// A tab webview was closed: forget the app's per-tab state. + fn tab_closed(&self, _app: &AppHandle, _label: &str, _why: TabClosed) {} + + /// The shell was raised above the tabs (`on`) or lowered again. + fn shell_raised(&self, _app: &AppHandle, _on: bool) {} +} + +/// The account profiles and which profile each open tab webview belongs to. +#[derive(Debug, Default)] +pub struct ProfileState { + pub settings: ProfileSettings, + /// Tab webview label -> the profile its WebView data directory belongs to. + pub tab_profiles: HashMap, +} + +struct Profiles(Mutex); +struct Strings(Mutex); + +struct Host { + config: AppConfig, + hooks: Arc, +} + +fn host_state(app: &AppHandle) -> tauri::State<'_, Host> { + app.state::() +} + +/// The app's config ([`run_app`] must be running). +pub fn config(app: &AppHandle) -> AppConfig { + host_state(app).config +} + +/// The profiles lock. Never call an app hook while holding it. +pub fn profiles(app: &AppHandle) -> Result, String> { + app.try_state::() + .ok_or("DATABASE: workspace state unavailable; restart safely")? + .inner() + .0 + .lock() + .map_err(|_| "DATABASE: workspace state unavailable; restart safely".into()) +} + +/// The profile tab webview `label` belongs to. +pub fn tab_profile(app: &AppHandle, label: &str) -> Option { + profiles(app).ok()?.tab_profiles.get(label).cloned() +} + +/// A tab reported the account the site shows in it. Recorded only for that webview's own profile +/// (validated by the site's [`crate::site::AccountRules`]); the shell hears about a change. The +/// caller checks the webview is on the site right now. +pub fn account_seen(app: &AppHandle, label: &str, seen: AccountSeen) -> Result<(), String> { + let site = config(app).site; + let changed = { + let mut data = profiles(app)?; + let profile = data.tab_profiles.get(label).cloned(); + match profile { + Some(profile) if data.settings.observe(&profile, seen, &site.accounts) => Some(data.settings.clone()), + _ => None, + } + }; + if let Some(settings) = changed { + write_json(app, PROFILES_FILE, &settings)?; + emit_shell(app, tabs::EVENT_PROFILES_CHANGED, settings); + } + Ok(()) +} + +/// Opens an http(s) or mailto link in the system browser / mail app; other schemes are dropped. +pub fn open_external(app: &AppHandle, url: &Url) { + if matches!(url.scheme(), "http" | "https" | "mailto") { + let _ = app.opener().open_url(url.as_str(), None::<&str>); + } +} + +/// Shows a native OS notification under the app's name. +pub fn notify(app: &AppHandle, title: &str, body: &str) { + crate::alerts::notify(app, config(app).site.product, title, body); +} + +fn with_strings(app: &AppHandle, f: impl FnOnce(&NativeStrings) -> T) -> Option { + let state = app.try_state::()?; + let strings = state.0.lock().ok()?; + Some(f(&strings)) +} + +/// The native string `key` in the owner's language, or the compiled-in English `fallback`. +pub fn tr(app: &AppHandle, key: &str, fallback: &str) -> String { + with_strings(app, |strings| strings.get(key, fallback).to_owned()).unwrap_or_else(|| fallback.to_owned()) +} + +/// [`tr`] with `{name}` placeholders filled in (values are plain text). +pub fn trf(app: &AppHandle, key: &str, fallback: &str, params: &[(&str, &str)]) -> String { + with_strings(app, |strings| strings.format(key, fallback, params)) + .unwrap_or_else(|| NativeStrings::default().format(key, fallback, params)) +} + +/// The script handing a site tab its strings ([`AppConfig::page_string_prefixes`]), guarded to +/// the site's origin ([`i18n::page_script`]). Evaluate it at document start and on every load. +pub fn i18n_page_script(app: &AppHandle) -> String { + let config = config(app); + let payload = with_strings(app, |strings| strings.page_payload(config.page_string_prefixes)) + .unwrap_or_else(|| serde_json::json!({ "locale": "en", "dir": "ltr", "messages": {} })); + i18n::page_script(config.site, &payload) +} + +/// Whether the shell webview sits above the tab webviews (one of its overlays is open). +static SHELL_RAISED: AtomicBool = AtomicBool::new(false); + +/// Whether the shell is raised above the tabs right now (`shell_raise`). +pub fn shell_is_raised() -> bool { + SHELL_RAISED.load(Ordering::SeqCst) +} + +fn in_site(site: &SiteSpec, hooks: &dyn SiteHooks, url: &Url) -> bool { + site.is_origin(url) || hooks.site_navigation(url) +} + +// --------------------------------------------------------------------------------------------- +// Commands (commands::SHELL, commands::TAB). Each checks its caller first (testkit::assert_host_guards). + +/// Reconciles native tab webviews with the shell's panes: creates missing ones, positions and +/// shows/hides all of them, and closes webviews whose tab no longer exists. +#[tauri::command] +async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec, viewport: Option<[f64; 2]>) -> Result<(), String> { + shell_only(&webview)?; + let hooks = host_state(&app).hooks.clone(); + let window = webview.window(); + // Kept current by the window's resize events (host::follow_window_resizes): no blocking + // round trips to the event loop on every frame of a drag. + let metrics = host::window_metrics(&window).map_err(|error| format!("TAB: {error}"))?; + let win_size = LogicalSize::new(metrics.width, metrics.height); + let (maximized, frameless) = (metrics.maximized, metrics.frameless); + // Laid out for a window size that is already gone (the window was resized while this was in + // flight): re-based onto the current size like a native resize follow, never shown stale. + let rebase = host::layout_window(&metrics, viewport.map(|[width, height]| (width, height))).and_then(|old| { + let visible: Vec<_> = items.iter().filter(|item| item.visible).map(|item| (item.x, item.y, item.width, item.height)).collect(); + layout::Frame::around(&visible, old).map(|frame| (old, frame)) + }); + let mut keep = HashSet::new(); + let mut placed = Vec::new(); + for item in items { + if !policy::valid_tab_id(&item.id) { + return Err("VALIDATION: invalid tab id".into()); + } + let label = policy::tab_label(&item.id); + let current_profile = { + let data = profiles(&app)?; + if !profiles::valid_profile_id(&item.profile) || !data.settings.contains(&item.profile) { + return Err("VALIDATION: unknown profile".into()); + } + data.tab_profiles.get(&label).cloned() + }; + keep.insert(item.id.clone()); + let (item_x, item_y, item_width, item_height) = match rebase { + Some((old, frame)) => layout::follow_rect((item.x, item.y, item.width, item.height), old, (metrics.width, metrics.height), frame), + None => (item.x, item.y, item.width, item.height), + }; + let rect = policy::clamp_tab_rect(item_x, item_y, item_width, item_height, win_size.width, win_size.height, maximized, frameless) + .map_err(|error| error.to_string())?; + // Nothing left after clamping: keep (or create) the tab, but hidden. + let visible = item.visible && rect.is_some(); + let (x, y, width, height) = rect.unwrap_or((0.0, policy::TITLEBAR_H, 1.0, 1.0)); + let existing = tab_webview(&app, &item.id); + // A webview can never switch data directories: a profile change means a fresh webview, + // and the app's per-tab state goes with the old one. + let existing = match existing { + Some(tab) if current_profile.as_deref() != Some(item.profile.as_str()) => { + host::forget_tab(&app, &label); + let _ = tab.close(); + profiles(&app)?.tab_profiles.remove(&label); + hooks.tab_closed(&app, &label, TabClosed::Replaced); + None + } + other => other, + }; + let tab = match existing { + Some(tab) => tab, + None => { + let url = parse_web_url(&item.url)?; + let data_dir = app.path().app_local_data_dir().ok().and_then(|local| profiles::data_dir(&local, &item.profile)); + if item.profile != profiles::DEFAULT_PROFILE && data_dir.is_none() { + return Err("PROFILE: no local data directory".into()); + } + // Reserve the profile before the webview exists, re-checked under the lock that + // profiles_set holds, so a concurrent removal cannot delete its folder under it. + { + let mut data = profiles(&app)?; + if !data.settings.contains(&item.profile) { + return Err("VALIDATION: unknown profile".into()); + } + data.tab_profiles.insert(label.clone(), item.profile.clone()); + } + if let Some(dir) = &data_dir { + if let Err(error) = std::fs::create_dir_all(dir) { + profiles(&app)?.tab_profiles.remove(&label); + return Err(format!("PROFILE: {error}")); + } + } + let new_tab = NewTab { id: &item.id, label: &label, profile: &item.profile, item: &item }; + let builder = tab_builder(&app, &hooks, &new_tab, url, data_dir); + // The site's page color until it paints (never the WebView's white). + let builder = match hooks.tab_background(&app, &label) { + Some(color) => builder.background_color(color), + None => builder, + }; + match window.add_child(builder, LogicalPosition::new(x, y), LogicalSize::new(width, height)) { + Ok(tab) => { + hooks.tab_created(&app); + // A new child webview starts on top: keep a raised shell above it. + if shell_is_raised() { + host::raise_shell(&webview, true); + } + tab + } + Err(error) => { + profiles(&app)?.tab_profiles.remove(&label); + return Err(format!("TAB: {error}")); + } + } + } + }; + hooks.tab_placed(&app, &tab, &item); + host::place_tab(&tab, (x, y, width, height), visible, item.parked || rect.is_none()); + placed.push((item.id.clone(), (x, y, width, height), visible)); + } + host::layout_placed(&metrics); + hooks.layout_changed(&app, &placed); + for existing in window.webviews() { + if let Some(id) = policy::tab_id(existing.label()) { + if !keep.contains(id) { + let label = existing.label().to_owned(); + host::forget_tab(&app, &label); + let _ = existing.close(); + if let Ok(mut data) = profiles(&app) { + data.tab_profiles.remove(&label); + } + hooks.tab_closed(&app, &label, TabClosed::Removed); + } + } + } + Ok(()) +} + +/// Shows the native window system menu (Restore, Move, Size, Minimize, Maximize, Close) at a +/// screen position, for a right-click on the custom titlebar. No-op outside Windows. +#[tauri::command] +fn window_system_menu(webview: Webview, x: f64, y: f64) -> Result<(), String> { + shell_only(&webview)?; + host::system_menu(&webview, x, y) +} + +#[tauri::command] +async fn tab_navigate(webview: Webview, app: AppHandle, id: String, url: String) -> Result<(), String> { + shell_only(&webview)?; + host::navigate_tab(&app, &id, &url) +} + +/// back | forward | reload | stop | focus +#[tauri::command] +async fn tab_action(webview: Webview, app: AppHandle, id: String, action: String) -> Result<(), String> { + shell_only(&webview)?; + host::tab_action(&app, &id, &action) +} + +/// Gives keyboard focus back to the shell (e.g. Ctrl+L pressed inside a tab). +#[tauri::command] +async fn shell_focus(webview: Webview) -> Result<(), String> { + shell_only(&webview)?; + webview.set_focus().map_err(|error| format!("FOCUS: {error}")) +} + +/// The shell calls this after its first DOM commit, so startup never exposes an empty webview. +#[tauri::command] +async fn shell_ready(webview: Webview, app: AppHandle) -> Result<(), String> { + shell_only(&webview)?; + app.get_window(policy::MAIN_LABEL) + .ok_or("WINDOW: main window missing")? + .show() + .map_err(|error| format!("WINDOW: {error}")) +} + +/// The shell has committed a captured tab frame; its native webview can now be hidden. +#[tauri::command] +async fn tab_still_ready(webview: Webview, app: AppHandle, id: String, token: u64) -> Result<(), String> { + shell_only(&webview)?; + if !policy::valid_tab_id(&id) { return Err("VALIDATION: invalid tab id".into()); } + host::acknowledge_still(&app, &id, token); + Ok(()) +} + +/// Raises the shell above the tab webviews while one of its overlays (menu, dialog, palette, +/// drag) is open, so the panes stay on screen under it, or lowers it again. Returns whether this +/// platform can; when not, the shell hides the tabs for the overlay instead. +#[tauri::command] +async fn shell_raise(webview: Webview, app: AppHandle, on: bool) -> Result { + shell_only(&webview)?; + if on { + host_state(&app).hooks.shell_raised(&app, on); + } + SHELL_RAISED.store(on, Ordering::SeqCst); + Ok(host::raise_shell(&webview, on)) +} + +#[tauri::command] +async fn open_external_url(webview: Webview, app: AppHandle, url: String) -> Result<(), String> { + shell_only(&webview)?; + let url = parse_web_url(&url)?; + app.opener().open_url(url.as_str(), None::<&str>).map_err(|error| format!("OPEN: {error}")) +} + +#[tauri::command] +async fn profiles_get(webview: Webview, app: AppHandle) -> Result { + shell_only(&webview)?; + Ok(profiles(&app)?.settings.clone()) +} + +/// Saves the profile list (add, rename, recolor, switch active, remove). A removed profile must +/// have no open tab; its WebView data directory (that account's login) is then deleted. +#[tauri::command] +async fn profiles_set(webview: Webview, app: AppHandle, settings: ProfileSettings) -> Result { + shell_only(&webview)?; + let site = config(&app).site; + let settings = settings.validated(&site.accounts)?; + // One lock for check + save + swap: tabs_sync reserves a tab's profile under the same lock, + // so no tab can start in a profile between this check and its data folder being deleted. + let (settings, removed) = { + let mut data = profiles(&app)?; + // Accounts are what the tabs saw, never what the shell sends. + let settings = settings.keep_accounts_from(&data.settings); + let removed = data.settings.removal(&settings, data.tab_profiles.values())?; + write_json(&app, PROFILES_FILE, &settings)?; + data.settings = settings.clone(); + (settings, removed) + }; + host::remove_profile_dirs(&app, site, &removed); + Ok(settings) +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct LanguageInfo { + /// `site`, `system`, a locale tag, or empty before the shell ever chose. + preference: String, + locale: String, + /// The OS language preferences, most preferred first. + system: Vec, +} + +/// The saved language choice and the OS languages. +#[tauri::command] +async fn i18n_get(webview: Webview, app: AppHandle) -> Result { + shell_only(&webview)?; + let (preference, locale) = with_strings(&app, |strings| (strings.preference.clone(), strings.locale.clone())).unwrap_or_default(); + Ok(LanguageInfo { preference, locale, system: i18n::system_locales() }) +} + +/// Shell only: the owner's language and the strings native code and site tabs show in it +/// (validated plain text; site tabs get only [`AppConfig::page_string_prefixes`], as data). +#[tauri::command] +async fn i18n_set(webview: Webview, app: AppHandle, strings: NativeStrings) -> Result<(), String> { + shell_only(&webview)?; + let config = config(&app); + let strings = strings.validated()?; + write_json(&app, I18N_FILE, &strings)?; + let script = i18n::page_script(config.site, &strings.page_payload(config.page_string_prefixes)); + { + let state = app.state::(); + *state.0.lock().map_err(|_| "I18N: language state unavailable")? = strings; + } + host::eval_in_site_tabs(&app, config.site, &script); + Ok(()) +} + +/// Browser shortcuts pressed while a tab has keyboard focus, forwarded to the shell. +#[tauri::command] +async fn tab_shortcut(webview: Webview, app: AppHandle, shortcut: String) -> Result<(), String> { + let id = tab_only(&webview)?; + host::forward_shortcut(&app, id, shortcut) +} + +/// A link drag started in this tab (`start`, with the dragged http(s) link), an external link drag +/// entered it (`enter`), or this tab's drag ended (`end`). The shell then hides the tab webviews +/// and shows its drop zones; the link only ever opens as a new tab, like `window.open`. +#[tauri::command] +async fn tab_link_drag(webview: Webview, app: AppHandle, phase: String, url: Option) -> Result<(), String> { + let id = tab_only(&webview)?; + host::forward_link_drag(&app, id, phase, url) +} + +// --------------------------------------------------------------------------------------------- +// Tab webviews + +/// Linux: the page-level part of a tab's `on_navigation`, run when the main frame starts loading +/// `url` (WebKitGTK's navigation callback cannot tell iframes from the page). Returns false when +/// the load was redirected (a legacy domain) or stopped and handed to the browser. +fn main_frame_started(app: &AppHandle, site: &SiteSpec, hooks: &dyn SiteHooks, tab: &Webview, url: &Url) -> bool { + static ON_SITE: std::sync::OnceLock>> = std::sync::OnceLock::new(); + if let Some(site_url) = hooks.canonical_url(url) { + let tab = tab.clone(); + std::thread::spawn(move || { + let _ = tab.navigate(site_url); + }); + return false; + } + let Some(external_browser) = hooks.navigation_started(app, tab.label()) else { return false }; + let mut on_site = ON_SITE.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let was_on_site = on_site.get(tab.label()).copied().unwrap_or(false); + if external_browser && was_on_site && matches!(url.scheme(), "http" | "https") && !in_site(site, hooks, url) { + open_external(app, url); + let _ = tab.eval("window.stop()"); + return false; + } + on_site.insert(tab.label().to_owned(), site.is_origin(url)); + true +} + +/// A new tab webview: its profile's data directory, the app's document-start scripts, and the +/// navigation, pop-up, load, title and download handling every wayBetter tab gets. +fn tab_builder(app: &AppHandle, hooks: &Arc, tab: &NewTab, url: Url, data_dir: Option) -> WebviewBuilder { + let site = config(app).site; + let tab_id = tab.id.to_owned(); + let (nav_app, nav_id, nav_hooks) = (app.clone(), tab_id.clone(), hooks.clone()); + let (new_app, new_id, new_hooks) = (app.clone(), tab_id.clone(), hooks.clone()); + let (load_app, load_id, load_hooks) = (app.clone(), tab_id.clone(), hooks.clone()); + let (title_app, title_id) = (app.clone(), tab_id); + let mut builder = WebviewBuilder::new(tab.label, WebviewUrl::External(url)); + // Non-default profiles get their own cookie/storage jar; the default keeps the existing one. + if let Some(dir) = data_dir { + builder = builder.data_directory(dir); + #[cfg(target_os = "macos")] + { + builder = builder.data_store_identifier(profiles::store_identifier(tab.profile)); + } + } + for script in hooks.init_scripts(app, tab) { + builder = builder.initialization_script(script); + } + builder + // HTML5 drag and drop in the page: link drags out of it (split/tab drop zones in the shell) + // and the site's own file drops, instead of wry's OS file-drop handler (which refuses links). + .disable_drag_drop_handler() + .on_navigation(move |url| { + let app = &nav_app; + if !matches!(url.scheme(), "http" | "https") { + // about:blank and similar internal documents are fine; other schemes go to the OS. + if url.scheme() == "about" { + return true; + } + // WebKitGTK: possibly an iframe's own document (see below). + if cfg!(target_os = "linux") && matches!(url.scheme(), "blob" | "data") { + return true; + } + open_external(app, url); + return false; + } + // WebKitGTK asks this for iframe navigations too, without saying which frame (WebView2 + // asks only for the page): a signed-out page embedding a sign-in iframe would get that + // iframe's URL as the tab's address. On Linux the page-level work below runs from + // on_page_load (Started), which is the main frame only. + if cfg!(target_os = "linux") { + return true; + } + if let Some(site_url) = nav_hooks.canonical_url(url) { + if let Some(tab) = tab_webview(app, &nav_id) { + std::thread::spawn(move || { + let _ = tab.navigate(site_url); + }); + } + return false; + } + let Some(external_browser) = nav_hooks.navigation_started(app, &policy::tab_label(&nav_id)) else { return false }; + let on_site = tab_webview(app, &nav_id).and_then(|tab| tab.url().ok()).is_some_and(|current| site.is_origin(¤t)); + if external_browser && on_site && !in_site(site, &*nav_hooks, url) { + open_external(app, url); + return false; + } + emit_tab_state(app, TabState { id: nav_id.clone(), url: Some(url.to_string()), loading: Some(true), ..Default::default() }); + true + }) + .on_new_window(move |url, _| { + let app = &new_app; + if !matches!(url.scheme(), "http" | "https") { + open_external(app, &url); + return NewWindowResponse::Deny; + } + let url = new_hooks.canonical_url(&url).unwrap_or(url); + let mode = new_hooks.new_window_mode(app, &url); + if mode == "browser" { + open_external(app, &url); + } else { + emit_shell( + app, + tabs::EVENT_TAB_OPEN, + OpenRequest { url: url.to_string(), from: Some(new_id.clone()), background: false, beside: mode == "pane" }, + ); + } + NewWindowResponse::Deny + }) + .on_page_load(move |tab, payload| { + let app = &load_app; + if cfg!(target_os = "linux") + && matches!(payload.event(), PageLoadEvent::Started) + && !main_frame_started(app, site, &*load_hooks, &tab, payload.url()) + { + return; + } + let finished = matches!(payload.event(), PageLoadEvent::Finished); + if !finished { + load_hooks.page_started(app, &tab); + } + emit_tab_state(app, TabState { id: load_id.clone(), url: Some(payload.url().to_string()), loading: Some(!finished), ..Default::default() }); + if finished && site.is_origin(payload.url()) { + load_hooks.site_page_loaded(app, &tab, payload.url()); + } + }) + .on_document_title_changed(move |_, title| { + emit_tab_state(&title_app, TabState { id: title_id.clone(), title: Some(title), ..Default::default() }); + }) + .on_download(|_, event| match event { + // Ordinary browser downloads land in the user's Downloads folder. + DownloadEvent::Requested { .. } => true, + _ => true, + }) +} + +// --------------------------------------------------------------------------------------------- +// The app + +/// What the window-state plugin saves and restores: never DECORATIONS (a state file from a framed +/// build would re-enable the OS frame) or VISIBLE (the window is shown once it is placed). +pub fn window_state_flags() -> tauri_plugin_window_state::StateFlags { + use tauri_plugin_window_state::StateFlags; + StateFlags::all() - StateFlags::DECORATIONS - StateFlags::VISIBLE +} + +/// A window state saved while the window was minimized (Windows parks it at -32000,-32000 with a +/// caption-sized rectangle) or on a monitor that is gone comes back as a tiny, off-screen window +/// in which nothing works. Such geometry is replaced by `size`, centered. +pub fn reset_lost_geometry(window: &tauri::Window, size: (f64, f64), min: (f64, f64)) { + let Ok(scale) = window.scale_factor() else { return }; + let too_small = window + .inner_size() + .map(|size| size.to_logical::(scale)) + .is_ok_and(|size| size.width < min.0 || size.height < min.1); + let off_screen = match (window.outer_position(), window.outer_size(), window.available_monitors()) { + (Ok(position), Ok(size), Ok(monitors)) => !monitors.iter().any(|monitor| { + let (mp, ms) = (monitor.position(), monitor.size()); + // At least a 120 px square of the window must be on some monitor. + let overlap_x = (position.x + size.width as i32).min(mp.x + ms.width as i32) - position.x.max(mp.x); + let overlap_y = (position.y + size.height as i32).min(mp.y + ms.height as i32) - position.y.max(mp.y); + overlap_x >= 120 && overlap_y >= 120 + }), + _ => false, + }; + if too_small || off_screen { + let _ = window.set_size(LogicalSize::new(size.0, size.1)); + let _ = window.center(); + } +} + +/// The host's commands ([`commands::SHELL`], [`commands::TAB`]). +fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { + tauri::generate_handler![ + tabs_sync, + tab_navigate, + tab_action, + open_external_url, + shell_focus, + shell_ready, + tab_still_ready, + shell_raise, + window_system_menu, + profiles_get, + profiles_set, + i18n_get, + i18n_set, + tab_shortcut, + tab_link_drag + ] +} + +type Setup = Box Result<(), Box> + Send>; + +/// The app builder: config, site hooks, the app's own setup, then [`App::run`]. +pub struct App { + config: AppConfig, + hooks: Arc, + setup: Option, +} + +impl App { + pub fn new(config: AppConfig, hooks: impl SiteHooks) -> Self { + Self { config, hooks: Arc::new(hooks), setup: None } + } + + /// The app's own setup (open its database, `manage` its state), run after the host's (app + /// data folder, profiles, language) and before the window exists. + pub fn setup(mut self, setup: impl FnOnce(&AppHandle) -> Result<(), Box> + Send + 'static) -> Self { + self.setup = Some(Box::new(setup)); + self + } + + /// Runs the app: `context` is `tauri::generate_context!()` and `handler` the app's own + /// `tauri::generate_handler![...]` (the host serves [`commands::SHELL`] and [`commands::TAB`]). + pub fn run(self, context: tauri::Context, handler: H) + where + H: Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static, + { + let App { config, hooks, setup } = self; + let host_handler = host_handler(); + let builder = tauri::Builder::::default() + // Must be first: a second launch focuses the running window instead of fighting over + // the app's data and WebView profile (and hands over its link). + .plugin(tauri_plugin_single_instance::init(|app, _, _| { + if let Some(window) = app.get_window(policy::MAIN_LABEL) { + let _ = window.unminimize(); + let _ = window.show(); + let _ = window.set_focus(); + } + })); + // Install links (after single-instance, which forwards a second launch's link). + let builder = if config.deep_link { builder.plugin(tauri_plugin_deep_link::init()) } else { builder }; + let builder = builder + .plugin(tauri_plugin_window_state::Builder::default().with_state_flags(window_state_flags()).build()) + .plugin(tauri_plugin_opener::init()); + // No capability grants the updater/process JS APIs; only Rust drives them. + let builder = if config.updater { builder.plugin(tauri_plugin_updater::Builder::new().build()) } else { builder }; + builder + .plugin(tauri_plugin_process::init()) + .plugin(tauri_plugin_notification::init()) + .plugin(tauri_plugin_dialog::init()) + .setup(move |tauri_app| { + let handle = tauri_app.handle().clone(); + let site = config.site; + if let Some(legacy) = config.legacy_identifier { + host::migrate_identifier(&handle, site, legacy); + } + let directory = tauri_app.path().app_data_dir()?; + std::fs::create_dir_all(&directory)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700))?; + } + let settings = read_json::(&handle, PROFILES_FILE) + .and_then(|settings| settings.validated(&site.accounts).ok()) + .unwrap_or_default(); + host::prune_profile_dirs(&handle, &settings); + tauri_app.manage(Profiles(Mutex::new(ProfileState { settings, tab_profiles: HashMap::new() }))); + let strings = read_json::(&handle, I18N_FILE).and_then(|strings| strings.validated().ok()).unwrap_or_default(); + tauri_app.manage(Strings(Mutex::new(strings))); + tauri_app.manage(Host { config, hooks }); + if let Some(setup) = setup { + setup(&handle)?; + } + open_window(tauri_app, &config) + }) + .invoke_handler(move |invoke| { + if commands::is_host(invoke.message.command()) { + host_handler(invoke) + } else { + handler(invoke) + } + }) + .run(context) + .unwrap_or_else(|error| panic!("Failed to launch {}: {error}", config.title)); + } +} + +/// [`App::new`] + [`App::setup`] + [`App::run`] in one call. +pub fn run_app( + config: AppConfig, + hooks: impl SiteHooks, + setup: impl FnOnce(&AppHandle) -> Result<(), Box> + Send + 'static, + context: tauri::Context, + handler: H, +) where + H: Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static, +{ + App::new(config, hooks).setup(setup).run(context, handler) +} + +/// The main window (frameless on Windows/Linux, overlay titlebar on macOS) with the shell +/// webview filling it, shown once its saved geometry is restored. +fn open_window(app: &mut tauri::App, config: &AppConfig) -> Result<(), Box> { + let (r, g, b) = config.background; + let builder = tauri::window::WindowBuilder::new(app, policy::MAIN_LABEL) + .title(config.title) + .inner_size(config.window_size.0, config.window_size.1) + // The titlebar needs room for the logo, a few tabs and the caption buttons. + .min_inner_size(config.min_window_size.0, config.min_window_size.1) + // The shell draws its own titlebar (Windows 11: DWM shadow and rounded corners). + .decorations(!config.custom_titlebar) + .shadow(true) + // No white flash before the shell paints. + .background_color(tauri::window::Color(r, g, b, 255)) + .resizable(true) + // Shown after the saved geometry is restored. + .visible(false); + // macOS keeps the native frame with an overlay titlebar and traffic lights. + // (`traffic_light_position` is not on the multiwebview WindowBuilder in tauri 2.12.) + #[cfg(target_os = "macos")] + let builder = if config.custom_titlebar { + builder.decorations(true).title_bar_style(tauri::TitleBarStyle::Overlay).hidden_title(true) + } else { + builder + }; + let window = builder.build()?; + { + use tauri_plugin_window_state::WindowExt; + // Never DECORATIONS: a state file from a framed build would re-enable the OS frame. + let _ = window.restore_state(window_state_flags()); + } + reset_lost_geometry(&window, config.window_size, config.min_window_size); + // `taskkill` (and anything else closing "the first visible window") must close the app + // even when a minimized window sits below the runtime's helper windows. + host::route_helper_closes(&window); + // Tab webviews follow window resizes natively, before the shell lays out again. + host::follow_window_resizes(&window); + let size = window.inner_size()?.to_logical::(window.scale_factor()?); + // The shell fills the window; tab webviews are layered over its pane rectangles. + let shell = WebviewBuilder::new(policy::SHELL_LABEL, WebviewUrl::App("index.html".into())) + .auto_resize() + // HTML5 drag and drop (tab dragging, split drop zones) instead of OS file drops. + .disable_drag_drop_handler() + .on_navigation(|url| policy::local_navigation_allowed(url, cfg!(debug_assertions))) + .on_new_window(|_, _| NewWindowResponse::Deny); + // Raised over the tabs for an overlay (`shell_raise`), the page is see-through where the + // panes are; otherwise its own background paints as before. (macOS: `macos-private-api`.) + #[cfg(any(not(target_os = "macos"), feature = "macos-private-api"))] + let shell = shell.transparent(true); + let shell = window.add_child(shell, LogicalPosition::new(0.0, 0.0), LogicalSize::new(size.width, size.height))?; + host::attach_shell(&shell); + if config.defer_window_show { + // A shell that opts in shows the window after initial layout and sync. If JS fails to + // start, make the failure visible rather than leaving a hidden process. + let fallback = window.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs(3)); + if fallback.is_visible().is_ok_and(|visible| !visible) { + let _ = fallback.show(); + } + }); + } else { + window.show()?; + } + Ok(()) +} diff --git a/crates/waybetter-host/src/backup.rs b/crates/waybetter-host/src/backup.rs new file mode 100644 index 0000000..e6df7fd --- /dev/null +++ b/crates/waybetter-host/src/backup.rs @@ -0,0 +1,290 @@ +//! Settings backup: the versioned `.waybetter` JSON envelope, its import-side checks and the +//! sections every wayBetter app has (plugins, custom CSS, the account list). The app registers the +//! rest: which sections exist ([`parse_backup`] keeps only those) and how its own files map to +//! them. Pure (an app-data directory in, JSON out), unit-tested headless. +//! +//! Never included by these helpers: WebView profile folders (cookies, site sessions, local +//! storage), signing or sync keys, update state. [`strip_secrets`] removes secret-looking keys +//! from whatever is exported or imported as a second line of defence. + +use crate::plugins::{valid_file_name, MAX_PLUGIN_BYTES}; +use crate::profiles::{DEFAULT_COLOR, DEFAULT_PROFILE}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; +use std::fs; +use std::path::Path; + +pub const FORMAT: &str = "waybetter-backup"; +pub const VERSION: u32 = 1; +pub const EXTENSION: &str = "waybetter"; +/// Largest backup file accepted for import. +pub const MAX_BACKUP_BYTES: usize = 32 * 1024 * 1024; +pub const MAX_PLUGIN_FILES: usize = 64; +/// Largest JSON settings file a backup reads. +pub const MAX_JSON_FILE: usize = 8 * 1024 * 1024; + +/// Keys that never leave (or enter) the app through a backup, compared case-insensitively with +/// `_`/`-` removed. +const SECRET_KEYS: [&str; 22] = [ + "cookie", "cookies", "setcookie", "token", "tokens", "accesstoken", "authtoken", "refreshtoken", "idtoken", "ct0", "password", + "passphrase", "secret", "clientsecret", "session", "sessionid", "authorization", "bearer", "csrf", "csrftoken", "privatekey", + "signingkey", +]; + +fn secret_key(key: &str) -> bool { + let folded: String = key.chars().filter(|ch| *ch != '_' && *ch != '-').flat_map(char::to_lowercase).collect(); + SECRET_KEYS.contains(&folded.as_str()) || folded.ends_with("secret") || folded.ends_with("token") || folded.ends_with("password") +} + +/// Removes secret-looking keys anywhere in `value`; returns their JSON paths. +pub fn strip_secrets(value: &mut Value) -> Vec { + fn walk(value: &mut Value, path: &str, removed: &mut Vec) { + match value { + Value::Object(map) => { + let keys: Vec = map.keys().cloned().collect(); + for key in keys { + if secret_key(&key) { + map.remove(&key); + removed.push(format!("{path}.{key}")); + } else if let Some(child) = map.get_mut(&key) { + walk(child, &format!("{path}.{key}"), removed); + } + } + } + Value::Array(items) => { + for (index, item) in items.iter_mut().enumerate() { + walk(item, &format!("{path}[{index}]"), removed); + } + } + _ => {} + } + } + let mut removed = Vec::new(); + walk(value, "$", &mut removed); + removed +} + +/// A JSON settings file, if it exists, parses and is at most [`MAX_JSON_FILE`]. +pub fn read_json_file(path: &Path) -> Option { + let raw = fs::read(path).ok()?; + if raw.len() > MAX_JSON_FILE { + return None; + } + serde_json::from_slice(&raw).ok() +} + +/// A JSON object settings file, or `default` when it is missing, damaged or not an object. +pub fn object_section(path: &Path, default: Value) -> Value { + read_json_file(path).filter(Value::is_object).unwrap_or(default) +} + +/// A plugin file of the owner's: `file` + `source`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct PluginFile { + pub file: String, + pub source: String, +} + +/// The `plugins` section (enabled states + the owner's own plugin files) and the `customCss` +/// section, read from the plugin store folder. `shipped` are the plugin files the app writes +/// itself (bundled + example): untouched copies of those are left out. +pub fn plugin_sections(plugins_dir: &Path, shipped: &[(&str, &str)]) -> (Value, Value) { + let enabled: Vec = read_json_file(&plugins_dir.join("enabled.json")) + .and_then(|value| serde_json::from_value::>(value).ok()) + .unwrap_or_default() + .into_iter() + .filter(|file| valid_file_name(file)) + .collect(); + let mut files: Vec = Vec::new(); + if let Ok(entries) = fs::read_dir(plugins_dir) { + let mut names: Vec = entries.flatten().filter_map(|entry| entry.file_name().to_str().map(str::to_owned)).collect(); + names.sort(); + for file in names { + if !valid_file_name(&file) || files.len() >= MAX_PLUGIN_FILES { + continue; + } + let path = plugins_dir.join(&file); + let Ok(meta) = fs::metadata(&path) else { continue }; + if !meta.is_file() || meta.len() > MAX_PLUGIN_BYTES { + continue; + } + let Ok(source) = fs::read_to_string(&path) else { continue }; + if shipped.iter().any(|(name, content)| *name == file && *content == source) { + continue; + } + files.push(PluginFile { file, source }); + } + } + let css = fs::read_to_string(plugins_dir.join("custom.css")).unwrap_or_default(); + (json!({ "enabled": enabled, "files": files }), json!({ "css": css })) +} + +/// The `accounts` section from the profiles file: profile ids, names and colors only. The site +/// account a profile is signed in to is observed by the tabs (never imported), and its login is +/// the WebView profile folder, which a backup never reads. +pub fn accounts_section(profiles_file: &Path) -> Value { + let profiles = read_json_file(profiles_file).unwrap_or(Value::Null); + let list: Vec = profiles + .get("profiles") + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(|profile| { + Some(json!({ + "id": profile.get("id")?.as_str()?, + "name": profile.get("name").and_then(Value::as_str).unwrap_or(""), + "color": profile.get("color").and_then(Value::as_str).unwrap_or(DEFAULT_COLOR), + })) + }) + .collect() + }) + .unwrap_or_default(); + let active = profiles.get("active").and_then(Value::as_str).unwrap_or(DEFAULT_PROFILE); + json!({ "profiles": list, "active": active }) +} + +/// Finishes collected sections: secret-looking keys removed anywhere. +pub fn scrubbed(sections: Map) -> Map { + let mut value = Value::Object(sections); + strip_secrets(&mut value); + match value { + Value::Object(map) => map, + _ => Map::new(), + } +} + +/// Checks the envelope of a backup file and returns its sections (only the app's `sections`, +/// secret-looking keys removed). +pub fn parse_backup(bytes: &[u8], sections: &[&str]) -> Result, String> { + if bytes.len() > MAX_BACKUP_BYTES { + return Err("BACKUP: the file is larger than 32 MB".into()); + } + let mut value: Value = serde_json::from_slice(bytes).map_err(|error| format!("BACKUP: not a wayBetter backup (line {}: {error})", error.line()))?; + if value.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err("BACKUP: not a wayBetter backup".into()); + } + let version = value.get("version").and_then(Value::as_u64).unwrap_or(0); + if version == 0 || version > u64::from(VERSION) { + return Err(format!("BACKUP: made by a newer wayBetter (backup version {version}); update the app first")); + } + strip_secrets(&mut value); + let found = value.get_mut("sections").and_then(Value::as_object_mut).ok_or("BACKUP: the backup has no sections")?; + found.retain(|key, _| sections.contains(&key.as_str())); + Ok(std::mem::take(found)) +} + +/// The plugins section of an import: file names checked, sizes capped, at most [`MAX_PLUGIN_FILES`]. +pub fn plugins_section(value: &Value) -> Result<(Vec, Vec), String> { + let enabled: Vec = serde_json::from_value(value.get("enabled").cloned().unwrap_or(json!([]))).map_err(|_| "BACKUP: invalid plugin list")?; + let files: Vec = serde_json::from_value(value.get("files").cloned().unwrap_or(json!([]))).map_err(|_| "BACKUP: invalid plugin files")?; + if files.len() > MAX_PLUGIN_FILES || enabled.len() > 256 { + return Err("BACKUP: too many plugins".into()); + } + for name in enabled.iter().chain(files.iter().map(|file| &file.file)) { + if !valid_file_name(name) { + return Err("BACKUP: invalid plugin file name".into()); + } + } + if files.iter().any(|file| file.source.len() as u64 > MAX_PLUGIN_BYTES) { + return Err("BACKUP: a plugin file is larger than 2 MiB".into()); + } + Ok((enabled, files)) +} + +/// Writes a file next to its final name and renames it over (a running tab never reads half). +pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> { + let temp = path.with_extension("importing"); + fs::write(&temp, bytes).map_err(|error| format!("BACKUP: {error}"))?; + fs::rename(&temp, path).map_err(|error| { + let _ = fs::remove_file(&temp); + format!("BACKUP: {error}") + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SECTIONS: [&str; 3] = ["plugins", "customCss", "settings"]; + + fn write(dir: &Path, name: &str, text: &str) { + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + + #[test] + fn secret_keys_are_stripped_anywhere() { + let mut value = json!({ "a": { "Auth-Token": "t", "list": [{ "password": "p", "keep": 1 }] }, "sessionId": "s", "ok": true }); + let removed = strip_secrets(&mut value); + assert_eq!(value, json!({ "a": { "list": [{ "keep": 1 }] }, "ok": true })); + assert_eq!(removed.len(), 3); + for key in ["clientSecret", "api_token", "refresh-token", "Bearer", "ct0", "signingKey", "PASSPHRASE"] { + assert!(secret_key(key), "{key}"); + } + assert!(!secret_key("tokenizer") && !secret_key("homeUrl")); + } + + #[test] + fn plugins_css_and_accounts_sections() { + let root = tempfile::tempdir().unwrap(); + let dir = root.path(); + write(dir, "plugins/enabled.json", r#"["mine.plugin.js","../bad.plugin.js"]"#); + write(dir, "plugins/mine.plugin.js", "mine"); + write(dir, "plugins/shipped.plugin.js", "as shipped"); + write(dir, "plugins/notes.txt", "not a plugin"); + write(dir, "plugins/custom.css", "a{}"); + write(dir, "profiles.json", r##"{"profiles":[{"id":"default","name":"Main","account":{"handle":"h"}},{"id":"w","color":"#000000","authToken":"t"}]}"##); + let (plugins, css) = plugin_sections(&dir.join("plugins"), &[("shipped.plugin.js", "as shipped")]); + assert_eq!(plugins, json!({ "enabled": ["mine.plugin.js"], "files": [{ "file": "mine.plugin.js", "source": "mine" }] })); + assert_eq!(css, json!({ "css": "a{}" })); + assert_eq!( + accounts_section(&dir.join("profiles.json")), + json!({ "profiles": [{ "id": "default", "name": "Main", "color": DEFAULT_COLOR }, { "id": "w", "name": "", "color": "#000000" }], "active": "default" }) + ); + assert_eq!(object_section(&dir.join("missing.json"), json!({})), json!({})); + assert_eq!(object_section(&dir.join("plugins/enabled.json"), json!({ "d": 1 })), json!({ "d": 1 }), "not an object"); + } + + #[test] + fn envelope_keeps_only_the_apps_sections_and_no_secret() { + assert!(parse_backup(b"not json", &SECTIONS).unwrap_err().contains("line 1")); + assert!(parse_backup(br#"{"format":"other","version":1,"sections":{}}"#, &SECTIONS).is_err()); + assert!(parse_backup(br#"{"format":"waybetter-backup","version":0,"sections":{}}"#, &SECTIONS).is_err()); + assert!(parse_backup(br#"{"format":"waybetter-backup","version":99,"sections":{}}"#, &SECTIONS).unwrap_err().contains("newer")); + assert!(parse_backup(br#"{"format":"waybetter-backup","version":1}"#, &SECTIONS).unwrap_err().contains("no sections")); + assert!(parse_backup(&vec![b' '; MAX_BACKUP_BYTES + 1], &SECTIONS).unwrap_err().contains("32 MB")); + let file = json!({ "format": FORMAT, "version": VERSION, "sections": { + "settings": { "homeUrl": "https://example.com/", "token": "t" }, "other": {} + } }); + let parsed = parse_backup(&serde_json::to_vec(&file).unwrap(), &SECTIONS).unwrap(); + assert_eq!(Value::Object(parsed), json!({ "settings": { "homeUrl": "https://example.com/" } })); + let collected = scrubbed(json!({ "settings": { "password": "p", "a": 1 } }).as_object().unwrap().clone()); + assert_eq!(Value::Object(collected), json!({ "settings": { "a": 1 } })); + } + + #[test] + fn plugin_imports_are_checked() { + assert!(plugins_section(&json!({ "files": [{ "file": "../evil.plugin.js", "source": "" }] })).is_err()); + assert!(plugins_section(&json!({ "enabled": ["C:\\x.plugin.js"] })).is_err()); + assert!(plugins_section(&json!({ "files": [{ "file": "a.plugin.js", "source": "", "extra": 1 }] })).is_err()); + let big = "a".repeat(MAX_PLUGIN_BYTES as usize + 1); + assert!(plugins_section(&json!({ "files": [{ "file": "a.plugin.js", "source": big }] })).is_err()); + let many: Vec = (0..=MAX_PLUGIN_FILES).map(|n| json!({ "file": format!("p{n}.plugin.js"), "source": "" })).collect(); + assert!(plugins_section(&json!({ "files": many })).is_err()); + let (enabled, files) = plugins_section(&json!({ "enabled": ["a.plugin.js"], "files": [{ "file": "a.plugin.js", "source": "x" }] })).unwrap(); + assert_eq!((enabled.len(), files.len()), (1, 1)); + } + + #[test] + fn atomic_write_replaces_the_file() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("settings.json"); + fs::write(&path, "old").unwrap(); + write_atomic(&path, b"new").unwrap(); + assert_eq!(fs::read_to_string(&path).unwrap(), "new"); + assert!(!root.path().join("settings.importing").exists()); + } +} diff --git a/crates/waybetter-host/src/bridge.rs b/crates/waybetter-host/src/bridge.rs new file mode 100644 index 0000000..9b74f74 --- /dev/null +++ b/crates/waybetter-host/src/bridge.rs @@ -0,0 +1,67 @@ +//! The tab bridge: the script every tab webview gets as a main-frame initialization script +//! ([`script`]). It reports the tab's own URL, title, favicon and focus to the shell (`tab_report`) +//! and, when the app enables them, forwards browser shortcuts pressed in the page (`tab_shortcut`, +//! [`crate::tabs::valid_shortcut`]) and link drags (`tab_link_drag`, [`crate::tabs::link_drag`]). +//! The app's `tab-chrome` capability grants exactly the commands it calls, about the tab itself. + +/// The bridge source (`tab-bridge.js` next to this crate's `Cargo.toml`), all features on. +pub const SOURCE: &str = include_str!("../tab-bridge.js"); +const DEFAULT_OPTIONS: &str = "const options = { shortcuts: true, linkDrags: true };"; + +/// What the bridge forwards besides the tab report. Turn a feature off when the app's shell does +/// not handle it: a forwarded shortcut is taken from the page (`preventDefault`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BridgeOptions { + /// Browser shortcuts (new/close/reopen tab, reload, back/forward, split, palette, deck keys). + pub shortcuts: bool, + /// Link drags out of (or into) the page, for the shell's split/tab drop zones. + pub link_drags: bool, +} + +impl BridgeOptions { + pub const ALL: Self = Self { shortcuts: true, link_drags: true }; + /// Only `tab_report` (URL, title, favicon, focus). + pub const REPORT_ONLY: Self = Self { shortcuts: false, link_drags: false }; +} + +/// The bridge script with `options`. +pub fn script(options: BridgeOptions) -> String { + let set = format!("const options = {{ shortcuts: {}, linkDrags: {} }};", options.shortcuts, options.link_drags); + SOURCE.replacen(DEFAULT_OPTIONS, &set, 1) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn options_are_set_in_the_one_options_line() { + assert_eq!(SOURCE.matches(DEFAULT_OPTIONS).count(), 1); + assert_eq!(script(BridgeOptions::ALL), SOURCE); + let report = script(BridgeOptions::REPORT_ONLY); + assert!(report.contains("const options = { shortcuts: false, linkDrags: false };")); + assert!(!report.contains(DEFAULT_OPTIONS)); + assert!(report.contains("if (options.shortcuts) addEventListener('keydown'")); + assert!(report.contains("if (options.linkDrags) {")); + } + + #[test] + fn bridge_calls_only_the_tab_chrome_commands() { + let mut commands: Vec<&str> = SOURCE.match_indices("invoke('").map(|(at, _)| SOURCE[at + 8..].split('\'').next().unwrap()).collect(); + commands.sort(); + commands.dedup(); + assert_eq!(commands, ["tab_link_drag", "tab_report", "tab_shortcut"]); + assert!(SOURCE.contains("if (window.top !== window || window.__wbTabBridge) return;"), "top frame only, once"); + } + + #[test] + fn forwarded_shortcuts_are_ones_the_host_accepts() { + for name in ["deck-toggle", "deck-compose", "column-page-prev", "column-page-next", "column-prev", "column-next", "reopen-tab", "new-tab", + "open-panel", "close-tab", "focus-address", "command-palette", "prev-tab", "next-tab", "hard-reload", "reload", "split-down", + "split-right", "back", "forward"] { + assert!(SOURCE.contains(&format!("'{name}'")), "{name} is not in the bridge"); + assert!(crate::tabs::valid_shortcut(name), "{name} would be refused"); + } + assert!(crate::tabs::valid_shortcut("column-3")); + } +} diff --git a/crates/waybetter-host/src/commands.rs b/crates/waybetter-host/src/commands.rs new file mode 100644 index 0000000..263f656 --- /dev/null +++ b/crates/waybetter-host/src/commands.rs @@ -0,0 +1,75 @@ +//! The Tauri commands [`crate::app::run_app`] registers for every app, and who may call them. +//! +//! An app's `build.rs` lists its own commands plus these in the app-command manifest +//! ([`manifest`]), and its capability files grant [`SHELL`] to the local `shell` webview only and +//! [`TAB`] to tab webviews only; [`crate::testkit`] checks both. Every command re-checks its caller +//! natively (`host::shell_only` / `host::tab_only`) before anything else. + +/// Shell-only: the local `shell` webview (debug builds also accept the dev server). +pub const SHELL: &[&str] = &[ + "tabs_sync", + "tab_navigate", + "tab_action", + "open_external_url", + "shell_focus", + "shell_ready", + "tab_still_ready", + "shell_raise", + "window_system_menu", + "profiles_get", + "profiles_set", + "i18n_get", + "i18n_set", +]; + +/// Tab-only: any tab webview, speaking only about itself. +pub const TAB: &[&str] = &["tab_shortcut", "tab_link_drag"]; + +/// Whether `command` is one of the host's (dispatched to the host, never to the app's handler). +pub fn is_host(command: &str) -> bool { + SHELL.contains(&command) || TAB.contains(&command) +} + +/// The capability permission tauri-build generates for `command` (`tabs_sync` → `allow-tabs-sync`). +pub fn permission(command: &str) -> String { + format!("allow-{}", command.replace('_', "-")) +} + +/// The app-command manifest for `build.rs`: the app's own commands followed by the host's (each +/// once). Leaked on purpose: tauri-build wants `&'static` and a build script runs once. +/// +/// ```ignore +/// tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&["draft_list"])) +/// ``` +pub fn manifest(app: &[&'static str]) -> &'static [&'static str] { + let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len()); + for command in app.iter().chain(SHELL).chain(TAB) { + if !all.contains(command) { + all.push(command); + } + } + Box::leak(all.into_boxed_slice()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn manifest_adds_the_host_commands_once() { + let all = manifest(&["draft_list", "tabs_sync"]); + assert_eq!(all[0], "draft_list"); + assert_eq!(all.iter().filter(|c| **c == "tabs_sync").count(), 1); + for command in SHELL.iter().chain(TAB) { + assert!(all.contains(command), "{command}"); + assert!(is_host(command)); + } + assert!(!is_host("draft_list")); + assert_eq!(permission("tab_link_drag"), "allow-tab-link-drag"); + } + + #[test] + fn shell_and_tab_commands_do_not_overlap() { + assert!(!SHELL.iter().any(|command| TAB.contains(command))); + } +} diff --git a/crates/waybetter-host/src/devmode.rs b/crates/waybetter-host/src/devmode.rs new file mode 100644 index 0000000..5dcdeea --- /dev/null +++ b/crates/waybetter-host/src/devmode.rs @@ -0,0 +1,307 @@ +//! Live-reload developer mode (Settings → Developer, off by default): native code watches the +//! plugins folder (`*.plugin.js`), `custom.css` and one theme file the owner picked, and hot-reloads +//! what changed in every site tab. The app's commands for it are shell-only; site tabs gain no +//! command (they only receive the scripts native code already evaluates: plugin start/stop, custom +//! CSS, the theme preview). +//! +//! The watcher polls file signatures (length + modification time) a few times a second, which +//! works the same on every platform and for files on synced/network drives. A change is reported +//! once the file has been stable for [`DEBOUNCE`] (editors save in several writes), and changes are +//! applied in a fixed order: theme, then custom CSS, then plugins by file name, each plugin stopped +//! before its new version starts. Pure (signatures and instants in, changes out), tested headless. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant, SystemTime}; + +pub const FILE: &str = "developer.json"; +/// A file must keep the same signature this long before it counts as changed. +pub const DEBOUNCE: Duration = Duration::from_millis(250); +/// How often the watcher looks. +pub const POLL: Duration = Duration::from_millis(200); +/// Largest theme file read (a background image is a data: URL inside it). +pub const MAX_THEME_FILE: u64 = 1_200_000; +/// Shell event for everything developer mode does (`DevEvent`). +pub const EVENT: &str = "dev-event"; +/// `sourceURL` prefix of reloaded plugins (stack traces show `wb-dev/:`). +pub const SOURCE_PREFIX: &str = "wb-dev/"; + +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", default)] +pub struct DevSettings { + pub enabled: bool, + /// Absolute path of the theme JSON file to live-apply (picked in the native dialog), if any. + pub theme_file: Option, +} + +impl DevSettings { + pub fn validated(self) -> Result { + if let Some(path) = &self.theme_file { + let path = Path::new(path); + if !path.is_absolute() || path.extension().and_then(|ext| ext.to_str()).map(str::to_ascii_lowercase).as_deref() != Some("json") { + return Err("VALIDATION: the theme file must be an absolute path to a .json file".into()); + } + } + Ok(self) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Target { + Theme, + Css, + Plugin(String), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Signature { + pub len: u64, + pub modified: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Change { + Changed(Target), + Removed(Target), +} + +impl Change { + pub fn target(&self) -> &Target { + match self { + Change::Changed(target) | Change::Removed(target) => target, + } + } +} + +fn signature(path: &Path) -> Option { + let meta = fs::metadata(path).ok()?; + meta.is_file().then(|| Signature { len: meta.len(), modified: meta.modified().ok() }) +} + +/// What the watcher looks at now: every valid `*.plugin.js`, `custom.css` and the theme file. +pub fn scan(plugins_dir: &Path, theme_file: Option<&Path>) -> BTreeMap { + let mut out = BTreeMap::new(); + if let Ok(entries) = fs::read_dir(plugins_dir) { + for entry in entries.flatten() { + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue }; + if crate::plugins::valid_file_name(&name) { + if let Some(sig) = signature(&entry.path()) { + out.insert(Target::Plugin(name), sig); + } + } + } + } + if let Some(sig) = signature(&plugins_dir.join("custom.css")) { + out.insert(Target::Css, sig); + } + if let Some(sig) = theme_file.and_then(signature) { + out.insert(Target::Theme, sig); + } + out +} + +/// The debounced change detector. The first scan is the baseline (nothing is "changed" at start). +#[derive(Default)] +pub struct Watcher { + known: Option>, + /// Target → (signature seen, since when), for changes not yet stable. + pending: BTreeMap, Instant)>, +} + +impl Watcher { + pub fn new() -> Self { + Self::default() + } + + /// Feeds one scan; returns the changes that became stable, in reload order. + pub fn observe(&mut self, now: Instant, scan: BTreeMap) -> Vec { + let Some(known) = self.known.as_mut() else { + self.known = Some(scan); + return Vec::new(); + }; + let mut targets: Vec = known.keys().cloned().collect(); + for target in scan.keys() { + if !known.contains_key(target) { + targets.push(target.clone()); + } + } + for target in targets { + let current = scan.get(&target).copied(); + if current == known.get(&target).copied() { + self.pending.remove(&target); + continue; + } + match self.pending.get(&target) { + Some((seen, _)) if *seen == current => {} + _ => { + self.pending.insert(target, (current, now)); + } + } + } + let mut ready = Vec::new(); + let stable: Vec = self + .pending + .iter() + .filter(|(_, (_, since))| now.duration_since(*since) >= DEBOUNCE) + .map(|(target, _)| target.clone()) + .collect(); + for target in stable { + let Some((current, _)) = self.pending.remove(&target) else { continue }; + match current { + Some(sig) => { + known.insert(target.clone(), sig); + ready.push(Change::Changed(target)); + } + None => { + known.remove(&target); + ready.push(Change::Removed(target)); + } + } + } + reload_order(ready) + } + + /// Forgets the baseline (the next scan becomes it), e.g. after the theme file changed. + pub fn reset(&mut self) { + self.known = None; + self.pending.clear(); + } +} + +/// Theme first (so plugins read the new `--wb-*` values), then custom CSS, then plugins by name. +pub fn reload_order(mut changes: Vec) -> Vec { + changes.sort_by(|a, b| a.target().cmp(b.target())); + changes +} + +/// A JSON error position, 1-based, for the error overlay. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct DevError { + pub file: String, + pub line: Option, + pub column: Option, + pub message: String, +} + +/// Reads and checks the watched theme file: at most [`MAX_THEME_FILE`], UTF-8 (a BOM is fine), one +/// JSON object, `$schema` dropped. `build` turns that document into the app's theme preview state +/// and validates it; its error (without a `VALIDATION: ` prefix) is shown in the error overlay. +pub fn load_theme_file( + path: &Path, + build: impl FnOnce(serde_json::Map) -> Result, +) -> Result { + let file = path.file_name().and_then(|name| name.to_str()).unwrap_or("theme.json").to_owned(); + let fail = |line: Option, column: Option, message: String| DevError { file: file.clone(), line, column, message }; + let meta = fs::metadata(path).map_err(|_| fail(None, None, "The theme file is missing.".into()))?; + if meta.len() > MAX_THEME_FILE { + return Err(fail(None, None, "The theme file is larger than 1.2 MB.".into())); + } + let raw = fs::read_to_string(path).map_err(|_| fail(None, None, "The theme file is not UTF-8 text.".into()))?; + let doc: serde_json::Value = serde_json::from_str(raw.trim_start_matches('\u{feff}')).map_err(|error| { + let message = error.to_string(); + let message = message.split(" at line ").next().unwrap_or(&message).to_owned(); + fail(Some(error.line()), Some(error.column()), message) + })?; + let serde_json::Value::Object(mut object) = doc else { + return Err(fail(Some(1), Some(1), "A theme file is one JSON object.".into())); + }; + object.remove("$schema"); + build(object).map_err(|error| fail(None, None, error.trim_start_matches("VALIDATION: ").to_owned())) +} + +pub fn plugins_dir_of(app_data: &Path) -> PathBuf { + app_data.join("plugins") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sig(len: u64, secs: u64) -> Signature { + Signature { len, modified: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(secs)) } + } + + fn scan_of(items: &[(Target, Signature)]) -> BTreeMap { + items.iter().cloned().collect() + } + + #[test] + fn debounce_waits_for_a_stable_file_and_reports_once() { + let start = Instant::now(); + let at = |ms: u64| start + Duration::from_millis(ms); + let plugin = Target::Plugin("a.plugin.js".into()); + let mut watcher = Watcher::new(); + assert!(watcher.observe(at(0), scan_of(&[(plugin.clone(), sig(10, 1))])).is_empty(), "baseline"); + // An editor writes in steps: 0 bytes, then partial, then the whole file. + assert!(watcher.observe(at(100), scan_of(&[(plugin.clone(), sig(0, 2))])).is_empty()); + assert!(watcher.observe(at(200), scan_of(&[(plugin.clone(), sig(5, 2))])).is_empty()); + assert!(watcher.observe(at(300), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty()); + assert!(watcher.observe(at(500), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty(), "stable for 200 ms only"); + assert_eq!(watcher.observe(at(560), scan_of(&[(plugin.clone(), sig(12, 3))])), vec![Change::Changed(plugin.clone())]); + assert!(watcher.observe(at(900), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty(), "reported once"); + // Changed and changed back before it settled: nothing to reload. + assert!(watcher.observe(at(1000), scan_of(&[(plugin.clone(), sig(13, 4))])).is_empty()); + assert!(watcher.observe(at(1100), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty()); + assert!(watcher.observe(at(2000), scan_of(&[(plugin.clone(), sig(12, 3))])).is_empty()); + // Deleted. + assert!(watcher.observe(at(3000), BTreeMap::new()).is_empty()); + assert_eq!(watcher.observe(at(3300), BTreeMap::new()), vec![Change::Removed(plugin)]); + } + + #[test] + fn reload_order_is_theme_css_then_plugins_by_name() { + let start = Instant::now(); + let mut watcher = Watcher::new(); + let (b, a) = (Target::Plugin("b.plugin.js".into()), Target::Plugin("a.plugin.js".into())); + watcher.observe(start, scan_of(&[(b.clone(), sig(1, 1)), (a.clone(), sig(1, 1)), (Target::Css, sig(1, 1)), (Target::Theme, sig(1, 1))])); + let changed = scan_of(&[(b.clone(), sig(2, 2)), (a.clone(), sig(2, 2)), (Target::Css, sig(2, 2)), (Target::Theme, sig(2, 2))]); + watcher.observe(start + Duration::from_millis(10), changed.clone()); + let ready = watcher.observe(start + Duration::from_millis(300), changed); + assert_eq!(ready, vec![Change::Changed(Target::Theme), Change::Changed(Target::Css), Change::Changed(a), Change::Changed(b)]); + } + + #[test] + fn scan_sees_plugins_css_and_the_theme_file_only() { + let root = tempfile::tempdir().unwrap(); + let plugins = root.path().join("plugins"); + fs::create_dir_all(&plugins).unwrap(); + fs::write(plugins.join("a.plugin.js"), "x").unwrap(); + fs::write(plugins.join("notes.txt"), "x").unwrap(); + fs::write(plugins.join("enabled.json"), "[]").unwrap(); + fs::write(plugins.join("custom.css"), "a{}").unwrap(); + let theme = root.path().join("mine.json"); + fs::write(&theme, "{}").unwrap(); + let found: Vec = scan(&plugins, Some(&theme)).into_keys().collect(); + assert_eq!(found, vec![Target::Theme, Target::Css, Target::Plugin("a.plugin.js".into())]); + } + + #[test] + fn theme_file_errors_carry_line_and_column() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("mine.json"); + let id = |object: serde_json::Map| -> Result, String> { + match object.get("id").and_then(serde_json::Value::as_str) { + Some(id) if !id.contains(' ') => Ok(object), + _ => Err("VALIDATION: theme ids are slugs".into()), + } + }; + fs::write(&path, "{\n \"id\": \"mine\",\n \"name\": \"Mine\"\n \"colors\": {}\n}").unwrap(); + let error = load_theme_file(&path, id).unwrap_err(); + assert_eq!((error.file.as_str(), error.line), ("mine.json", Some(4))); + assert!(error.column.is_some() && error.message.contains("expected"), "{error:?}"); + fs::write(&path, "\u{feff}{ \"$schema\": \"https://unpkg.com/waybetter/theme.schema.json\", \"id\": \"nord\" }").unwrap(); + let doc = load_theme_file(&path, id).unwrap(); + assert!(doc.get("$schema").is_none() && doc["id"] == "nord"); + fs::write(&path, r#"{ "id": "Bad Id", "name": "x" }"#).unwrap(); + assert_eq!(load_theme_file(&path, id).unwrap_err().message, "theme ids are slugs"); + fs::write(&path, "[1]").unwrap(); + assert_eq!(load_theme_file(&path, id).unwrap_err().message, "A theme file is one JSON object."); + fs::write(&path, vec![b' '; MAX_THEME_FILE as usize + 1]).unwrap(); + assert!(load_theme_file(&path, id).unwrap_err().message.contains("larger")); + assert!(load_theme_file(&root.path().join("gone.json"), id).unwrap_err().message.contains("missing")); + assert!(DevSettings { enabled: true, theme_file: Some("relative.json".into()) }.validated().is_err()); + } +} diff --git a/crates/waybetter-host/src/fonts.rs b/crates/waybetter-host/src/fonts.rs new file mode 100644 index 0000000..dbc14a5 --- /dev/null +++ b/crates/waybetter-host/src/fonts.rs @@ -0,0 +1,308 @@ +//! Google Fonts downloads and the font cache (`net` feature): fetches woff2 files from +//! `fonts.googleapis.com`/`fonts.gstatic.com` only (allowlist re-checked before every request, no +//! redirects or cookies, size caps, woff2 magic), caches them under the app-data `fonts/` folder +//! with a sha256 manifest ([`crate::gfonts`]), and builds the page script from cached bytes, never +//! a remote font URL. The app wraps these in its own shell-only commands and, after an install or +//! removal, re-sends fonts to its site tabs. + +use crate::gfonts::{self, Face, Weights}; +use crate::site::SiteSpec; +use base64::Engine; +use serde::Serialize; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; +use url::Url; + +static ROOT: OnceLock = OnceLock::new(); + +/// Sets the font cache folder: `/fonts` (created). Call once at startup. +pub fn init(app_data: &Path) { + let root = app_data.join(gfonts::FONTS_DIR); + let _ = std::fs::create_dir_all(&root); + let _ = ROOT.set(root); +} + +pub fn root() -> Option<&'static Path> { + ROOT.get().map(PathBuf::as_path) +} + +fn root_or_err() -> Result<&'static Path, String> { + root().ok_or_else(|| "STORAGE: no application data directory".into()) +} + +/// Installed-family faces (`faces_json`), keyed by family; lazily filled, invalidated on install/remove. +static FACES: Mutex>> = Mutex::new(None); +/// Text-subset preview cache, keyed by `"||"`, capped at 400 entries. +static PREVIEWS: Mutex>>> = Mutex::new(None); +/// At most 6 preview fetches in flight (no `tokio::sync::Semaphore`: only the `time` feature is enabled). +static PREVIEW_INFLIGHT: AtomicUsize = AtomicUsize::new(0); +const MAX_PREVIEW_INFLIGHT: usize = 6; +const MAX_PREVIEW_CACHE: usize = 400; + +fn invalidate_caches() { + *FACES.lock().unwrap_or_else(|e| e.into_inner()) = None; + *PREVIEWS.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +fn faces_for(family: &str) -> Option { + let mut guard = FACES.lock().unwrap_or_else(|e| e.into_inner()); + let cache = guard.get_or_insert_with(HashMap::new); + if let Some(value) = cache.get(family) { + return Some(value.clone()); + } + drop(guard); + + let root = root()?; + let manifest = gfonts::read_manifest(root, family)?; + let dir = gfonts::family_dir(root, family)?; + let bytes = gfonts::verify_cached(&dir, &manifest).ok()?; + let value = gfonts::faces_json(&manifest, &bytes); + + let mut guard = FACES.lock().unwrap_or_else(|e| e.into_inner()); + guard.get_or_insert_with(HashMap::new).insert(family.to_string(), value.clone()); + Some(value) +} + +/// Builds the page script for up to 8 distinct, installed, valid families. Missing families are +/// skipped silently (e.g. removed since the page last asked). +pub fn page_script_for(site: &SiteSpec, families: &[String]) -> Option { + let mut seen = std::collections::HashSet::new(); + let mut fonts = Vec::new(); + for family in families { + if fonts.len() >= 8 || !seen.insert(family.clone()) { + continue; + } + if !gfonts::valid_family(family) { + continue; + } + if let Some(value) = faces_for(family) { + fonts.push(value); + } + } + gfonts::page_script(site, &fonts) +} + +fn client() -> Result<&'static reqwest::Client, String> { + static CLIENT: OnceLock = OnceLock::new(); + if let Some(client) = CLIENT.get() { + return Ok(client); + } + if rustls::crypto::CryptoProvider::get_default().is_none() { + let _ = rustls::crypto::ring::default_provider().install_default(); + } + let client = reqwest::Client::builder() + .user_agent(gfonts::USER_AGENT) + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(30)) + .build() + .map_err(|e| format!("NETWORK: {e}"))?; + Ok(CLIENT.get_or_init(|| client)) +} + +async fn read_limited(mut response: reqwest::Response, max: usize) -> Result, String> { + if response.content_length().is_some_and(|len| len as usize > max) { + return Err("NETWORK: response too large".into()); + } + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|e| format!("NETWORK: {e}"))? { + if bytes.len() + chunk.len() > max { + return Err("NETWORK: response too large".into()); + } + bytes.extend_from_slice(&chunk); + } + Ok(bytes) +} + +/// Fetches `url`, re-checking the css/file allowlist right before the request. A 400 means Google +/// didn't recognize the family/kit; any other non-200 is a plain network error. +async fn fetch(url: &Url, max: usize) -> Result, String> { + if !gfonts::allowed_css_url(url) && !gfonts::allowed_file_url(url) { + return Err("VALIDATION: URL not allowed".into()); + } + let response = client()?.get(url.clone()).send().await.map_err(|e| format!("NETWORK: {e}"))?; + let status = response.status(); + if status.as_u16() == 400 { + return Err("FONTS: unknown family".into()); + } + if status.as_u16() != 200 { + return Err(format!("NETWORK: status {}", status.as_u16())); + } + read_limited(response, max).await +} + +async fn download_faces(faces: Vec, per_file_max: usize, family_max: Option) -> Result)>, String> { + let mut out = Vec::with_capacity(faces.len()); + let mut total = 0usize; + for face in faces { + let url = Url::parse(&face.url).map_err(|_| "VALIDATION: invalid face URL")?; + let bytes = fetch(&url, per_file_max).await?; + if !gfonts::is_woff2(&bytes) { + return Err("FONTS: invalid font file".into()); + } + total += bytes.len(); + if let Some(max) = family_max { + if total > max { + return Err("FONTS: family too large".into()); + } + } + out.push((face, bytes)); + } + Ok(out) +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InstalledFont { + family: String, + weights: Weights, + bytes: usize, + faces: usize, + installed_at: String, +} + +impl From for InstalledFont { + fn from(m: gfonts::Manifest) -> Self { + InstalledFont { family: m.family, weights: m.weights, bytes: m.bytes, faces: m.faces.len(), installed_at: m.installed_at } + } +} + +/// The installed families. +pub fn installed() -> Result, String> { + let root = root_or_err()?; + Ok(gfonts::list_installed(root).into_iter().map(InstalledFont::from).collect()) +} + +/// Downloads and caches `family` in `weights` (replacing an installed copy). The caller re-sends +/// fonts to its tabs afterwards. +pub async fn install(family: String, weights: Weights) -> Result { + if !gfonts::valid_family(&family) { + return Err("VALIDATION: invalid family name".into()); + } + weights.validate()?; + let root = root_or_err()?; + + let already_installed = gfonts::read_manifest(root, &family).is_some(); + let installed = gfonts::list_installed(root); + if !already_installed && installed.len() >= gfonts::MAX_FAMILIES { + return Err("FONTS: too many installed families".into()); + } + let current_bytes: usize = installed.iter().filter(|m| m.family != family).map(|m| m.bytes).sum(); + + let css_url = gfonts::css_url(&family, &weights, None)?; + let css_bytes = fetch(&css_url, gfonts::MAX_CSS_BYTES).await?; + let css = String::from_utf8(css_bytes).map_err(|_| "FONTS: invalid CSS response")?; + let faces = gfonts::select_faces(gfonts::parse_css(&css)?); + if faces.is_empty() { + return Err("FONTS: no usable font faces".into()); + } + + let remaining = gfonts::MAX_CACHE_BYTES.saturating_sub(current_bytes); + let downloaded = download_faces(faces, gfonts::MAX_FILE_BYTES, Some(remaining.min(gfonts::MAX_FAMILY_BYTES))).await?; + + let installed_at = chrono::Utc::now().to_rfc3339(); + let manifest = gfonts::write_family(root, &family, &weights, &downloaded, installed_at)?; + + invalidate_caches(); + Ok(InstalledFont::from(manifest)) +} + +/// Removes an installed family. The caller re-sends fonts to its tabs afterwards. +pub fn remove(family: &str) -> Result<(), String> { + let root = root_or_err()?; + gfonts::remove_family(root, family)?; + invalidate_caches(); + Ok(()) +} + +/// An installed family's faces with their bytes (verified against the manifest). +pub fn faces(family: &str) -> Result { + if !gfonts::valid_family(family) { + return Err("VALIDATION: invalid family name".into()); + } + faces_for(family).ok_or_else(|| "FONTS: not installed".to_string()) +} + +fn preview_key(family: &str, weights: &Weights, text: &str) -> String { + format!("{family}|{}|{text}", weights.query()) +} + +/// A text-subset preview of a family that is not installed (cached, at most 6 fetches at once). +pub async fn preview(family: String, weights: Weights, text: String) -> Result, String> { + let key = preview_key(&family, &weights, &text); + { + let mut guard = PREVIEWS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(cached) = guard.get_or_insert_with(HashMap::new).get(&key) { + return Ok(cached.clone()); + } + } + + if PREVIEW_INFLIGHT.fetch_add(1, Ordering::SeqCst) >= MAX_PREVIEW_INFLIGHT { + PREVIEW_INFLIGHT.fetch_sub(1, Ordering::SeqCst); + return Err("FONTS: busy".into()); + } + let result = preview_inner(&family, &weights, &text).await; + PREVIEW_INFLIGHT.fetch_sub(1, Ordering::SeqCst); + let faces = result?; + + let mut guard = PREVIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let cache = guard.get_or_insert_with(HashMap::new); + if cache.len() >= MAX_PREVIEW_CACHE { + cache.clear(); + } + cache.insert(key, faces.clone()); + Ok(faces) +} + +async fn preview_inner(family: &str, weights: &Weights, text: &str) -> Result, String> { + let css_url = gfonts::css_url(family, weights, Some(text))?; + let css_bytes = fetch(&css_url, gfonts::MAX_CSS_BYTES).await?; + let css = String::from_utf8(css_bytes).map_err(|_| "FONTS: invalid CSS response")?; + let faces = gfonts::select_faces(gfonts::parse_css(&css)?); + if faces.is_empty() { + return Err("FONTS: no usable font faces".into()); + } + let downloaded = download_faces(faces, gfonts::MAX_PREVIEW_BYTES, None).await?; + + let encoder = base64::engine::general_purpose::STANDARD; + Ok(downloaded + .into_iter() + .map(|(face, bytes)| { + serde_json::json!({ + "weight": [face.weight.0, face.weight.1], + "unicodeRange": face.unicode_range, + "data": encoder.encode(&bytes), + }) + }) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::site::testing::SITE; + + #[test] + fn cache_serves_installed_families_to_the_page_and_forgets_removed_ones() { + let data = tempfile::tempdir().unwrap(); + init(data.path()); + let root = root().unwrap(); + assert!(installed().unwrap().is_empty()); + let mut bytes = vec![0u8; 100]; + bytes[0..4].copy_from_slice(b"wOF2"); + bytes[8..12].copy_from_slice(&100u32.to_be_bytes()); + let face = Face { subset: Some("latin".into()), style: "normal".into(), weight: (400, 400), url: "https://fonts.gstatic.com/s/x.woff2".into(), unicode_range: None }; + gfonts::write_family(root, "Lato", &Weights::List { values: vec![400] }, &[(face, bytes)], "2026-01-01T00:00:00Z".into()).unwrap(); + assert_eq!(installed().unwrap().len(), 1); + assert_eq!(faces("Lato").unwrap()["family"], "Lato"); + assert!(faces("../Lato").is_err()); + let families = ["Lato".to_owned(), "Lato".to_owned(), "Missing".to_owned(), "bad/name".to_owned()]; + let script = page_script_for(&SITE, &families).unwrap(); + assert_eq!(script.matches("\"family\":\"Lato\"").count(), 1, "deduplicated, missing and invalid skipped"); + remove("Lato").unwrap(); + assert!(faces("Lato").is_err(), "the face cache is invalidated"); + assert!(page_script_for(&SITE, &families).is_none()); + } +} diff --git a/crates/waybetter-host/src/gfonts.rs b/crates/waybetter-host/src/gfonts.rs new file mode 100644 index 0000000..920c2e7 --- /dev/null +++ b/crates/waybetter-host/src/gfonts.rs @@ -0,0 +1,750 @@ +//! Google Fonts, self-hosted: a site's CSP usually blocks remote `@font-face` fetches, so the app +//! downloads woff2 files natively (`fonts.googleapis.com`/`fonts.gstatic.com` only) and hands the +//! raw bytes to site pages as `FontFace(ArrayBuffer)`. +//! +//! Pure module (no network, no Tauri): CSS parsing, URL/byte validation, the on-disk cache format +//! and the page script. [`crate::fonts`] (`net` feature) downloads and caches with it. + +use crate::site::SiteSpec; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use url::Url; + +pub const CSS_ORIGIN: &str = "https://fonts.googleapis.com"; +pub const FILE_HOST: &str = "fonts.gstatic.com"; +pub const MAX_CSS_BYTES: usize = 256 * 1024; +pub const MAX_FILE_BYTES: usize = 1_500_000; +pub const MAX_FAMILY_BYTES: usize = 4_000_000; +pub const MAX_CACHE_BYTES: usize = 80_000_000; +pub const MAX_FAMILIES: usize = 64; +pub const MAX_PREVIEW_TEXT: usize = 120; +pub const MAX_PREVIEW_BYTES: usize = 300_000; +pub const KEEP_SUBSETS: [&str; 2] = ["latin", "latin-ext"]; +pub const FONTS_DIR: &str = "fonts"; +pub const MANIFEST: &str = "manifest.json"; +/// Google only serves woff2 to modern desktop browsers; a stale/unknown UA gets ttf/eot instead. +pub const USER_AGENT: &str = + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"; + +/// Google family names: letters, digits and single interior spaces (`"Noto Sans JP"`, `"Lato"`). +pub fn valid_family(name: &str) -> bool { + if name.is_empty() || name.len() > 48 { + return false; + } + let bytes = name.as_bytes(); + if bytes[0] == b' ' || bytes[bytes.len() - 1] == b' ' { + return false; + } + if name.contains(" ") { + return false; + } + bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b' ') +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", tag = "kind")] +pub enum Weights { + Range { min: u16, max: u16 }, + List { values: Vec }, +} + +impl Weights { + pub fn validate(&self) -> Result<(), String> { + match self { + Weights::Range { min, max } => { + if !(100..=1000).contains(min) || !(100..=1000).contains(max) || min > max { + return Err("VALIDATION: invalid weight range".into()); + } + Ok(()) + } + Weights::List { values } => { + if values.is_empty() || values.len() > 9 { + return Err("VALIDATION: 1-9 weights".into()); + } + if !values.iter().all(|w| (100..=1000).contains(w)) { + return Err("VALIDATION: invalid weight".into()); + } + let mut sorted = values.clone(); + sorted.sort_unstable(); + sorted.dedup(); + if sorted.len() != values.len() { + return Err("VALIDATION: duplicate weight".into()); + } + Ok(()) + } + } + } + + /// The css2 `wght@...` axis query, e.g. `"wght@100..900"` or `"wght@400;700"`. + pub fn query(&self) -> String { + match self { + Weights::Range { min, max } => format!("wght@{min}..{max}"), + Weights::List { values } => { + let mut sorted = values.clone(); + sorted.sort_unstable(); + let parts: Vec = sorted.iter().map(|w| w.to_string()).collect(); + format!("wght@{}", parts.join(";")) + } + } + } +} + +/// Builds `https://fonts.googleapis.com/css2?family=:&display=swap[&text=...]`. +pub fn css_url(family: &str, weights: &Weights, text: Option<&str>) -> Result { + if !valid_family(family) { + return Err("VALIDATION: invalid family name".into()); + } + weights.validate()?; + if let Some(text) = text { + let chars = text.chars().count(); + if chars == 0 || chars > MAX_PREVIEW_TEXT { + return Err("VALIDATION: preview text length".into()); + } + if text.chars().any(|c| c.is_control()) { + return Err("VALIDATION: preview text contains control characters".into()); + } + } + let mut url = Url::parse(&format!("{CSS_ORIGIN}/css2")).map_err(|_| "VALIDATION: unreachable")?; + { + let mut pairs = url.query_pairs_mut(); + pairs.append_pair("family", &format!("{family}:{}", weights.query())); + pairs.append_pair("display", "swap"); + if let Some(text) = text { + pairs.append_pair("text", text); + } + } + Ok(url) +} + +/// `https://fonts.googleapis.com/css2?...` only, no userinfo, no explicit port. +pub fn allowed_css_url(u: &Url) -> bool { + u.scheme() == "https" + && u.host_str() == Some("fonts.googleapis.com") + && u.path() == "/css2" + && u.username().is_empty() + && u.password().is_none() + && u.port().is_none() +} + +/// `https://fonts.gstatic.com/s/...` (static) or `/l/font...` (`&text=` subset preview) only. +pub fn allowed_file_url(u: &Url) -> bool { + u.scheme() == "https" + && u.host_str() == Some(FILE_HOST) + && u.username().is_empty() + && u.password().is_none() + && u.port().is_none() + && (u.path().starts_with("/s/") || u.path().starts_with("/l/font")) +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Face { + pub subset: Option, + pub style: String, + pub weight: (u16, u16), + pub url: String, + pub unicode_range: Option, +} + +fn slice_between<'a>(text: &'a str, start: &str, terminators: &[char]) -> Option<&'a str> { + let idx = text.find(start)? + start.len(); + let rest = &text[idx..]; + let end = rest.find(|c| terminators.contains(&c)).unwrap_or(rest.len()); + Some(rest[..end].trim()) +} + +/// Parses `font-weight: 400;` or `font-weight: 100 900;` into `(min, max)`. +fn parse_weight(value: &str) -> Option<(u16, u16)> { + let mut parts = value.split_whitespace(); + let a: u16 = parts.next()?.parse().ok()?; + let b: u16 = match parts.next() { + Some(s) => s.parse().ok()?, + None => a, + }; + if parts.next().is_some() { + return None; + } + if !(1..=1000).contains(&a) || !(1..=1000).contains(&b) { + return None; + } + Some((a.min(b), a.max(b))) +} + +/// Extracts the first `url(...) format('woff2')` from a `src:` declaration value. +fn woff2_url(src: &str) -> Option { + let mut rest = src; + loop { + let url_idx = rest.find("url(")?; + let after_url = &rest[url_idx + 4..]; + let close = after_url.find(')')?; + let raw = after_url[..close].trim(); + let raw = raw.trim_matches(|c| c == '\'' || c == '"'); + let after_close = &after_url[close + 1..]; + let format_ok = after_close + .find("format(") + .map(|fi| { + let fafter = &after_close[fi + 7..]; + let fclose = fafter.find(')').unwrap_or(0); + let fmt = fafter[..fclose].trim().trim_matches(|c| c == '\'' || c == '"'); + fmt.eq_ignore_ascii_case("woff2") + }) + .unwrap_or(false); + // Stop scanning this declaration once we pass the next comma boundary (a src: list entry). + let boundary = after_close.find(',').unwrap_or(after_close.len()); + if format_ok { + return Some(raw.to_string()); + } + rest = &after_close[boundary..]; + if !rest.contains("url(") { + return None; + } + } +} + +/// Hand-written `@font-face` block parser (no regex crate): tracks the `/* subset */` comment +/// that precedes each block, and pulls `font-style`, `font-weight`, `src` (woff2 only) and +/// `unicode-range` out of it. +pub fn parse_css(css: &str) -> Result, String> { + let trimmed = css.trim_start(); + if trimmed.starts_with('<') { + return Err("FONTS: unknown family".into()); + } + let mut faces = Vec::new(); + let mut pos = 0usize; + let mut pending_subset: Option = None; + while let Some(rel) = { + let comment_rel = css[pos..].find("/*"); + let face_rel = css[pos..].find("@font-face"); + match (comment_rel, face_rel) { + (Some(c), Some(f)) => Some(c.min(f)), + (Some(c), None) => Some(c), + (None, Some(f)) => Some(f), + (None, None) => None, + } + } { + let abs = pos + rel; + if css[abs..].starts_with("/*") { + let after = abs + 2; + let Some(end_rel) = css[after..].find("*/") else { break }; + let comment = css[after..after + end_rel].trim(); + if !comment.is_empty() && comment.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') { + pending_subset = Some(comment.to_string()); + } + pos = after + end_rel + 2; + continue; + } + // "@font-face" + let Some(brace_rel) = css[abs..].find('{') else { break }; + let brace_abs = abs + brace_rel; + let Some(close_rel) = css[brace_abs..].find('}') else { break }; + let block = &css[brace_abs + 1..brace_abs + close_rel]; + pos = brace_abs + close_rel + 1; + + let style = slice_between(block, "font-style:", &[';']).unwrap_or("normal").to_string(); + let weight_raw = slice_between(block, "font-weight:", &[';']); + let src_raw = slice_between(block, "src:", &[';']); + let unicode_range = slice_between(block, "unicode-range:", &[';']).map(|s| s.to_string()); + + let (Some(weight_raw), Some(src_raw)) = (weight_raw, src_raw) else { + pending_subset = None; + continue; + }; + let Some(weight) = parse_weight(weight_raw) else { + pending_subset = None; + continue; + }; + let Some(url_str) = woff2_url(src_raw) else { + pending_subset = None; + continue; + }; + let Ok(parsed_url) = Url::parse(&url_str) else { + pending_subset = None; + continue; + }; + if !allowed_file_url(&parsed_url) { + pending_subset = None; + continue; + } + + faces.push(Face { subset: pending_subset.take(), style, weight, url: url_str, unicode_range }); + } + if faces.is_empty() { + return Err("FONTS: no usable font faces".into()); + } + Ok(faces) +} + +/// Keeps normal-style faces; if any carry a subset label, keeps only `latin`/`latin-ext` +/// (unlabeled faces, e.g. a `&text=` preview, are all kept). Capped at 24 faces. +pub fn select_faces(faces: Vec) -> Vec { + let normal: Vec = faces.into_iter().filter(|f| f.style == "normal").collect(); + let has_labels = normal.iter().any(|f| f.subset.is_some()); + let mut kept: Vec = if has_labels { + normal.into_iter().filter(|f| f.subset.as_deref().is_some_and(|s| KEEP_SUBSETS.contains(&s))).collect() + } else { + normal + }; + kept.truncate(24); + kept +} + +/// WOFF2 header: signature(4) flavor(4) length(4) numTables(2) reserved(2) totalSfntSize(4) +/// totalCompressedSize(4) majorVersion(2) minorVersion(2) metaOffset(4) metaLength(4) +/// metaOrigLength(4) privOffset(4) privLength(4) = 48 bytes. +pub fn is_woff2(bytes: &[u8]) -> bool { + if bytes.len() < 48 || &bytes[0..4] != b"wOF2" { + return false; + } + let length = u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize; + length == bytes.len() +} + +pub fn slug(family: &str) -> String { + family.to_lowercase().replace(' ', "-") +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CachedFace { + /// `"0.woff2"`, `"1.woff2"`, ... + pub file: String, + pub weight: [u16; 2], + pub unicode_range: Option, + pub subset: Option, + pub bytes: usize, + /// Lowercase hex. + pub sha256: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Manifest { + pub family: String, + pub weights: Weights, + pub faces: Vec, + pub bytes: usize, + /// RFC3339. + pub installed_at: String, + pub source: String, +} + +fn valid_face_file(file: &str) -> Option { + let n = file.strip_suffix(".woff2")?; + if n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) || (n.len() > 1 && n.starts_with('0')) { + return None; + } + let n: usize = n.parse().ok()?; + if n >= 24 { + return None; + } + Some(n) +} + +impl Manifest { + pub fn validate(&self) -> Result<(), String> { + if !valid_family(&self.family) { + return Err("VALIDATION: invalid family name".into()); + } + self.weights.validate()?; + if self.faces.is_empty() || self.faces.len() > 24 { + return Err("VALIDATION: invalid face count".into()); + } + let mut total = 0usize; + for face in &self.faces { + if valid_face_file(&face.file).is_none() { + return Err("VALIDATION: invalid cached face file name".into()); + } + if face.sha256.len() != 64 || !face.sha256.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("VALIDATION: invalid sha256".into()); + } + if face.weight[0] > face.weight[1] || face.weight[0] < 1 || face.weight[1] > 1000 { + return Err("VALIDATION: invalid cached face weight".into()); + } + total += face.bytes; + } + if total != self.bytes || total > MAX_FAMILY_BYTES { + return Err("VALIDATION: family size mismatch".into()); + } + Ok(()) + } +} + +fn sha256_hex(bytes: &[u8]) -> String { + let mut hasher = Sha256::new(); + hasher.update(bytes); + hasher.finalize().iter().map(|b| format!("{b:02x}")).collect() +} + +/// Reads and verifies every cached face file under `dir` against `manifest`; returns their bytes +/// in manifest order. Any size/hash/magic mismatch is treated as a damaged cache, not a partial one. +pub fn verify_cached(dir: &Path, manifest: &Manifest) -> Result>, String> { + manifest.validate()?; + let mut out = Vec::with_capacity(manifest.faces.len()); + for face in &manifest.faces { + let bytes = std::fs::read(dir.join(&face.file)).map_err(|_| "FONTS: cache damaged")?; + if bytes.len() != face.bytes || !is_woff2(&bytes) || sha256_hex(&bytes) != face.sha256 { + return Err("FONTS: cache damaged".into()); + } + out.push(bytes); + } + Ok(out) +} + +/// `fonts_root/`, or `None` when `family` is not a valid Google Fonts name. +pub fn family_dir(fonts_root: &Path, family: &str) -> Option { + if !valid_family(family) { + return None; + } + Some(fonts_root.join(slug(family))) +} + +pub fn read_manifest(fonts_root: &Path, family: &str) -> Option { + let dir = family_dir(fonts_root, family)?; + let text = std::fs::read_to_string(dir.join(MANIFEST)).ok()?; + let manifest: Manifest = serde_json::from_str(&text).ok()?; + manifest.validate().ok()?; + if manifest.family != family { + return None; + } + Some(manifest) +} + +pub fn list_installed(fonts_root: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(fonts_root) else { return Vec::new() }; + let mut out = Vec::new(); + for entry in entries.flatten() { + if out.len() >= MAX_FAMILIES { + break; + } + let Ok(file_type) = entry.file_type() else { continue }; + if !file_type.is_dir() { + continue; + } + let text = std::fs::read_to_string(entry.path().join(MANIFEST)).ok(); + let Some(text) = text else { continue }; + let Ok(manifest) = serde_json::from_str::(&text) else { continue }; + if manifest.validate().is_err() { + continue; + } + out.push(manifest); + } + out +} + +pub fn cache_bytes(fonts_root: &Path) -> usize { + list_installed(fonts_root).iter().map(|m| m.bytes).sum() +} + +/// Validates every buffer, writes them into a fresh temp sibling directory, then swaps it in for +/// the family directory (best-effort atomic: remove old, rename temp into place). +pub fn write_family( + fonts_root: &Path, + family: &str, + weights: &Weights, + faces: &[(Face, Vec)], + installed_at: String, +) -> Result { + if !valid_family(family) { + return Err("VALIDATION: invalid family name".into()); + } + weights.validate()?; + if faces.is_empty() || faces.len() > 24 { + return Err("VALIDATION: invalid face count".into()); + } + let mut total = 0usize; + for (_, bytes) in faces { + if bytes.len() > MAX_FILE_BYTES || !is_woff2(bytes) { + return Err("FONTS: invalid font file".into()); + } + total += bytes.len(); + } + if total > MAX_FAMILY_BYTES { + return Err("FONTS: family too large".into()); + } + + let final_dir = family_dir(fonts_root, family).ok_or("VALIDATION: invalid family name")?; + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let tmp_dir = fonts_root.join(format!(".tmp-{}-{}-{unique}", slug(family), std::process::id())); + std::fs::create_dir_all(&tmp_dir).map_err(|error| format!("STORAGE: {error}"))?; + + let mut cached_faces = Vec::with_capacity(faces.len()); + for (index, (face, bytes)) in faces.iter().enumerate() { + let file = format!("{index}.woff2"); + std::fs::write(tmp_dir.join(&file), bytes).map_err(|error| format!("STORAGE: {error}"))?; + cached_faces.push(CachedFace { + file, + weight: [face.weight.0, face.weight.1], + unicode_range: face.unicode_range.clone(), + subset: face.subset.clone(), + bytes: bytes.len(), + sha256: sha256_hex(bytes), + }); + } + + let manifest = Manifest { + family: family.to_string(), + weights: weights.clone(), + faces: cached_faces, + bytes: total, + installed_at, + source: "google".into(), + }; + manifest.validate()?; + let json = serde_json::to_string_pretty(&manifest).map_err(|_| "STORAGE: serialization failed")?; + std::fs::write(tmp_dir.join(MANIFEST), json).map_err(|error| format!("STORAGE: {error}"))?; + + if final_dir.exists() { + std::fs::remove_dir_all(&final_dir).map_err(|error| format!("STORAGE: {error}"))?; + } + std::fs::rename(&tmp_dir, &final_dir).map_err(|error| format!("STORAGE: {error}"))?; + Ok(manifest) +} + +pub fn remove_family(fonts_root: &Path, family: &str) -> Result<(), String> { + let dir = family_dir(fonts_root, family).ok_or("VALIDATION: invalid family name")?; + if dir.exists() { + std::fs::remove_dir_all(&dir).map_err(|error| format!("STORAGE: {error}"))?; + } + Ok(()) +} + +/// `{ "family": ..., "faces": [ { "weight": [min,max], "unicodeRange": ..., "data": "" } ] }` +pub fn faces_json(manifest: &Manifest, bytes: &[Vec]) -> serde_json::Value { + use base64::Engine; + let faces: Vec = manifest + .faces + .iter() + .zip(bytes) + .map(|(face, data)| { + serde_json::json!({ + "weight": face.weight, + "unicodeRange": face.unicode_range, + "data": base64::engine::general_purpose::STANDARD.encode(data), + }) + }) + .collect(); + serde_json::json!({ "family": manifest.family, "faces": faces }) +} + +/// The script evaluated in every site tab so the page runtime (`window..fonts`) can +/// hand cached font bytes to `document.fonts` without the site's CSP ever seeing a remote font URL. +/// It does nothing outside the top frame on the site's primary origin. +pub fn page_script(site: &SiteSpec, fonts: &[serde_json::Value]) -> Option { + if fonts.is_empty() { + return None; + } + let json = serde_json::to_string(fonts).ok()?; + let json = json.replace("{{if(window.top!==window||location.origin!=='{origin}')return;const f={json};const BT=window.{global};if(BT&&BT.fonts)BT.fonts.provide(f);else(window.__wbFonts=window.__wbFonts||[]).push(...f);}})();" + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::site::testing::SITE; + + const INTER_CSS: &str = include_str!("../tests/fixtures/gfonts/inter.css"); + const LATO_CSS: &str = include_str!("../tests/fixtures/gfonts/lato.css"); + const LATO_TEXT_CSS: &str = include_str!("../tests/fixtures/gfonts/lato-text.css"); + + #[test] + fn parses_inter_variable_font() { + let faces = parse_css(INTER_CSS).unwrap(); + assert_eq!(faces.len(), 7); + let subsets: Vec<&str> = faces.iter().map(|f| f.subset.as_deref().unwrap()).collect(); + assert_eq!(subsets, ["cyrillic-ext", "cyrillic", "greek-ext", "greek", "vietnamese", "latin-ext", "latin"]); + assert!(faces.iter().all(|f| f.weight == (100, 900))); + assert!(faces.iter().all(|f| f.style == "normal")); + + let selected = select_faces(faces); + assert_eq!(selected.len(), 2); + let mut subsets: Vec<&str> = selected.iter().map(|f| f.subset.as_deref().unwrap()).collect(); + subsets.sort_unstable(); + assert_eq!(subsets, ["latin", "latin-ext"]); + } + + #[test] + fn parses_lato_static_weights() { + let faces = parse_css(LATO_CSS).unwrap(); + assert_eq!(faces.len(), 4); + assert!(faces.iter().all(|f| f.weight == (400, 400) || f.weight == (700, 700))); + let selected = select_faces(faces); + assert_eq!(selected.len(), 4); + } + + #[test] + fn parses_lato_text_preview_without_subset_labels() { + let faces = parse_css(LATO_TEXT_CSS).unwrap(); + assert_eq!(faces.len(), 2); + assert!(faces.iter().all(|f| f.subset.is_none())); + assert!(faces.iter().all(|f| f.url.contains("/l/font"))); + let selected = select_faces(faces); + assert_eq!(selected.len(), 2); + } + + #[test] + fn html_response_is_unknown_family() { + let err = parse_css("").unwrap_err(); + assert_eq!(err, "FONTS: unknown family"); + } + + #[test] + fn empty_css_has_no_usable_faces() { + let err = parse_css("/* nothing here */").unwrap_err(); + assert_eq!(err, "FONTS: no usable font faces"); + } + + #[test] + fn css_url_allowlist_rejects_bad_hosts_and_paths() { + assert!(allowed_css_url(&Url::parse("https://fonts.googleapis.com/css2?family=Lato").unwrap())); + assert!(!allowed_css_url(&Url::parse("http://fonts.googleapis.com/css2?family=Lato").unwrap())); + assert!(!allowed_css_url(&Url::parse("https://fonts.googleapis.com/css3?family=Lato").unwrap())); + assert!(!allowed_css_url(&Url::parse("https://evil.test/fonts.googleapis.com/css2").unwrap())); + assert!(!allowed_css_url(&Url::parse("https://user@fonts.googleapis.com/css2").unwrap())); + assert!(!allowed_css_url(&Url::parse("https://fonts.googleapis.com:8443/css2").unwrap())); + } + + #[test] + fn file_url_allowlist_rejects_lookalike_hosts() { + assert!(allowed_file_url(&Url::parse("https://fonts.gstatic.com/s/lato/v25/x.woff2").unwrap())); + assert!(allowed_file_url(&Url::parse("https://fonts.gstatic.com/l/font?kit=abc").unwrap())); + assert!(!allowed_file_url(&Url::parse("https://fonts.gstatic.com.evil.test/s/lato/v25/x.woff2").unwrap())); + assert!(!allowed_file_url(&Url::parse("https://evil.test/fonts.gstatic.com/s/lato/v25/x.woff2").unwrap())); + assert!(!allowed_file_url(&Url::parse("http://fonts.gstatic.com/s/lato/v25/x.woff2").unwrap())); + assert!(!allowed_file_url(&Url::parse("https://fonts.gstatic.com/other/x.woff2").unwrap())); + } + + #[test] + fn css_url_encoding_and_validation() { + let url = css_url("Noto Sans JP", &Weights::List { values: vec![700, 400] }, None).unwrap(); + assert!(url.as_str().starts_with("https://fonts.googleapis.com/css2?")); + assert!(url.as_str().contains("family=Noto+Sans+JP%3Awght%40400%3B700") || url.query().unwrap().contains("family=Noto+Sans+JP:wght@400;700")); + assert!(url.query().unwrap().contains("display=swap")); + + let with_text = css_url("Lato", &Weights::Range { min: 400, max: 700 }, Some("Hi")).unwrap(); + assert!(with_text.query().unwrap().contains("text=Hi")); + + assert!(css_url("../x", &Weights::Range { min: 400, max: 400 }, None).is_err()); + assert!(css_url("a\u{0}", &Weights::Range { min: 400, max: 400 }, None).is_err()); + assert!(css_url("", &Weights::Range { min: 400, max: 400 }, None).is_err()); + assert!(css_url(&"a".repeat(49), &Weights::Range { min: 400, max: 400 }, None).is_err()); + assert!(css_url("Lato", &Weights::Range { min: 50, max: 400 }, None).is_err()); + assert!(css_url("Lato", &Weights::Range { min: 400, max: 400 }, Some(&"a".repeat(121))).is_err()); + assert!(css_url("Lato", &Weights::Range { min: 400, max: 400 }, Some("")).is_err()); + } + + #[test] + fn is_woff2_checks_magic_and_length_field() { + let mut good = vec![0u8; 48]; + good[0..4].copy_from_slice(b"wOF2"); + good[8..12].copy_from_slice(&48u32.to_be_bytes()); + assert!(is_woff2(&good)); + + let mut bad_magic = good.clone(); + bad_magic[0..4].copy_from_slice(b"XXXX"); + assert!(!is_woff2(&bad_magic)); + + let mut bad_length = good.clone(); + bad_length[8..12].copy_from_slice(&999u32.to_be_bytes()); + assert!(!is_woff2(&bad_length)); + + assert!(!is_woff2(&[0u8; 10])); + } + + #[test] + fn write_family_read_manifest_verify_round_trip() { + let dir = tempfile::tempdir().unwrap(); + let mut face_bytes = vec![0u8; 100]; + face_bytes[0..4].copy_from_slice(b"wOF2"); + face_bytes[8..12].copy_from_slice(&100u32.to_be_bytes()); + let face = Face { subset: Some("latin".into()), style: "normal".into(), weight: (400, 400), url: "https://fonts.gstatic.com/s/x.woff2".into(), unicode_range: Some("U+00-FF".into()) }; + let weights = Weights::List { values: vec![400] }; + let manifest = write_family(dir.path(), "Lato", &weights, &[(face, face_bytes.clone())], "2026-01-01T00:00:00Z".into()).unwrap(); + assert_eq!(manifest.bytes, 100); + + let read = read_manifest(dir.path(), "Lato").unwrap(); + assert_eq!(read, manifest); + + let family_dir_path = family_dir(dir.path(), "Lato").unwrap(); + let verified = verify_cached(&family_dir_path, &read).unwrap(); + assert_eq!(verified, vec![face_bytes]); + + assert_eq!(cache_bytes(dir.path()), 100); + assert_eq!(list_installed(dir.path()).len(), 1); + } + + #[test] + fn tampered_cache_file_fails_verification() { + let dir = tempfile::tempdir().unwrap(); + let mut face_bytes = vec![0u8; 60]; + face_bytes[0..4].copy_from_slice(b"wOF2"); + face_bytes[8..12].copy_from_slice(&60u32.to_be_bytes()); + let face = Face { subset: None, style: "normal".into(), weight: (400, 400), url: "https://fonts.gstatic.com/s/x.woff2".into(), unicode_range: None }; + let weights = Weights::List { values: vec![400] }; + let manifest = write_family(dir.path(), "Lato", &weights, &[(face, face_bytes)], "2026-01-01T00:00:00Z".into()).unwrap(); + + let family_dir_path = family_dir(dir.path(), "Lato").unwrap(); + std::fs::write(family_dir_path.join(&manifest.faces[0].file), vec![1u8; 60]).unwrap(); + let err = verify_cached(&family_dir_path, &manifest).unwrap_err(); + assert_eq!(err, "FONTS: cache damaged"); + } + + #[test] + fn oversized_buffer_is_rejected() { + let dir = tempfile::tempdir().unwrap(); + let mut face_bytes = vec![0u8; 48]; + face_bytes[0..4].copy_from_slice(b"wOF2"); + face_bytes[8..12].copy_from_slice(&(MAX_FILE_BYTES as u32 + 1).to_be_bytes()); + face_bytes.resize(MAX_FILE_BYTES + 1, 0); + let face = Face { subset: None, style: "normal".into(), weight: (400, 400), url: "https://fonts.gstatic.com/s/x.woff2".into(), unicode_range: None }; + let weights = Weights::List { values: vec![400] }; + let err = write_family(dir.path(), "Lato", &weights, &[(face, face_bytes)], "2026-01-01T00:00:00Z".into()).unwrap_err(); + assert_eq!(err, "FONTS: invalid font file"); + } + + #[test] + fn manifest_with_path_traversal_file_name_is_rejected() { + let manifest = Manifest { + family: "Lato".into(), + weights: Weights::List { values: vec![400] }, + faces: vec![CachedFace { file: "../evil.woff2".into(), weight: [400, 400], unicode_range: None, subset: None, bytes: 48, sha256: "0".repeat(64) }], + bytes: 48, + installed_at: "2026-01-01T00:00:00Z".into(), + source: "google".into(), + }; + assert!(manifest.validate().is_err()); + } + + #[test] + fn page_script_escapes_closing_script_tags() { + let fonts = vec![serde_json::json!({ "family": "", "faces": [] })]; + let script = page_script(&SITE, &fonts).unwrap(); + assert!(script.starts_with("(()=>{if(window.top!==window||location.origin!=='https://x.com')return;")); + assert!(script.contains("const BT=window.BetterTwttr;")); + assert!(!script.contains("")); + assert!(script.contains("<\\/script>")); + } + + #[test] + fn page_script_is_none_for_empty_fonts() { + assert!(page_script(&SITE, &[]).is_none()); + } + + #[test] + fn valid_family_rejects_bad_names() { + assert!(valid_family("Lato")); + assert!(valid_family("Noto Sans JP")); + assert!(!valid_family("")); + assert!(!valid_family(" Lato")); + assert!(!valid_family("Lato ")); + assert!(!valid_family("Lato Bold")); + assert!(!valid_family("../x")); + assert!(!valid_family(&"a".repeat(49))); + } +} diff --git a/crates/waybetter-host/src/host.rs b/crates/waybetter-host/src/host.rs index 1127b03..a070b88 100644 --- a/crates/waybetter-host/src/host.rs +++ b/crates/waybetter-host/src/host.rs @@ -185,12 +185,497 @@ pub fn system_menu(webview: &Webview, x: f64, y: f64) -> Result<( Ok(()) } +/// Windows: a graceful close sent to one of the process's helper windows closes the app window +/// instead. Call once from `setup`, on the main thread, after the main window is built. No-op +/// elsewhere. +/// +/// tao's thread event target and the single-instance plugin's message window are visible (1 px, +/// layered, transparent) unowned top-level windows. `taskkill /PID` without `/F` posts one +/// `WM_CLOSE` to the first such window in z-order; a minimized window sinks to the bottom, so the +/// close hit a helper, `DefWindowProc` destroyed it (a second instance could no longer find us, +/// or the event loop lost its target) and the app kept running. +pub fn route_helper_closes(window: &tauri::Window) { + #[cfg(windows)] + helper_close::install(window); + #[cfg(not(windows))] + let _ = window; +} + +#[cfg(windows)] +mod helper_close { + use windows::core::BOOL; + use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM}; + use windows::Win32::System::Threading::GetCurrentThreadId; + use windows::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}; + use windows::Win32::UI::WindowsAndMessaging::{ + EnumThreadWindows, GetWindow, IsWindow, IsWindowVisible, PostMessageW, GW_OWNER, WM_CLOSE, WM_NCDESTROY, + }; + + const SUBCLASS_ID: usize = 0x7762_636c; // "wbcl" + + pub(super) fn install(window: &tauri::Window) { + let Ok(main) = window.hwnd() else { return }; + // SAFETY: enumerates and subclasses windows of the calling (event loop) thread only; + // `main` is passed by value through the LPARAM / ref data. + unsafe { + let _ = EnumThreadWindows(GetCurrentThreadId(), Some(visit), LPARAM(main.0 as isize)); + } + } + + unsafe extern "system" fn visit(hwnd: HWND, main: LPARAM) -> BOOL { + let main = HWND(main.0 as *mut _); + // Visible, unowned, not the app window: what `taskkill` may pick. IME windows are hidden. + if hwnd != main && IsWindowVisible(hwnd).as_bool() && GetWindow(hwnd, GW_OWNER).is_err() { + let _ = SetWindowSubclass(hwnd, Some(forward), SUBCLASS_ID, main.0 as usize); + } + BOOL(1) + } + + unsafe extern "system" fn forward( + hwnd: HWND, + msg: u32, + wparam: WPARAM, + lparam: LPARAM, + id: usize, + main: usize, + ) -> LRESULT { + match msg { + WM_CLOSE => { + let main = HWND(main as *mut _); + if IsWindow(Some(main)).as_bool() { + let _ = PostMessageW(Some(main), WM_CLOSE, WPARAM(0), LPARAM(0)); + return LRESULT(0); + } + } + WM_NCDESTROY => { + let _ = RemoveWindowSubclass(hwnd, Some(forward), id); + } + _ => {} + } + DefSubclassProc(hwnd, msg, wparam, lparam) + } +} + +/// Places a child webview (tab, popover) at a rectangle of its window, in logical px. +/// +/// Windows/macOS: the native child bounds. Linux: tauri 2 packs every child webview into the +/// window's GtkBox (`build_gtk` with a box: stacked one under another, bounds ignored), so the host +/// moves each one into the GtkOverlay made by [`attach_shell`] and places it there. +pub fn place_child(webview: &Webview, x: f64, y: f64, width: f64, height: f64) { + #[cfg(target_os = "linux")] + linux::place(webview, x, y, width, height); + // One native move+resize: separate set_position/set_size calls were two WebView2 `SetBounds` + // (the page re-laid out at the old size, then at the new one) and two main-thread messages. + #[cfg(not(target_os = "linux"))] + let _ = webview.set_bounds(tauri::Rect { + position: tauri::LogicalPosition::new(x, y).into(), + size: tauri::LogicalSize::new(width, height).into(), + }); +} + +/// Linux: the shell webview becomes the base layer of a GtkOverlay filling the window, which +/// [`place_child`] layers tab webviews over. Call once, right after the shell is added. No-op +/// elsewhere. +pub fn attach_shell(shell: &Webview) { + #[cfg(target_os = "linux")] + linux::attach_shell(shell); + #[cfg(not(target_os = "linux"))] + let _ = shell; +} + +/// Puts the shell webview above every tab webview (`on_top`), so shell menus, dialogs and drag +/// zones draw over the panes while the panes stay on screen (the shell page must then be +/// transparent where the panes are), or back below them. Returns whether this platform can. +/// Windows: WebView2 hosts each webview in its own child window, re-ordered with `SetWindowPos` +/// (no activation or focus change). Linux: the shell's place among the GtkOverlay's layers +/// ([`attach_shell`]). macOS: the shell's WKWebView re-ordered among its superview's subviews +/// (first responder kept). Elsewhere the caller hides the tabs instead. +pub fn raise_shell(shell: &Webview, on_top: bool) -> bool { + #[cfg(windows)] + { + let _ = shell.with_webview(move |platform| { + use windows::Win32::Foundation::HWND; + use windows::Win32::UI::WindowsAndMessaging::{ + SetWindowPos, HWND_BOTTOM, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE, + }; + let mut container = HWND::default(); + // SAFETY: the shell's own live controller and its container window, on the main + // thread (with_webview runs the closure there). + unsafe { + if platform.controller().ParentWindow(&mut container).is_ok() && !container.is_invalid() { + let after = if on_top { HWND_TOP } else { HWND_BOTTOM }; + let _ = SetWindowPos( + container, + Some(after), + 0, + 0, + 0, + 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER, + ); + } + } + }); + true + } + #[cfg(target_os = "linux")] + { + linux::raise_shell(shell, on_top); + true + } + #[cfg(target_os = "macos")] + { + macos::raise_shell(shell, on_top); + true + } + #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))] + { + let _ = (shell, on_top); + false + } +} + +#[cfg(target_os = "macos")] +mod macos { + use objc2_app_kit::{NSResponder, NSView, NSWindowOrderingMode}; + use tauri::{Runtime, Webview}; + + pub fn raise_shell(shell: &Webview, on_top: bool) { + let _ = shell.with_webview(move |platform| { + // SAFETY: `inner` is the shell's live WKWebView (an NSView) and its superview (the + // window's content view, which owns it), on the main thread (with_webview runs the + // closure there). + let view: &NSView = unsafe { &*platform.inner().cast::() }; + let Some(parent) = (unsafe { view.superview() }) else { return }; + // Re-adding a subview can resign it as first responder: typing stays where it was. + let window = view.window(); + let focused = window.as_ref().and_then(|window| window.firstResponder()).is_some_and(|responder| { + responder.downcast_ref::().is_some_and(|responder| responder.isDescendantOf(view)) + }); + let mode = if on_top { NSWindowOrderingMode::Above } else { NSWindowOrderingMode::Below }; + parent.addSubview_positioned_relativeTo(view, mode, None); + if focused { + if let Some(window) = window { + let responder: &NSResponder = view; + window.makeFirstResponder(Some(responder)); + } + } + }); + } +} + +/// Where [`place_child`] last put a child webview, in logical px (x, y, width, height). Linux +/// only: there `Webview::position` is not the placement (always 0,0 outside X11 child windows). +#[cfg(target_os = "linux")] +pub fn placed_rect(webview: &Webview) -> Option<(f64, f64, f64, f64)> { + linux::placed(webview.label()) +} + +#[cfg(target_os = "linux")] +mod linux { + use gtk::prelude::*; + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Mutex, OnceLock}; + use tauri::{Runtime, Webview}; + + type Rect = (f64, f64, f64, f64); + /// A child's placement in whole px (x, y, width, height), kept on the GTK widget. + type GtkRect = (i32, i32, i32, i32); + const RECT_KEY: &str = "waybetter-rect"; + + fn rects() -> std::sync::MutexGuard<'static, HashMap> { + static RECTS: OnceLock>> = OnceLock::new(); + RECTS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + pub fn placed(label: &str) -> Option { + rects().get(label).copied() + } + + /// The shell is above the tab webviews ([`raise_shell`]). + static RAISED: AtomicBool = AtomicBool::new(false); + + /// The shell is the overlay's first layer (under the tabs, which `place` adds above it) or, + /// raised, its last. Tabs placed while it is raised go under it. + pub fn raise_shell(shell: &Webview, on_top: bool) { + RAISED.store(on_top, Ordering::SeqCst); + let _ = shell.with_webview(move |platform| { + let widget = platform.inner().upcast::(); + let Some(overlay) = widget.parent().and_then(|parent| parent.downcast::().ok()) else { return }; + overlay.reorder_overlay(&widget, if on_top { -1 } else { 0 }); + }); + } + + pub fn attach_shell(shell: &Webview) { + let _ = shell.with_webview(|platform| { + let widget = platform.inner().upcast::(); + let Some(vbox) = widget.parent().and_then(|parent| parent.downcast::().ok()) else { return }; + let overlay = gtk::Overlay::new(); + // Exactly the placed rectangle: the default position uses the child's preferred size, + // which WebKit (not the placement) decides. + overlay.connect_get_child_position(|_, child| { + // SAFETY: "waybetter-rect" is only ever set by `place`, always as `GtkRect`. + let (x, y, w, h) = unsafe { *child.data::(RECT_KEY)?.as_ptr() }; + Some(gtk::gdk::Rectangle::new(x, y, w, h)) + }); + // `widget` holds a reference, so removing it from the box does not destroy it. The + // shell is an overlay layer too (an empty box is the base), so it can be re-ordered + // above the tabs; with no placement it fills the overlay (Fill alignment). + vbox.remove(&widget); + widget.set_halign(gtk::Align::Fill); + widget.set_valign(gtk::Align::Fill); + overlay.add(>k::Box::new(gtk::Orientation::Vertical, 0)); + overlay.add_overlay(&widget); + vbox.pack_start(&overlay, true, true, 0); + overlay.show(); + }); + } + + pub fn place(webview: &Webview, x: f64, y: f64, width: f64, height: f64) { + rects().insert(webview.label().to_owned(), (x, y, width, height)); + // Whole px, with the right/bottom edges rounded the same way as the left/top ones. + let (left, top) = (x.round(), y.round()); + let (w, h) = (((x + width).round() - left).max(1.0), ((y + height).round() - top).max(1.0)); + let _ = webview.with_webview(move |platform| { + let widget = platform.inner().upcast::(); + // SAFETY: read back only as `GtkRect` (the overlay's get-child-position handler). + unsafe { widget.set_data::(RECT_KEY, (left as i32, top as i32, w as i32, h as i32)) }; + let Some(parent) = widget.parent() else { return }; + if parent.downcast_ref::().is_none() { + // First placement: out of the window box (where tauri packed it), into the overlay. + let Ok(vbox) = parent.downcast::() else { return }; + let Some(overlay) = vbox.children().into_iter().find_map(|child| child.downcast::().ok()) else { + return; + }; + vbox.remove(&widget); + overlay.add_overlay(&widget); + if RAISED.load(Ordering::SeqCst) { + overlay.reorder_overlay(&widget, 0); + } + } + widget.queue_resize(); + }); + } +} + +/// The event carrying a tab's last frame to the shell ([`capture_still`]). +pub const EVENT_TAB_STILL: &str = "tab-still"; +#[cfg(windows)] +const EVENT_TAB_STILL_START: &str = "tab-still-start"; +#[cfg(windows)] +const EVENT_TAB_STILL_CANCEL: &str = "tab-still-cancel"; +#[cfg(windows)] +const EVENT_TAB_STILL_RESET: &str = "tab-still-reset"; + +#[cfg(windows)] +#[derive(Clone, Serialize)] +struct TabStill { + id: String, + /// `data:image/jpeg;base64,…` + image: String, + token: u64, +} + +#[cfg(windows)] +#[derive(Clone, Serialize)] +struct TabStillToken { id: String, token: u64 } + +#[cfg(windows)] +#[derive(Clone, Copy, PartialEq, Eq)] +enum StillPhase { Pending, Hidden } + +#[cfg(windows)] +#[derive(Clone, Copy)] +struct StillEntry { token: u64, phase: StillPhase } + +#[cfg(windows)] +impl StillEntry { + fn accepts(self, token: u64) -> bool { self.token == token } + fn hide(&mut self, token: u64) -> bool { + if !self.accepts(token) || self.phase != StillPhase::Pending { return false; } + self.phase = StillPhase::Hidden; + true + } +} + +#[cfg(all(test, windows))] +mod still_tests { + use super::{cancel_pending_still, pending_stills, StillEntry, StillPhase}; + + #[test] + fn timeout_keeps_late_frame_valid_but_stale_tokens_cannot_hide() { + let mut entry = StillEntry { token: 7, phase: StillPhase::Pending }; + assert!(!entry.hide(6)); + assert!(entry.hide(7)); + assert!(entry.accepts(7)); // CapturePreview may finish after the bounded hide. + assert!(!entry.hide(7)); // A late acknowledgement must not hide a shown tab again. + entry = StillEntry { token: 8, phase: StillPhase::Pending }; + assert!(!entry.accepts(7)); + assert!(!entry.hide(7)); + } + + #[test] + fn teardown_invalidates_old_capture_before_same_label_is_reused() { + let label = "tab-still-test-recreated"; + pending_stills().lock().unwrap().insert(label.into(), StillEntry { token: 31, phase: StillPhase::Hidden }); + assert_eq!(cancel_pending_still(label), Some(31)); + pending_stills().lock().unwrap().insert(label.into(), StillEntry { token: 32, phase: StillPhase::Pending }); + let current = pending_stills().lock().unwrap().get(label).copied().unwrap(); + assert!(!current.accepts(31)); + assert!(current.accepts(32)); + cancel_pending_still(label); + } +} + +#[cfg(windows)] +fn pending_stills() -> &'static std::sync::Mutex> { + use std::sync::{Mutex, OnceLock}; + static PENDING: OnceLock>> = OnceLock::new(); + PENDING.get_or_init(Default::default) +} + +#[cfg(windows)] +fn cancel_pending_still(label: &str) -> Option { + pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(label).map(|entry| entry.token) +} + +#[cfg(windows)] +fn hide_after_still(app: &AppHandle, label: &str, token: u64) { + let app = app.clone(); + let label = label.to_owned(); + let dispatcher = app.clone(); + // Webview::show/hide both execute on Tauri's main thread. Check the token there, directly + // before hiding, so a queued hide cannot run after a newer show canceled this capture. + let _ = dispatcher.run_on_main_thread(move || { + let current = { + let mut pending = pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + pending.get_mut(&label).is_some_and(|entry| entry.hide(token)) + }; + if current { + if let Some(tab) = app.get_webview(&label) { let _ = tab.hide(); } + } + }); +} + +/// The shell has painted a captured frame; complete the bounded overlay handoff. +#[cfg(windows)] +pub fn acknowledge_still(app: &AppHandle, id: &str, token: u64) { + if policy::valid_tab_id(id) { + hide_after_still(app, &policy::tab_label(id), token); + } +} + +#[cfg(not(windows))] +pub fn acknowledge_still(_app: &AppHandle, _id: &str, _token: u64) {} + +/// Windows: a tab webview about to be hidden hands the shell its last frame (WebView2 +/// `CapturePreview`, JPEG) as [`EVENT_TAB_STILL`], which its pane shows while no webview is on +/// screen there. Only a webview that is on screen now; requested before the hide, on the same +/// thread, so the frame is still there. Kept in the shell's memory only. No-op elsewhere. +fn capture_still(webview: &Webview, token: u64) { + #[cfg(windows)] + { + let Some(id) = policy::tab_id(webview.label()).map(str::to_owned) else { return }; + let label = webview.label().to_owned(); + let app = webview.app_handle().clone(); + let fallback = app.clone(); + let fallback_label = label.clone(); + let result = webview.with_webview(move |platform| { + use base64::Engine; + use webview2_com::CapturePreviewCompletedHandler; + use webview2_com::Microsoft::Web::WebView2::Win32::COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG; + use windows::Win32::System::Com::{STREAM_SEEK_END, STREAM_SEEK_SET}; + use windows::Win32::UI::Shell::SHCreateMemStream; + // SAFETY: COM calls on this webview's live controller and a memory stream it writes + // into, on the main thread (with_webview and the completion handler run there). + unsafe { + let controller = platform.controller(); + let mut shown = windows::core::BOOL::default(); + if controller.IsVisible(&mut shown).is_err() || !shown.as_bool() { + hide_after_still(&app, &label, token); + return; + } + let (Ok(core), Some(stream)) = (controller.CoreWebView2(), SHCreateMemStream(None)) else { + hide_after_still(&app, &label, token); + return; + }; + let target = stream.clone(); + let callback_app = app.clone(); + let callback_label = label.clone(); + let handler = CapturePreviewCompletedHandler::create(Box::new(move |result| { + let image = (|| { + result.ok()?; + let mut size = 0u64; + target.Seek(0, STREAM_SEEK_END, Some(&mut size)).ok()?; + if size == 0 || size > 16 << 20 { return None; } + target.Seek(0, STREAM_SEEK_SET, None).ok()?; + let mut bytes = vec![0u8; size as usize]; + let mut read = 0u32; + target.Read(bytes.as_mut_ptr().cast(), size as u32, Some(&mut read)).ok().ok()?; + bytes.truncate(read as usize); + Some(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes))) + })(); + if let Some(image) = image { + let current = pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(&callback_label).is_some_and(|entry| entry.accepts(token)); + if current { + emit_shell(&callback_app, EVENT_TAB_STILL, TabStill { id, image, token }); + } + } else { + hide_after_still(&callback_app, &callback_label, token); + } + Ok(()) + })); + if core.CapturePreview(COREWEBVIEW2_CAPTURE_PREVIEW_IMAGE_FORMAT_JPEG, &stream, &handler).is_err() { + hide_after_still(&app, &label, token); + } + } + }); + if result.is_err() { + hide_after_still(&fallback, &fallback_label, token); + } + } + #[cfg(not(windows))] + let _ = (webview, token); +} + /// Shows or hides a tab webview and sets its WebView2 memory target to match /// ([`tabs::memory_target`]): hidden tabs run at `COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW` /// (ICoreWebView2_19, WebView2 Runtime 114+; older runtimes just skip it). Other platforms only /// show/hide. -pub fn set_tab_visible(webview: &Webview, visible: bool, parked: bool) { +pub fn set_tab_visible(webview: &Webview, visible: bool, parked: bool, was_visible: bool) { + #[cfg(windows)] + { + let app = webview.app_handle(); + let id = policy::tab_id(webview.label()).unwrap_or_default().to_owned(); + if let Some(token) = cancel_pending_still(webview.label()) { + emit_shell(app, EVENT_TAB_STILL_CANCEL, TabStillToken { id: id.clone(), token }); + } + if !visible && !parked && was_visible && webview.window().is_visible().unwrap_or(false) { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(1); + let token = NEXT.fetch_add(1, Ordering::Relaxed); + let label = webview.label().to_owned(); + pending_stills().lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(label.clone(), StillEntry { token, phase: StillPhase::Pending }); + emit_shell(app, EVENT_TAB_STILL_START, TabStillToken { id, token }); + let app = app.clone(); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(160)).await; + hide_after_still(&app, &label, token); + }); + capture_still(webview, token); + set_memory_target(webview, visible, parked); + return; + } + } let _ = if visible { webview.show() } else { webview.hide() }; + set_memory_target(webview, visible, parked); +} + +fn set_memory_target(webview: &Webview, visible: bool, parked: bool) { + let _ = (webview, visible, parked); #[cfg(windows)] { use std::collections::HashMap; @@ -224,3 +709,126 @@ pub fn set_tab_visible(webview: &Webview, visible: bool, parked: }); } } + +fn placements() -> std::sync::MutexGuard<'static, crate::layout::Placements> { + use std::sync::{Mutex, OnceLock}; + static PLACEMENTS: OnceLock> = OnceLock::new(); + PLACEMENTS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +/// Places a tab webview and shows or hides it ([`place_child`], [`set_tab_visible`]), skipping the +/// native calls for whatever did not change since its last placement: a sync that moves one pane +/// touches one webview, and one that changes nothing costs nothing. +pub fn place_tab(webview: &Webview, rect: crate::layout::Rect, visible: bool, parked: bool) { + let (changed, was_visible) = { + let mut placed = placements(); + let was_visible = placed.was_visible(webview.label()); + (placed.place(webview.label(), rect, visible), was_visible) + }; + if changed.bounds { + let (x, y, width, height) = rect; + place_child(webview, x, y, width, height); + } + if changed.visible { + set_tab_visible(webview, visible, parked, was_visible); + } else { + set_memory_target(webview, visible, parked); + } +} + +/// A tab webview was closed: a new one with the same label is placed from scratch. +pub fn forget_tab(app: &AppHandle, label: &str) { + #[cfg(windows)] + { + cancel_pending_still(label); + if let Some(id) = policy::tab_id(label) { + emit_shell(app, EVENT_TAB_STILL_RESET, id.to_owned()); + } + } + #[cfg(not(windows))] + let _ = app; + placements().forget(label); +} + +/// The window size (logical px) and state a tab layout is clamped against. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WindowMetrics { + pub width: f64, + pub height: f64, + pub maximized: bool, + pub frameless: bool, +} + +fn metrics_cache() -> std::sync::MutexGuard<'static, Option> { + use std::sync::{Mutex, OnceLock}; + static METRICS: OnceLock>> = OnceLock::new(); + METRICS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +fn read_metrics(window: &tauri::Window) -> tauri::Result { + let size = window.inner_size()?.to_logical::(window.scale_factor()?); + Ok(WindowMetrics { + width: size.width, + height: size.height, + maximized: window.is_maximized().unwrap_or(false), + frameless: !window.is_decorated().unwrap_or(true), + }) +} + +/// The window's metrics, kept current by [`follow_window_resizes`]: a tab sync (off the main +/// thread) then needs no blocking round trip to the event loop for them. +pub fn window_metrics(window: &tauri::Window) -> tauri::Result { + if let Some(metrics) = *metrics_cache() { + return Ok(metrics); + } + let metrics = read_metrics(window)?; + *metrics_cache() = Some(metrics); + Ok(metrics) +} + +/// The shell laid its panes out for a window of `viewport` (its own inner size); returns the +/// window size to lay them out in now and whether the layout is stale (the window was resized +/// since). Stale layouts are re-based with [`crate::layout::follow_rect`] by the caller. +pub fn layout_window(metrics: &WindowMetrics, viewport: Option<(f64, f64)>) -> Option<(f64, f64)> { + let (width, height) = viewport.filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 1.0 && *h > 1.0)?; + let stale = (width - metrics.width).abs() > 1.5 || (height - metrics.height).abs() > 1.5; + stale.then_some((width, height)) +} + +/// Records the window size the tab placements now correspond to. +pub fn layout_placed(metrics: &WindowMetrics) { + placements().set_window((metrics.width, metrics.height)); +} + +/// Keeps tab webviews glued to the window while it is resized, maximized or snapped: on every +/// resize (main thread, in the same event the runtime resizes the shell webview in) the visible +/// tabs are re-placed from the last layout ([`crate::layout::Placements::follow`]), with no JS +/// round trip. The shell's exact layout follows a frame or two later and replaces the estimate. +/// Call once from `setup`, after the window is built. +pub fn follow_window_resizes(window: &tauri::Window) { + if let Ok(metrics) = read_metrics(window) { + *metrics_cache() = Some(metrics); + } + let target = window.clone(); + window.on_window_event(move |event| { + if !matches!(event, tauri::WindowEvent::Resized(_) | tauri::WindowEvent::ScaleFactorChanged { .. }) { + return; + } + let Ok(metrics) = read_metrics(&target) else { return }; + *metrics_cache() = Some(metrics); + // Minimized: 0x0; nothing to follow, and the next restore re-bases from the last layout. + if metrics.width < 2.0 || metrics.height < 2.0 { + return; + } + let moved = placements().follow((metrics.width, metrics.height)); + for (label, (x, y, width, height)) in moved { + if let Some(webview) = target.app_handle().get_webview(&label) { + // Never over the titlebar or the resize border, like every shell layout. + let clamped = policy::clamp_tab_rect(x, y, width, height, metrics.width, metrics.height, metrics.maximized, metrics.frameless); + if let Ok(Some((x, y, width, height))) = clamped { + place_child(&webview, x, y, width, height); + } + } + } + }); +} diff --git a/crates/waybetter-host/src/i18n.rs b/crates/waybetter-host/src/i18n.rs new file mode 100644 index 0000000..f091a2d --- /dev/null +++ b/crates/waybetter-host/src/i18n.rs @@ -0,0 +1,246 @@ +//! Native side of wayBetter i18n. +//! +//! The shell owns language: it loads the catalogs, picks the locale (follow the site, follow the +//! system, or the owner's pick) and hands native code the few strings native UI needs (dialog +//! titles, notifications, the site runtime's own words) as [`NativeStrings`]. These are data only: +//! validated here (bounded, plain text, no markup or control characters), kept in app data so the +//! next launch has them before the shell loads, and delivered to site tabs as a JSON value. +//! +//! [`system_locales`] reads the OS preference for the first run and for "Follow system". + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// At most this many strings reach native code (the site runtime's, the kit's, bundled plugins', native UI's). +pub const MAX_STRINGS: usize = 4000; +/// Longest message accepted. +pub const MAX_VALUE: usize = 2000; +/// Longest key accepted. +pub const MAX_KEY: usize = 96; +/// Total bytes of keys and values. +pub const MAX_TOTAL: usize = 512 * 1024; + +/// A BCP 47 language tag as the catalogs use it: `tr`, `pt-BR`, `zh-Hant`, `ar-x-fm`. +pub fn valid_tag(tag: &str) -> bool { + if tag.is_empty() || tag.len() > 35 { + return false; + } + let mut parts = tag.split('-'); + let Some(language) = parts.next() else { return false }; + if !(2..=3).contains(&language.len()) || !language.bytes().all(|b| b.is_ascii_alphabetic()) { + return false; + } + parts.all(|part| (1..=8).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphanumeric())) +} + +/// Writing direction of a tag (by primary language). +pub fn is_rtl(tag: &str) -> bool { + let language = tag.split('-').next().unwrap_or("").to_ascii_lowercase(); + matches!(language.as_str(), "ar" | "arc" | "ckb" | "dv" | "fa" | "he" | "iw" | "ks" | "ps" | "sd" | "syr" | "ug" | "ur" | "yi") +} + +fn valid_key(key: &str) -> bool { + !key.is_empty() + && key.len() <= MAX_KEY + && key.as_bytes()[0].is_ascii_lowercase() + && key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) +} + +/// Plain text only: no markup, no control or bidi-override characters (newlines and tabs are fine). +pub fn valid_text(value: &str) -> bool { + if value.len() > MAX_VALUE { + return false; + } + let lower = value.to_ascii_lowercase(); + if lower.contains("javascript:") || lower.contains("<") || lower.contains("<") || lower.contains("<") { + return false; + } + let mut chars = value.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == '<' { + if let Some(next) = chars.clone().find(|c| !c.is_whitespace()) { + if next.is_ascii_alphabetic() || matches!(next, '/' | '!' | '?') { + return false; + } + } + } + let code = ch as u32; + let control = (ch.is_control() && !matches!(ch, '\n' | '\t' | '\r')) || (0x202A..=0x202E).contains(&code) || (0x2066..=0x2069).contains(&code); + if control { + return false; + } + } + true +} + +/// The strings native code and site tabs need, in the owner's language. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase", default)] +pub struct NativeStrings { + /// Active locale (a catalog tag). + pub locale: String, + /// The owner's choice: `site` (follow the site's own language), `system`, or a locale tag. + pub preference: String, + pub messages: BTreeMap, +} + +impl NativeStrings { + /// Checks everything the shell sent; any bad entry refuses the whole set. + pub fn validated(self) -> Result { + if !valid_tag(&self.locale) { + return Err("VALIDATION: invalid locale".into()); + } + if !(self.preference == "site" || self.preference == "system" || valid_tag(&self.preference)) { + return Err("VALIDATION: language preference must be \"site\", \"system\" or a locale".into()); + } + if self.messages.len() > MAX_STRINGS { + return Err("VALIDATION: too many strings".into()); + } + let mut total = 0; + for (key, value) in &self.messages { + if !valid_key(key) { + return Err(format!("VALIDATION: invalid string key {:?}", key.chars().take(40).collect::())); + } + if !valid_text(value) { + return Err(format!("VALIDATION: string {key} is not plain text")); + } + total += key.len() + value.len(); + } + if total > MAX_TOTAL { + return Err("VALIDATION: strings too large".into()); + } + Ok(self) + } + + /// The message for `key`, or `fallback` (English, compiled in) when there is none. + pub fn get<'a>(&'a self, key: &str, fallback: &'a str) -> &'a str { + self.messages.get(key).map(String::as_str).filter(|value| !value.is_empty()).unwrap_or(fallback) + } + + /// `get` with `{name}` placeholders filled in, in one pass: values are inserted as text and are + /// never scanned for placeholders themselves. Unknown `{…}` stays as written. + pub fn format(&self, key: &str, fallback: &str, params: &[(&str, &str)]) -> String { + let template = self.get(key, fallback); + let mut out = String::with_capacity(template.len()); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + let tail = &rest[open..]; + let value = tail.find('}').and_then(|close| params.iter().find(|(name, _)| *name == &tail[1..close]).map(|(_, value)| (close, value))); + match value { + Some((close, value)) => { + out.push_str(value); + rest = &tail[close + 1..]; + } + None => { + out.push('{'); + rest = &tail[1..]; + } + } + } + out.push_str(rest); + out + } + + /// The strings whose keys start with one of `prefixes`, as the JSON value a site tab receives. + pub fn page_payload(&self, prefixes: &[&str]) -> serde_json::Value { + let messages: serde_json::Map = self + .messages + .iter() + .filter(|(key, _)| prefixes.iter().any(|prefix| key.starts_with(prefix))) + .map(|(key, value)| (key.clone(), serde_json::Value::String(value.clone()))) + .collect(); + serde_json::json!({ "locale": self.locale, "dir": if is_rtl(&self.locale) { "rtl" } else { "ltr" }, "messages": messages }) + } +} + +/// The script that hands a site tab its strings (`payload`, see [`NativeStrings::page_payload`]): +/// delivered through the page runtime (queued in `__wbI18n` until it exists), and only on the +/// site's primary origin: other sites' tabs run the same document-start scripts and must not get them. +pub fn page_script(site: &crate::site::SiteSpec, payload: &serde_json::Value) -> String { + let script = crate::tabs::deliver_script(site.runtime_global, "i18n", "set", "__wbI18n", &payload.to_string()); + format!("if(location.origin==='{}'){script}", site.primary_origin()) +} + +/// The OS language preferences, most preferred first (`tr-TR`, `en-US`), as valid tags. +pub fn system_locales() -> Vec { + sys_locale::get_locales() + .map(|tag| tag.replace('_', "-")) + // POSIX locales may carry an encoding or modifier (`tr_TR.UTF-8@euro`). + .map(|tag| tag.split(['.', '@']).next().unwrap_or("").to_owned()) + .filter(|tag| valid_tag(tag)) + .take(8) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn page_script_is_guarded_to_the_site_origin() { + let payload = strings(&[("x.fab.title", "wayBetter"), ("native.notify.title", "Hi")]).page_payload(&["x."]); + let script = page_script(&crate::site::testing::SITE, &payload); + assert!(script.starts_with("if(location.origin==='https://x.com')("), "{script}"); + assert!(script.contains("x.fab.title") && !script.contains("native.notify.title"), "{script}"); + } + + fn strings(messages: &[(&str, &str)]) -> NativeStrings { + NativeStrings { + locale: "tr".into(), + preference: "site".into(), + messages: messages.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(), + } + } + + #[test] + fn tags_are_validated() { + for good in ["tr", "pt-BR", "zh-Hant", "ar-x-fm", "fil", "en-GB"] { + assert!(valid_tag(good), "{good}"); + } + for bad in ["", "t", "english", "tr_TR", "tr-", "tr-", "a-b", "zh-Hant-TW-far-too-long-for-a-language-tag"] { + assert!(!valid_tag(bad), "{bad}"); + } + assert!(is_rtl("ar-x-fm") && is_rtl("he") && !is_rtl("tr")); + } + + #[test] + fn strings_are_plain_text_only() { + assert!(strings(&[("native.alert.title", "“{keyword}” geçti"), ("x.toast.saved", "Kaydedildi\n")]).validated().is_ok()); + for bad in ["", "a < b / "] { + assert!(with(json!({ "preset": "site", "themes": [{ "id": id, "name": "n" }] })).is_err(), "accepted {id}"); + } + assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A" }, { "id": "a", "name": "B" }] })).is_err()); + assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "" }] })).is_err()); + assert!(with(json!({ "preset": "site", "themes": ["css"] })).is_err()); + assert!(with(json!({ "preset": "site", "overrides": { "script": {} } })).is_err()); + assert!(with(json!({ "preset": "site", "overrides": { "css": { "text": "a { color: red }" } } })).is_ok(), "theme CSS override"); + assert!(with(json!({ "preset": "site", "overrides": { "css": "a {}" } })).is_err(), "theme CSS must be an object"); + assert!(with(json!({ "preset": "site", "overrides": { "font": "Comic Sans" } })).is_err()); + let huge = "a".repeat(MAX_THEME_BYTES); + assert!(with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A", "css": huge }] })).is_err()); + let many: Vec = (0..=MAX_THEMES).map(|i| json!({ "id": format!("t{i}"), "name": "T" })).collect(); + assert!(with(json!({ "preset": "site", "themes": many })).is_err()); + } + + #[test] + fn tabs_get_pane_then_account_then_global_theme() { + let global = with(json!({ "preset": "mine", "accent": "#ff0000", "overrides": { "font": { "scale": 1.1 } }, + "themes": [{ "id": "mine", "name": "Mine" }, { "id": "other", "name": "Other" }] })).unwrap(); + let scopes: ThemeScopes = serde_json::from_value(json!({ "profiles": { "p1": "paper" }, "panes": { "t1": "other", "t2": "gone" } })).unwrap(); + scopes.validate().unwrap(); + assert_eq!(scopes.chrome, "theme"); + assert_eq!(scopes.theme_id(&SITE, &global, "t1", Some("p1")), "other"); + assert_eq!(scopes.theme_id(&SITE, &global, "t2", Some("p1")), "paper"); + assert_eq!(scopes.theme_id(&SITE, &global, "t2", Some("default")), "mine"); + assert_eq!(scopes.theme_id(&SITE, &global, "t3", None), "mine"); + // The global theme keeps its customizations; another theme is sent bare and alone. + let same = scopes.for_tab(&SITE, &global, "t9", None); + assert_eq!((same.accent.as_deref(), same.overrides.len(), same.themes.len()), (Some("#ff0000"), 1, 1)); + let other = scopes.for_tab(&SITE, &global, "t1", None); + assert_eq!((other.preset.as_str(), other.accent.as_deref(), other.overrides.len(), other.themes.len()), ("other", None, 0, 1)); + other.validate(&SITE).unwrap(); + let builtin = scopes.for_tab(&SITE, &global, "t5", Some("p1")); + assert_eq!((builtin.preset.as_str(), builtin.themes.len()), ("paper", 0)); + builtin.validate(&SITE).unwrap(); + } + + #[test] + fn scopes_are_bounded_and_checked() { + let parse = |value: Value| serde_json::from_value::(value).map_err(|e| e.to_string()).and_then(|s| s.validate().map(|()| s)); + assert!(parse(json!({})).unwrap().is_default()); + assert!(parse(json!({ "chrome": "own" })).is_ok()); + assert!(parse(json!({ "chrome": "rainbow" })).is_err()); + assert!(parse(json!({ "panes": { "t1": "Night Ink" } })).is_err(), "theme ids are slugs"); + assert!(parse(json!({ "panes": { "../t": "paper" } })).is_err(), "tab ids are checked"); + assert!(parse(json!({ "profiles": { "work": "paper" } })).is_err(), "profile ids are checked"); + assert!(parse(json!({ "script": {} })).is_err(), "unknown fields"); + let many: Map = (0..=MAX_PANE_THEMES).map(|i| (format!("t{i}"), json!("paper"))).collect(); + assert!(parse(json!({ "panes": many })).is_err()); + } + + #[test] + fn google_fonts_come_from_the_shown_theme_only() { + let global = with(json!({ "preset": "mine", "overrides": { "font": { "roles": { "numbers": { "family": ["Space Mono"], "source": "google" } } } }, + "themes": [ + { "id": "mine", "name": "Mine", "font": { "roles": { + "interface": { "family": ["Inter", "sans-serif"], "source": "google" }, + "post": { "family": ["Georgia"] }, + "chrome": { "family": ["Fraunces"], "source": "google" }, + "heading": { "family": ["../../evil"], "source": "google" } } } }, + { "id": "other", "name": "Other", "font": { "roles": { "post": { "family": ["Lora"], "source": "google" } } } } + ] })).unwrap(); + // Chrome fonts are the shell's; invalid names are dropped; overrides count. + assert_eq!(global.google_fonts(), vec!["Inter".to_string(), "Space Mono".to_string()]); + assert_eq!(global.for_theme(&SITE, "other").google_fonts(), vec!["Lora".to_string()]); + assert!(global.for_theme(&SITE, "paper").google_fonts().is_empty()); + } + + #[test] + fn default_and_empty() { + let own = ThemeChoice::default_for(&SITE); + assert!(own.is_default(&SITE) && own.is_empty(&SITE)); + assert_eq!(own.preset, "site"); + let kept = with(json!({ "preset": "site", "themes": [{ "id": "a", "name": "A" }] })).unwrap(); + assert!(kept.is_default(&SITE) && !kept.is_empty(&SITE)); + } + + /// The envelope checks are the theme file's JSON Schema (`waybetter/theme.schema.json`). + #[test] + fn envelope_rules_are_the_schema_rules() { + let schema: Value = serde_json::from_str(include_str!("../../../packages/waybetter/theme.schema.json")).unwrap(); + let properties = schema["properties"].as_object().unwrap(); + assert_eq!(schema["properties"]["id"]["pattern"], "^[a-z0-9-]{1,40}$"); + assert_eq!(schema["properties"]["name"]["maxLength"], MAX_NAME_CHARS); + for group in OVERRIDE_KEYS { + assert!(properties.contains_key(group), "{group} is a theme document group"); + } + assert_eq!(schema["required"], json!(["name"])); + let long = "a".repeat(41); + for (id, ok) in [("a", true), ("night-ink-2", true), ("A", false), ("a_b", false), (long.as_str(), false)] { + assert_eq!(valid_id(id), ok, "{id}"); + } + } +} diff --git a/crates/waybetter-host/src/updater.rs b/crates/waybetter-host/src/updater.rs new file mode 100644 index 0000000..d80ac1b --- /dev/null +++ b/crates/waybetter-host/src/updater.rs @@ -0,0 +1,275 @@ +//! Native updates (tauri-plugin-updater: the app's signed endpoint and public key from its +//! `tauri.conf.json`) and the signed, data-only hotfix channel, run from Rust (`tauri` + `net` +//! features). The scheduling and the crash handshake are [`crate::update`]; the hotfix format and +//! its verification are [`crate::hotfix`]. +//! +//! The app registers the updater plugin, calls [`init`] from `setup` with its [`UpdaterConfig`], +//! and wraps [`status`], [`apply`] and [`ready`] in its own shell-only commands; its shell gets an +//! `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data +//! ([`hotfix_script`]). + +use crate::hotfix::{self, Hotfix, Outcome}; +use crate::site::SiteSpec; +use crate::update::{self, PendingUpdate, UpdateStatus}; +use std::path::PathBuf; +use std::sync::Mutex; +use tauri::{AppHandle, Manager}; +use tauri_plugin_updater::{Update, UpdaterExt}; + +/// Shell event carrying the current [`UpdateStatus`]. +pub const EVENT: &str = "update-status"; +const HOTFIX_FILE: &str = "hotfix.json"; +const HOTFIX_SIG_FILE: &str = "hotfix.json.sig"; + +/// What differs between apps: the hotfix channel, the page names hotfix data is delivered under, +/// the manual download page and what to do when an update is ready. +pub struct UpdaterConfig { + /// Hotfix data goes to this site's tabs. + pub site: &'static SiteSpec, + /// Hotfix channel URL (`.sig` is appended for the signature). + pub hotfix_url: &'static str, + /// Hotfix public key (base64 of the minisign `.pub` file). + pub hotfix_pubkey: &'static str, + /// Page global and event the hotfix is delivered under (`window.`, ``). + pub hotfix_global: &'static str, + pub hotfix_event: &'static str, + /// Offered when an update keeps failing to start. + pub manual_download_url: &'static str, + /// Generic user agent of the hotfix fetch (no identifiers, no cookies). + pub user_agent: &'static str, + /// An update was downloaded and verified (`version`): e.g. a notification in the owner's language. + pub on_ready: fn(&AppHandle, &str), +} + +#[derive(Default)] +struct Inner { + status: Option, + /// A downloaded, signature-verified update waiting for the user's restart. + ready: Option<(Update, Vec)>, + hotfix: Option, + /// Automatic apply is off after repeated failed starts of an update. + problem: bool, +} + +struct UpdateState { + config: &'static UpdaterConfig, + inner: Mutex, +} + +fn status_of(config: &UpdaterConfig, inner: &Inner) -> UpdateStatus { + if inner.problem { + return UpdateStatus::Problem { download_url: config.manual_download_url.into() }; + } + inner.status.clone().unwrap_or(UpdateStatus::Idle) +} + +fn set_status(app: &AppHandle, status: UpdateStatus) { + let state = app.state::(); + let Ok(mut inner) = state.inner.lock() else { return }; + inner.status = Some(status); + let current = status_of(state.config, &inner); + drop(inner); + crate::host::emit_shell(app, EVENT, current); +} + +fn data_path(app: &AppHandle, name: &str) -> Option { + app.path().app_data_dir().ok().map(|dir| dir.join(name)) +} + +fn entropy() -> u64 { + let mut bytes = [0u8; 8]; + if getrandom::getrandom(&mut bytes).is_err() { + return std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0); + } + u64::from_le_bytes(bytes) +} + +/// Called from `setup`: runs the launch handshake, loads the cached hotfix and starts the loop +/// (first check after [`update::FIRST_CHECK`], then every 30 min +/- 5). +pub fn init(app: &AppHandle, config: &'static UpdaterConfig) { + let current = app.package_info().version.to_string(); + let pending_path = data_path(app, update::PENDING_FILE); + let pending = pending_path + .as_ref() + .and_then(|path| std::fs::read_to_string(path).ok()) + .and_then(|text| serde_json::from_str::(&text).ok()); + let decision = update::on_boot(pending, ¤t); + if let Some(path) = &pending_path { + match &decision.marker { + Some(marker) => { + let _ = std::fs::write(path, serde_json::to_string(marker).unwrap_or_default()); + } + None => { + let _ = std::fs::remove_file(path); + } + } + } + let hotfix = load_cached_hotfix(app, config, ¤t); + app.manage(UpdateState { config, inner: Mutex::new(Inner { problem: decision.problem, hotfix, ..Default::default() }) }); + + let app = app.clone(); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(update::FIRST_CHECK).await; + loop { + check_native(&app).await; + check_hotfix(&app).await; + tokio::time::sleep(update::next_check_delay(entropy())).await; + } + }); +} + +async fn check_native(app: &AppHandle) { + { + let state = app.state::(); + let Ok(inner) = state.inner.lock() else { return }; + // Already downloaded, or automatic apply disabled after failed starts. + // Also skip while an install is in flight (`ready` was taken by `apply`). + if inner.ready.is_some() || inner.problem || matches!(inner.status, Some(UpdateStatus::Installing { .. })) { + return; + } + } + set_status(app, UpdateStatus::Checking); + let update = match app.updater().map_err(|e| e.to_string()) { + Ok(updater) => updater.check().await.map_err(|e| e.to_string()), + Err(error) => Err(error), + }; + match update { + Ok(Some(update)) => { + let version = update.version.clone(); + set_status(app, UpdateStatus::Downloading { version: version.clone() }); + // The plugin verifies the minisign signature against the embedded pubkey here. + match update.download(|_, _| {}, || {}).await { + Ok(bytes) => { + let notes = update.body.clone().unwrap_or_default(); + let state = app.state::(); + if let Ok(mut inner) = state.inner.lock() { + inner.ready = Some((update, bytes)); + } + (state.config.on_ready)(app, &version); + set_status(app, UpdateStatus::Ready { version, notes }); + } + Err(error) => set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") }), + } + } + Ok(None) => set_status(app, UpdateStatus::UpToDate), + // Offline or server trouble: stay quiet, try again next round. + Err(error) => set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") }), + } +} + +fn load_cached_hotfix(app: &AppHandle, config: &UpdaterConfig, native: &str) -> Option { + let body = std::fs::read(data_path(app, HOTFIX_FILE)?).ok()?; + let sig = std::fs::read_to_string(data_path(app, HOTFIX_SIG_FILE)?).ok()?; + // Re-verified on every load: the cache on disk is not trusted either. Expired → defaults. + match hotfix::accept(config.hotfix_pubkey, &body, &sig, chrono::Utc::now(), native, None) { + Ok(Outcome::Accepted(hotfix)) => Some(hotfix), + _ => None, + } +} + +async fn fetch_limited(client: &reqwest::Client, url: &str, max: usize) -> Result, String> { + let response = client.get(url).send().await.map_err(|e| format!("HOTFIX: {e}"))?; + if !response.status().is_success() { + return Err(format!("HOTFIX: HTTP {}", response.status())); + } + if response.content_length().is_some_and(|len| len as usize > max) { + return Err("HOTFIX: response too large".into()); + } + // Stream with a hard cap: a chunked response without Content-Length must not grow unbounded. + let mut response = response; + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|e| format!("HOTFIX: {e}"))? { + if bytes.len() + chunk.len() > max { + return Err("HOTFIX: response too large".into()); + } + bytes.extend_from_slice(&chunk); + } + Ok(bytes) +} + +async fn check_hotfix(app: &AppHandle) { + if let Err(error) = try_check_hotfix(app).await { + let product = app.state::().config.site.product; + eprintln!("{product}: {error}"); + } +} + +async fn try_check_hotfix(app: &AppHandle) -> Result<(), String> { + let config = app.state::().config; + if rustls::crypto::CryptoProvider::get_default().is_none() { + let _ = rustls::crypto::ring::default_provider().install_default(); + } + // No identifiers: no cookies, no install id, a generic user agent. + let client = reqwest::Client::builder() + .user_agent(config.user_agent) + .timeout(std::time::Duration::from_secs(20)) + .build() + .map_err(|e| format!("HOTFIX: {e}"))?; + let body = fetch_limited(&client, config.hotfix_url, hotfix::MAX_BODY_BYTES).await?; + let sig_url = format!("{}.sig", config.hotfix_url); + let sig = fetch_limited(&client, &sig_url, hotfix::MAX_SIG_BYTES).await?; + let sig = String::from_utf8(sig).map_err(|_| "HOTFIX: signature is not text")?; + let native = app.package_info().version.to_string(); + let held = app.state::().inner.lock().ok().and_then(|inner| inner.hotfix.as_ref().map(|h| h.version)); + let Outcome::Accepted(hotfix) = hotfix::accept(config.hotfix_pubkey, &body, &sig, chrono::Utc::now(), &native, held)? else { + return Ok(()); + }; + if let (Some(body_path), Some(sig_path)) = (data_path(app, HOTFIX_FILE), data_path(app, HOTFIX_SIG_FILE)) { + let _ = std::fs::write(body_path, &body); + let _ = std::fs::write(sig_path, &sig); + } + let script = hotfix::script(&hotfix, config.hotfix_global, config.hotfix_event); + if let Ok(mut inner) = app.state::().inner.lock() { + inner.hotfix = Some(hotfix); + } + crate::host::eval_in_site_tabs(app, config.site, &script); + Ok(()) +} + +/// Hotfix data for a freshly loaded site document, if one is held. +pub fn hotfix_script(app: &AppHandle) -> Option { + let state = app.try_state::()?; + let inner = state.inner.lock().ok()?; + inner.hotfix.as_ref().map(|hotfix| hotfix::script(hotfix, state.config.hotfix_global, state.config.hotfix_event)) +} + +/// The current status (for the app's shell-only `update_status`). +pub fn status(app: &AppHandle) -> Result { + let state = app.try_state::().ok_or("UPDATE: state unavailable")?; + let inner = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?; + Ok(status_of(state.config, &inner)) +} + +/// Installs the downloaded update and restarts (the app's shell-only `apply_update`). On Windows +/// the quiet NSIS installer replaces the app and relaunches it (`/UPDATE /R`), and this process +/// exits inside `install`. +pub fn apply(app: &AppHandle) -> Result<(), String> { + let state = app.try_state::().ok_or("UPDATE: state unavailable")?; + let (update, bytes) = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?.ready.take().ok_or("UPDATE: no update is ready")?; + let version = update.version.clone(); + if let Some(path) = data_path(app, update::PENDING_FILE) { + let marker = PendingUpdate { version: version.clone(), boots: 0 }; + let _ = std::fs::write(path, serde_json::to_string(&marker).unwrap_or_default()); + } + set_status(app, UpdateStatus::Installing { version }); + if let Err(error) = update.install(&bytes) { + if let Some(path) = data_path(app, update::PENDING_FILE) { + let _ = std::fs::remove_file(path); + } + set_status(app, UpdateStatus::Error { message: format!("UPDATE: {error}") }); + return Err(format!("UPDATE: {error}")); + } + app.restart(); +} + +/// The shell reached a working state (the app's shell-only `app_ready`): confirms a +/// just-installed update and returns the status. +pub fn ready(app: &AppHandle) -> Result { + if let Some(path) = data_path(app, update::PENDING_FILE) { + let _ = std::fs::remove_file(path); + } + // `problem` is deliberately kept for this session: the shell always calls `app_ready` on + // mount, so clearing it here would hide the "Update problem" chip on the very launch that + // detected the failed starts. + status(app) +} diff --git a/crates/waybetter-host/src/workspaces.rs b/crates/waybetter-host/src/workspaces.rs new file mode 100644 index 0000000..9494f3d --- /dev/null +++ b/crates/waybetter-host/src/workspaces.rs @@ -0,0 +1,217 @@ +//! Saved workspaces (named tab/pane/deck layouts the shell builds), stored natively in app data +//! `workspaces.json` through the app's shell-only `workspaces_get` / `workspaces_set` commands. +//! +//! The shell builds and restores them; native code only keeps them bounded and well-formed: at most +//! [`MAX_WORKSPACES`], slug ids, names of 1–60 characters, each at most [`MAX_WORKSPACE_BYTES`], +//! at most [`MAX_TABS`] tabs, known tab kinds and http(s) URLs only, theme ids as slugs, and a +//! `default` that names one of them. Nothing here is ever evaluated. + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +pub const FILE: &str = "workspaces.json"; +pub const MAX_WORKSPACES: usize = 20; +pub const MAX_TABS: usize = 64; +pub const MAX_WORKSPACE_BYTES: usize = 256 * 1024; +const MAX_NAME: usize = 60; +const KINDS: [&str; 4] = ["web", "panel", "start", "deck"]; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WorkspaceStore { + #[serde(default = "version")] + pub version: u32, + #[serde(default)] + pub default: Option, + #[serde(default)] + pub items: Vec, +} + +fn version() -> u32 { + 1 +} + +/// No workspaces yet (what `workspaces_get` returns before the first save). +impl Default for WorkspaceStore { + fn default() -> Self { + Self { version: version(), default: None, items: Vec::new() } + } +} + +fn slug(id: &str, max: usize) -> bool { + !id.is_empty() && id.len() <= max && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +fn tab_id(id: &str) -> bool { + !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +fn http_url(value: &str) -> bool { + value.len() <= 4096 && url::Url::parse(value).is_ok_and(|url| matches!(url.scheme(), "http" | "https")) +} + +fn validate_panel(id: &str, panel: &Value) -> Result<(), String> { + let panel = panel.as_object().ok_or("VALIDATION: a workspace tab must be an object")?; + if !tab_id(id) || panel.get("id").and_then(Value::as_str) != Some(id) { + return Err("VALIDATION: invalid workspace tab id".into()); + } + let params = panel.get("params").and_then(Value::as_object).ok_or("VALIDATION: a workspace tab needs params")?; + let kind = params.get("kind").and_then(Value::as_str).unwrap_or(""); + if !KINDS.contains(&kind) { + return Err("VALIDATION: unknown workspace tab kind".into()); + } + for (key, value) in params { + match (key.as_str(), value) { + ("kind", _) => {} + ("url", Value::String(url)) if http_url(url) => {} + ("pinned", Value::Bool(_)) => {} + ("title", Value::String(title)) if title.chars().count() <= 300 => {} + ("profile" | "section" | "deckId", Value::String(text)) if text.len() <= 64 => {} + _ => return Err(format!("VALIDATION: workspace tab field \"{}\" is not allowed", key.chars().take(32).collect::())), + } + } + if kind == "web" && !params.contains_key("url") { + return Err("VALIDATION: a web tab needs a URL".into()); + } + Ok(()) +} + +fn validate_item(item: &Value) -> Result { + let object = item.as_object().ok_or("VALIDATION: a workspace must be an object")?; + let id = object.get("id").and_then(Value::as_str).ok_or("VALIDATION: a workspace needs an id")?; + if !slug(id, 40) { + return Err("VALIDATION: workspace ids are lowercase slugs".into()); + } + let name = object.get("name").and_then(Value::as_str).unwrap_or(""); + if name.trim().is_empty() || name.chars().count() > MAX_NAME || name.chars().any(char::is_control) { + return Err("VALIDATION: workspace names are 1-60 characters".into()); + } + for key in object.keys() { + if !["id", "name", "savedAt", "layout", "paneThemes", "decks"].contains(&key.as_str()) { + return Err("VALIDATION: unknown workspace field".into()); + } + } + let layout = object.get("layout").and_then(Value::as_object).ok_or("VALIDATION: a workspace needs a layout")?; + if !layout.get("grid").is_some_and(Value::is_object) { + return Err("VALIDATION: a workspace layout needs a grid".into()); + } + let panels = layout.get("panels").and_then(Value::as_object).ok_or("VALIDATION: a workspace layout needs panels")?; + if panels.is_empty() || panels.len() > MAX_TABS { + return Err(format!("VALIDATION: a workspace holds 1-{MAX_TABS} tabs")); + } + for (id, panel) in panels { + validate_panel(id, panel)?; + } + let themes = object.get("paneThemes").cloned().unwrap_or(Value::Object(Map::new())); + let themes = themes.as_object().ok_or("VALIDATION: pane themes must be an object")?; + for (tab, theme) in themes { + if !panels.contains_key(tab) || !theme.as_str().is_some_and(|theme| slug(theme, 40)) { + return Err("VALIDATION: invalid pane theme in workspace".into()); + } + } + if object.get("decks").is_some_and(|decks| !decks.is_array()) { + return Err("VALIDATION: workspace decks must be a list".into()); + } + if serde_json::to_vec(item).map(|bytes| bytes.len()).unwrap_or(usize::MAX) > MAX_WORKSPACE_BYTES { + return Err("VALIDATION: workspace is too large".into()); + } + Ok(id.to_owned()) +} + +impl WorkspaceStore { + pub fn validated(self) -> Result { + if self.version != 1 { + return Err("VALIDATION: unknown workspaces version".into()); + } + if self.items.len() > MAX_WORKSPACES { + return Err(format!("VALIDATION: at most {MAX_WORKSPACES} workspaces")); + } + let mut ids: Vec = Vec::new(); + for item in &self.items { + let id = validate_item(item)?; + if ids.contains(&id) { + return Err("VALIDATION: workspace ids must be unique".into()); + } + ids.push(id); + } + if let Some(default) = &self.default { + if !ids.contains(default) { + return Err("VALIDATION: the default workspace does not exist".into()); + } + } + Ok(self) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn workspace(id: &str) -> Value { + json!({ + "id": id, "name": "Launch day", "savedAt": "2026-09-29T10:00:00.000Z", + "layout": { + "grid": { "root": { "type": "branch", "data": [{ "type": "leaf", "data": { "views": ["t1", "deck-d1"], "activeView": "t1", "id": "1" } }] } }, + "panels": { + "t1": { "id": "t1", "contentComponent": "web", "params": { "kind": "web", "url": "https://x.com/home", "profile": "work" } }, + "deck-d1": { "id": "deck-d1", "contentComponent": "deck", "params": { "kind": "deck", "deckId": "d1" } } + } + }, + "paneThemes": { "t1": "nord" }, + "decks": [{ "id": "d1", "name": "Deck", "columns": [] }] + }) + } + + #[test] + fn the_empty_store_round_trips() { + // What workspaces_get returns before the first save must be accepted by workspaces_set. + let empty = WorkspaceStore::default(); + assert_eq!(empty.clone().validated().unwrap(), empty); + let parsed: WorkspaceStore = serde_json::from_value(serde_json::to_value(&empty).unwrap()).unwrap(); + assert!(parsed.validated().is_ok()); + } + + #[test] + fn accepts_bounded_layouts_and_a_default_that_exists() { + let store = WorkspaceStore { version: 1, default: Some("launch".into()), items: vec![workspace("launch"), workspace("night")] }; + assert!(store.clone().validated().is_ok()); + let missing = WorkspaceStore { default: Some("gone".into()), ..store.clone() }; + assert!(missing.validated().is_err()); + let twice = WorkspaceStore { default: None, items: vec![workspace("a"), workspace("a")], ..store }; + assert!(twice.validated().is_err()); + } + + #[test] + fn rejects_code_urls_unknown_fields_and_oversized_input() { + let with = |path: &[&str], value: Value| { + let mut item = workspace("a"); + let mut target = &mut item; + for key in &path[..path.len() - 1] { + target = target.get_mut(*key).unwrap(); + } + target[path[path.len() - 1]] = value; + WorkspaceStore { version: 1, default: None, items: vec![item] }.validated() + }; + assert!(with(&["layout", "panels", "t1", "params", "url"], json!("javascript:alert(1)")).is_err()); + assert!(with(&["layout", "panels", "t1", "params", "url"], json!("file:///C:/secret")).is_err()); + assert!(with(&["layout", "panels", "t1", "params", "cookie"], json!("sid=1")).is_err()); + assert!(with(&["layout", "panels", "t1", "params", "kind"], json!("script")).is_err()); + assert!(with(&["layout", "panels", "t1", "id"], json!("other")).is_err()); + assert!(with(&["paneThemes", "t1"], json!("Not A Slug")).is_err()); + assert!(with(&["paneThemes"], json!({ "t9": "nord" })).is_err(), "theme for a tab that is not in the layout"); + assert!(with(&["name"], json!("")).is_err()); + assert!(with(&["name"], json!("x".repeat(61))).is_err()); + assert!(with(&["extra"], json!(1)).is_err()); + assert!(with(&["decks"], json!([{ "notes": "y".repeat(MAX_WORKSPACE_BYTES) }])).is_err()); + let many = WorkspaceStore { version: 1, default: None, items: (0..=MAX_WORKSPACES).map(|n| workspace(&format!("w{n}"))).collect() }; + assert!(many.validated().is_err()); + let mut tabs = workspace("a"); + let panels = tabs["layout"]["panels"].as_object_mut().unwrap(); + for n in 0..MAX_TABS { + let id = format!("x{n}"); + panels.insert(id.clone(), json!({ "id": id, "params": { "kind": "start" } })); + } + assert!(WorkspaceStore { version: 1, default: None, items: vec![tabs] }.validated().is_err()); + } +} diff --git a/crates/waybetter-host/tab-bridge.js b/crates/waybetter-host/tab-bridge.js new file mode 100644 index 0000000..e094986 --- /dev/null +++ b/crates/waybetter-host/tab-bridge.js @@ -0,0 +1,135 @@ +// wayBetter tab bridge (waybetter-host `bridge.rs` serves this file). Injected into every browser +// tab (top frame only). Tells the shell about SPA URL changes, the favicon and focus and, when the +// app enables them, forwards browser shortcuts pressed while the page has focus and link drags. +// It can only call `tab_report` / `tab_shortcut` / `tab_link_drag`, which affect this tab's own +// address bar, forward a shortcut, or tell the shell a link drag started/entered/ended here. +(() => { + if (window.top !== window || window.__wbTabBridge) return; + window.__wbTabBridge = true; + const options = { shortcuts: true, linkDrags: true }; // waybetter-host: bridge::script() options + const invoke = (cmd, args) => { + const ipc = window.__TAURI_INTERNALS__; + if (ipc && typeof ipc.invoke === 'function') ipc.invoke(cmd, args).catch(() => {}); + }; + + let lastUrl = ''; + let lastTitle = ''; + let lastIcon = ''; + const favicon = () => { + const link = document.querySelector('link[rel~="icon"][href], link[rel="shortcut icon"][href]'); + try { return link ? new URL(link.getAttribute('href'), location.href).href : `${location.origin}/favicon.ico`; } catch { return ''; } + }; + const report = (extra) => { + const url = location.href; + const title = document.title || ''; + const icon = favicon(); + if (!extra && url === lastUrl && title === lastTitle && icon === lastIcon) return; + lastUrl = url; lastTitle = title; lastIcon = icon; + invoke('tab_report', { report: { url, title, favicon: icon, ...extra } }); + }; + let queued = false; + const schedule = () => { if (!queued) { queued = true; setTimeout(() => { queued = false; report(); }, 50); } }; + + for (const method of ['pushState', 'replaceState']) { + const original = history[method]; + history[method] = function (...args) { + const result = original.apply(this, args); + schedule(); + return result; + }; + } + addEventListener('popstate', schedule); + addEventListener('hashchange', schedule); + addEventListener('focus', () => report({ focused: true })); + addEventListener('pointerdown', () => report({ focused: true }), true); + const watchHead = () => { + if (!document.head) return; + new MutationObserver(schedule).observe(document.head, { childList: true, subtree: true, attributes: true, attributeFilter: ['href'] }); + schedule(); + }; + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watchHead, { once: true }); + else watchHead(); + + // Power User Mode: a deck column (the X runtime marks ) forwards the deck + // keys; bare keys only while nothing editable has focus. + const typing = () => { + const el = document.activeElement; + return !!el && (el.isContentEditable || /^(input|textarea|select)$/i.test(el.tagName)); + }; + const deckKey = (event) => { + const mod = event.ctrlKey || event.metaKey; + if (mod && event.shiftKey && !event.altKey && event.code === 'KeyD') return 'deck-toggle'; + if (!document.documentElement || !document.documentElement.hasAttribute('data-wb-column')) return null; + if (event.ctrlKey && event.altKey && !event.metaKey && !event.shiftKey && event.code === 'KeyN' && !typing()) return 'deck-compose'; + if (event.altKey && !mod && !event.shiftKey) { + const digit = /^Digit([1-9])$/.exec(event.code); + if (digit) return `column-${digit[1]}`; + if (event.key === 'PageUp') return 'column-page-prev'; + if (event.key === 'PageDown') return 'column-page-next'; + } + if (!mod && !event.altKey && !typing()) { + if (event.key === '[') return 'column-prev'; + if (event.key === ']') return 'column-next'; + } + return null; + }; + const shortcut = (event) => { + const deck = deckKey(event); + if (deck) return deck; + const mod = event.ctrlKey || event.metaKey; + const key = event.key.toLowerCase(); + if (mod && !event.altKey) { + if (key === 't' && event.shiftKey) return 'reopen-tab'; + if (key === 't') return 'new-tab'; + if (key === 'w' && event.shiftKey) return 'open-panel'; + if (key === 'w') return 'close-tab'; + if (key === 'l') return 'focus-address'; + if (key === 'k' && !event.shiftKey) return 'command-palette'; + if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab'; + if (key === 'r') return event.shiftKey ? 'hard-reload' : 'reload'; + // Physical key: layouts like Turkish-Q produce other characters on this key. + if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right'; + } + if (key === 'f5') return 'reload'; + if (event.altKey && !mod && key === 'arrowleft') return 'back'; + if (event.altKey && !mod && key === 'arrowright') return 'forward'; + return null; + }; + // Link drags: the shell hides the tab webviews and shows its split/tab drop zones, so a link + // dragged out of this page (or into it from another app) can be dropped as a new pane. + if (options.linkDrags) { + let localDrag = false; + let lastEnter = 0; + const linkTypes = (types) => { + const list = Array.from(types || []); + return !list.includes('Files') && (list.includes('text/uri-list') || list.includes('text/x-moz-url')); + }; + addEventListener('dragstart', (event) => { + localDrag = true; + // Links, and images inside links (sites like X wrap photos in `/status/.../photo/N` anchors). + const target = event.target; + const anchor = target && target.closest ? target.closest('a[href]') : null; + const url = anchor ? String(anchor.href) : ''; + if (/^https?:\/\//i.test(url) && url.length <= 4096) invoke('tab_link_drag', { phase: 'start', url }); + }, true); + addEventListener('dragend', () => { + localDrag = false; + invoke('tab_link_drag', { phase: 'end' }); + }, true); + addEventListener('dragenter', (event) => { + if (localDrag || !event.dataTransfer || !linkTypes(event.dataTransfer.types)) return; + const now = Date.now(); + if (now - lastEnter < 500) return; + lastEnter = now; + invoke('tab_link_drag', { phase: 'enter' }); + }, true); + } + + if (options.shortcuts) addEventListener('keydown', (event) => { + const action = shortcut(event); + if (!action) return; + event.preventDefault(); + event.stopImmediatePropagation(); + invoke('tab_shortcut', { shortcut: action }); + }, true); +})(); diff --git a/crates/waybetter-host/tests/fixtures/gfonts/inter.css b/crates/waybetter-host/tests/fixtures/gfonts/inter.css new file mode 100644 index 0000000..805bc71 --- /dev/null +++ b/crates/waybetter-host/tests/fixtures/gfonts/inter.css @@ -0,0 +1,63 @@ +/* cyrillic-ext */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2JL7SUc.woff2) format('woff2'); + unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; +} +/* cyrillic */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa0ZL7SUc.woff2) format('woff2'); + unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; +} +/* greek-ext */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2ZL7SUc.woff2) format('woff2'); + unicode-range: U+1F00-1FFF; +} +/* greek */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa1pL7SUc.woff2) format('woff2'); + unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; +} +/* vietnamese */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa2pL7SUc.woff2) format('woff2'); + unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; +} +/* latin-ext */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa25L7SUc.woff2) format('woff2'); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Inter'; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url(https://fonts.gstatic.com/s/inter/v20/UcC73FwrK3iLTeHuS_nVMrMxCp50SjIa1ZL7.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} diff --git a/crates/waybetter-host/tests/fixtures/gfonts/lato-text.css b/crates/waybetter-host/tests/fixtures/gfonts/lato-text.css new file mode 100644 index 0000000..f0839f1 --- /dev/null +++ b/crates/waybetter-host/tests/fixtures/gfonts/lato-text.css @@ -0,0 +1,14 @@ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 400; + src: url(https://fonts.gstatic.com/l/font?kit=S6uyw4BMUTPHvxwiUS_jT0aNgbBanoA&skey=2d58b92a99e1c086&v=v25) format('woff2'); + unicode-range: U+20, U+4c, U+53, U+61, U+65, U+6c-6d, U+6f-70, U+74; +} +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 700; + src: url(https://fonts.gstatic.com/l/font?kit=S6u9w4BMUTPHh6UVewqdFgekvrxQgpk3pro&skey=3480a19627739c0d&v=v25) format('woff2'); + unicode-range: U+20, U+4c, U+53, U+61, U+65, U+6c-6d, U+6f-70, U+74; +} diff --git a/crates/waybetter-host/tests/fixtures/gfonts/lato.css b/crates/waybetter-host/tests/fixtures/gfonts/lato.css new file mode 100644 index 0000000..be1ad92 --- /dev/null +++ b/crates/waybetter-host/tests/fixtures/gfonts/lato.css @@ -0,0 +1,36 @@ +/* latin-ext */ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url(https://fonts.gstatic.com/s/lato/v25/S6uyw4BMUTPHjxAwXjeu.woff2) format('woff2'); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url(https://fonts.gstatic.com/s/lato/v25/S6uyw4BMUTPHjx4wXg.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} +/* latin-ext */ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url(https://fonts.gstatic.com/s/lato/v25/S6u9w4BMUTPHh6UVSwaPGR_p.woff2) format('woff2'); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; +} +/* latin */ +@font-face { + font-family: 'Lato'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url(https://fonts.gstatic.com/s/lato/v25/S6u9w4BMUTPHh6UVSwiPGQ.woff2) format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} diff --git a/docs/STORE.md b/docs/STORE.md new file mode 100644 index 0000000..184459f --- /dev/null +++ b/docs/STORE.md @@ -0,0 +1,149 @@ +# The wayBetter Store, install links and the install screen + +Every wayBetter app can install themes and plugins from a dropped file, a `waybetter://install` +link or the signed wayBetter Store, always through its install screen. The framework has all of it: +the rules and the state (waybetter-host `store`), the UI (`waybetter/shell/InstallDialog`, +`waybetter/shell/StoreView`), the strings in every language (`wb.store.*`, `wb.install.*`, +`wb.permission.*` in the framework catalogs) and the tooling (`waybetter store build|sign|verify`). +An app adds its settings, its Tauri command wrappers, its theme format and its look. + +## One catalog, many apps + +The store is one folder, `https://waybetter.fyi/store/`, with one signed catalog shared by every +app (`catalog.json` + `catalog.json.sig`). Each item names the apps it is for; an app verifies the +whole file, then keeps only its own items: it never shows, stages or installs another app's item, +even one listed in the same signed file. + +```json +{ "format": 2, "name": "wayBetter Store", "generatedAt": "2026-09-29T04:18:08Z", "items": [ + { "apps": ["x"], "kind": "plugin", "id": "thread-reader", "name": "Thread Reader", "author": "wayBetter", + "version": "1.1.2", "description": "…", "category": "reading", "tags": ["threads"], + "url": "https://waybetter.fyi/store/plugins/bt-thread-reader.plugin.js", "file": "bt-thread-reader.plugin.js", + "sha256": "<64 lowercase hex>", "size": 12345, "preview": "https://waybetter.fyi/store/previews/plugin-thread-reader.svg", + "permissions": ["ui", "clipboard", "commands", "network:none"] }, + { "apps": ["x"], "kind": "theme", "id": "nord", "name": "Nord", "author": "", "version": "1.0.0", + "description": "…", "category": "dark", "tags": ["dark"], "url": "https://waybetter.fyi/store/themes/nord.json", + "sha256": "…", "size": 1700, "preview": "…", "colors": { "bg": "#232831", "surface": "#2e3440", "text": "#eceff4", "accent": "#88c0d0" } } +] } +``` + +JSON Schema: `waybetter/store-catalog.schema.json` (npm package). The rules apps enforce +(waybetter-host `store::catalog`, mirrored by the CLI): + +| Field | Rule | +| --- | --- | +| `format` | `2`. An app that reads another format says "update the app". Format 1 (before `apps`) is gone. | +| `apps` | 1–16 distinct app ids (`[a-z0-9-]{1,32}`), e.g. `"x"`; an item for several apps lists each. | +| `kind`, `id` | `theme` or `plugin`; `[a-z0-9-]{1,40}`, unique per app and kind. | +| `name`, `author`, `version`, `description`, `category`, `tags` | plain text (no control characters), ≤ 60 / 60 / 32 / 600 / 32 characters, ≤ 12 tags of ≤ 32. Known categories show in the reader's language (`wb.store.category.*`). | +| `url`, `preview` | https; for the reading app's own items, on its download hosts (below). | +| `file` | plugins only: `name.plugin.js` (letters, digits, `-_. `), unique per app ignoring case. | +| `sha256`, `size` | of the exact file; size 1 byte … 2 MiB. | +| `permissions` | plugins only: the header's `@permissions` (`null` = no line, legacy). | +| `colors` | themes only: `#rrggbb` swatches for the card. | + +Also refused: unknown fields anywhere, more than 500 items, a catalog over 1 MiB, a signature file +over 512 bytes. A malformed item for another app refuses the whole catalog (one file, one set of +rules); another app's download hosts are not held to this app's list. + +## Signing and keys + +The signature is Ed25519 over the exact catalog bytes (`verify_strict`), base64 of 64 bytes in +`catalog.json.sig`. Apps compile in the public keys (base64 of the raw 32 bytes) and accept a +catalog signed by any of them, so a key rotates in three steps: ship an app version that lists the +new key next to the old one, re-sign the catalog with the new key, drop the old key in a later +version. The private key is a PKCS#8 PEM that never leaves the machine it was made on; the CLI never +prints, copies or moves it. + +## Tooling: `waybetter store` + +```sh +waybetter store build --config store.config.mjs [--out public/store] [--base https://waybetter.fyi/store/] +waybetter store sign --init --key ~/.keys/store.key --pub keys/store.pub # once; never overwrites +waybetter store sign public/store/catalog.json --key ~/.keys/store.key --pub keys/store.pub +waybetter store verify public/store/catalog.json --pub keys/store.pub [--pub next.pub] [--app x] +``` + +`build` takes an app's config module: + +```js +export default { + app: 'x', + async items() { + return [{ kind: 'plugin', id: 'focus', name: 'Focus', version: '1.0.0', category: 'focus', tags: [], + file: 'focus.plugin.js', permissions: ['ui', 'network:none'], path: 'plugins/focus.plugin.js', bytes: source, + preview: { path: 'previews/plugin-focus.svg', bytes: svg } }]; + }, +}; +``` + +It replaces only that app's items (other apps' items and files stay), writes the files, fills +`apps`, `url`, `sha256` and `size`, removes files only the app's previous items used, and checks the +whole catalog with the apps' rules before writing anything. `pluginHeader(source)` (from +`waybetter/cli/store`) reads a plugin header for the config. `--key` defaults to +`$WAYBETTER_STORE_KEY`. Then deploy the folder as it is. + +## Install links + +`waybetter://install?kind=theme|plugin&url=` (the scheme is the app's +`StoreConfig::scheme`): https only, a host on the app's list (`DEFAULT_HOSTS`: `waybetter.fyi`, +`cdn1.crt.fyi`, and `git.crt.fyi` only for raw files `///raw/…`), default port, no +credentials or fragment, at most 2048 characters, no other or repeated parameters. A plugin URL must +end in `name.plugin.js`, the name it is saved under. A link only proposes an install: it is queued +for the shell (`install-link` event, `install_pending` for links that arrived before the shell +listened) and nothing is downloaded until the shell asks. + +## Trust model + +- Only the app's local shell webview may call the install commands; site tabs and web pages never + can. The framework has no commands of its own: the app's wrappers call `shell_only` first. +- Native code downloads (no redirects, no cookies, size caps), hashes and validates, and stages + the exact bytes under a random token; the screen shows those bytes; `Store::commit` writes exactly + them after validating them again, and refuses a commit less than 0.6 s after staging. The screen + keeps Install disabled for 1 s; Enter never confirms. +- Store items: catalog signature first, then the download's size and sha256. A link to a store file + that matches the catalog still shows as a link. +- Plugins: `plugins::validate_plugin` (file name, ≤ 2 MiB, UTF-8 text without binary bytes, header + with `@name` + `@version`, valid `@permissions`, `network:none` refused when the code calls + network APIs), then `PluginStore::install` (atomic rename, never enabled on its own; an update keeps + the enabled state). Themes: a JSON object with a `name` (≤ 2 MiB), then the app's own theme + sanitizer, as for any import. +- Permissions are a declaration and a guard rail, not a sandbox. + +## Adding the Store to an app + +Native (`waybetter-host` with the `net` feature): + +```rust +pub static STORE: StoreConfig = StoreConfig { + app_id: "kick", product: "wayBetter for Kick", user_agent: concat!("wayBetter-for-Kick/", env!("CARGO_PKG_VERSION")), + scheme: "waybetter", store_base: DEFAULT_STORE_BASE, public_keys: &[include_str!("../keys/store.pub")], + allowed_hosts: DEFAULT_HOSTS, +}; +// setup: app.manage(Store::new(&STORE, &plugins::HOST, app_data_dir)); +// deep links: emit_shell(app, EVENT_LINK, store.receive_link(url)). +``` + +Commands, each starting with `shell_only(&webview)?` and listed only in the shell's capability: +`install_pending` → `take_pending`, `install_stage_link {kind,url}` → `stage_link`, +`install_stage_file {name,text}` → `stage_file`, `install_cancel {token}` → `cancel`, +`install_commit {token,enable,themeId}` → `commit(…, run)` where `run` evaluates a plugin +start/stop script in the site's tabs, `plugin_remove {file}` → `remove_plugin`, `install_records` +→ `records`, `install_forget {kind,name}` → `forget`, `store_catalog {refresh}` → `catalog`, +`store_stage {item:{kind,id}}` → `stage_item`. + +Shell (React): + +```tsx +const controller = createInstallController({ backend: { invoke, listen }, t, site: 'Kick', theme: themeAdapter }); + }/> + invoke('store_catalog', { refresh })} + builtinThemes={…} userThemes={…} onRemove={…} onUse={…} notify={…} relativeTime={…}/> +``` + +`t` is the app's translator with the framework catalogs merged in (their English is +`STORE_MESSAGES`); `{site}` fills in the site's name. Import `waybetter/shell/store.css` and map the +`--wb-*` tokens listed at its top to the app's theme on `.wbs, .wbi-backdrop, .wbi-drop`. Pass your +own `controls` (Button, SearchField, Segmented, EmptyState, Badge) and `classNames` to match the +app's settings UI; the defaults work on their own. diff --git a/package.json b/package.json index 740acfe..2b918a5 100644 --- a/package.json +++ b/package.json @@ -10,18 +10,24 @@ "packages/*" ], "scripts": { - "typecheck": "tsc -p tsconfig.json", - "test": "bun run test:ts && bun run test:rust", + "typecheck": "tsc -p tsconfig.json && tsc -p packages/create-waybetter/tsconfig.json", + "test": "bun run test:ts && bun run test:rust && bun run test:create && bun run test:cli", "test:ts": "node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts", - "test:rust": "cargo test --manifest-path crates/waybetter-host/Cargo.toml --locked", - "check:tauri": "cargo check --manifest-path crates/waybetter-host/Cargo.toml --features tauri", + "test:create": "node --test packages/create-waybetter/tests/*.test.mjs", + "test:cli": "node --test packages/waybetter/tests/*.test.mjs", + "test:rust": "cargo test --manifest-path crates/waybetter-host/Cargo.toml --locked --features net", + "check:tauri": "cargo check --manifest-path crates/waybetter-host/Cargo.toml --features app,net", "build": "bun run typecheck && cargo build --manifest-path crates/waybetter-host/Cargo.toml --locked", "build:packages": "cd packages/waybetter && npm run build", - "pack:check": "bun run build:packages && npm pack ./packages/waybetter --dry-run", - "check": "bun run typecheck && bun run test" + "pack:check": "bun run build:packages && npm pack ./packages/waybetter --dry-run && npm pack ./packages/create-waybetter --dry-run", + "check": "bun run typecheck && bun run build:packages && bun run test" }, "devDependencies": { "@types/node": "^24.0.0", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "acorn": "^8.15.0", + "dockview": "^4", "typescript": "^5.9.0" }, "engines": { diff --git a/packages/create-waybetter/LICENSE b/packages/create-waybetter/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/packages/create-waybetter/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/packages/create-waybetter/README.md b/packages/create-waybetter/README.md new file mode 100644 index 0000000..3d9f921 --- /dev/null +++ b/packages/create-waybetter/README.md @@ -0,0 +1,67 @@ +# create-waybetter + +```sh +npm create waybetter +``` + +Scaffolds something for [wayBetter](https://waybetter.fyi), the framework behind wayBetter for X: +a **plugin**, a **theme**, or a whole new **wayBetter app** for another site. It asks what it needs +when run in a terminal; every answer is also a flag. No dependencies, Node 18.3+. + +## Plugin + +```sh +npm create waybetter plugin -- --name "Hide Trends" +npm create waybetter plugin -- --name "Word Badges" --ts # TypeScript project +``` + +One `*.plugin.js` file with the header the plugin store reads (`@name`, `@description`, +`@version`, `@author`) and a class with `start()` / `stop()`. The example uses the real plugin +API: `api.scope()` for cleanup, `api.storage()`, `scope.observe()`, `scope.onKey()`, the UI kit +(`scope.ui.toast` with an action, a settings `ui.dialog` built with `ui.h`) and the theme API +(`api.theme.current()`, `--wb-*` CSS variables). `--ts` makes a small TypeScript project typed by +the `waybetter` package; `npm run build` writes the loadable `dist/.plugin.js` with the header +first. `--app any` targets another wayBetter app (core API only; wayBetter for X adds +`api.tweet`, `api.account`, `api.users`). + +Install: **wayBetter → Plugins → Open folder**, copy the file in, **Rescan**, turn it on. + +## Theme + +```sh +npm create waybetter theme -- --name "Midnight Mint" --accent "#3ddc97" --font "Geist, system-ui" +``` + +A theme JSON with `"$schema": "https://unpkg.com/waybetter/theme.schema.json"` (editor completion +and checks), a full palette derived from `--bg`, `--text` and `--accent` the way the runtime derives +missing roles, and the font roles (`font.family` for the interface, `font.tweet` for post text). +Presets: `midnight`, `paper`, `dusk`. Import it in **wayBetter → Appearance → Import**. + +## App + +```sh +npm create waybetter app -- --site kick.com +npm create waybetter app -- --site youtube.com --name "wayBetter for YouTube" +``` + +A wayBetter app skeleton, the same system as wayBetter for X: a Tauri 2 window with a trusted +local shell and one native child webview per site tab (`waybetter-host`), the page runtime and +shell models from the `waybetter` package, and the site adapter in its three parts: + +- `src-tauri/src/site.rs`: the native `SiteSpec` (hosts, runtime global, account rules); +- `src/site.ts`: the page `SiteAdapter` (plugin API settings, account reader, link rules); +- `src-tauri/capabilities/`: `shell`, `tab-chrome` and `site-tab`, keyed by webview label. + +Presets for `youtube.com`, `kick.com` and `twitch.tv` (any host works); every selector and handle +rule is a marked PLACEHOLDER to check against the live site. The host crate comes from a git +submodule at `waybetter/` (default), a local path (`--host-source path --host-path `) or git +(`--host-source git`). + +## Options + +`npm create waybetter -- --help` lists every flag. `--yes` takes defaults for anything not given, +`--dry-run` prints the files, `--force` writes into a non-empty directory. + +## License + +GPL-3.0-or-later. See [LICENSE](./LICENSE). diff --git a/packages/create-waybetter/bin/create-waybetter.js b/packages/create-waybetter/bin/create-waybetter.js new file mode 100644 index 0000000..268dece --- /dev/null +++ b/packages/create-waybetter/bin/create-waybetter.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node +import { main } from '../src/cli.js'; + +main(process.argv.slice(2)).then( + code => { process.exitCode = code; }, + error => { + console.error(error); + process.exitCode = 1; + }, +); diff --git a/packages/create-waybetter/package.json b/packages/create-waybetter/package.json new file mode 100644 index 0000000..6d22f63 --- /dev/null +++ b/packages/create-waybetter/package.json @@ -0,0 +1,46 @@ +{ + "name": "create-waybetter", + "version": "0.1.0", + "license": "GPL-3.0-or-later", + "type": "module", + "description": "npm create waybetter: scaffold a wayBetter plugin (*.plugin.js, JS or TypeScript), theme (JSON with the waybetter theme schema) or a whole wayBetter app (Tauri 2 + waybetter-host + the waybetter runtime). No dependencies.", + "keywords": [ + "waybetter", + "create", + "scaffold", + "plugin", + "theme", + "tauri" + ], + "homepage": "https://waybetter.fyi", + "repository": { + "type": "git", + "url": "git+https://git.crt.fyi/CRT/waybetter.git", + "directory": "packages/create-waybetter" + }, + "bugs": { + "url": "https://git.crt.fyi/CRT/waybetter/issues" + }, + "bin": { + "create-waybetter": "bin/create-waybetter.js" + }, + "exports": { + ".": "./src/cli.js", + "./package.json": "./package.json" + }, + "files": [ + "bin", + "src", + "README.md", + "LICENSE" + ], + "engines": { + "node": ">=18.3.0" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "test": "cd ../.. && node --test packages/create-waybetter/tests/*.test.mjs" + } +} diff --git a/packages/create-waybetter/src/app.js b/packages/create-waybetter/src/app.js new file mode 100644 index 0000000..c9c4a27 --- /dev/null +++ b/packages/create-waybetter/src/app.js @@ -0,0 +1,1236 @@ +// `npm create waybetter -- app`: a whole wayBetter app skeleton for one site, per "One system for +// every app" in the waybetter README: a Tauri 2 window (trusted local shell + one child webview +// per site tab) on the `waybetter-host` crate, the page runtime and shell models from the +// `waybetter` package, and the site adapter in its three parts (native SiteSpec, page SiteAdapter, +// capabilities). Selectors are placeholders to fill in from the site's own DOM. + +import { deflateSync } from 'node:zlib'; +import { UsageError, camelCase, headerValue, lines, pascalCase, rustStr, slugify, str } from './names.js'; + +/** + * Known starting points. Everything site-specific is a placeholder until checked against the + * live site in devtools: selectors, handle rules, the avatar CDN. + */ +export const SITE_PRESETS = { + 'youtube.com': { + label: 'YouTube', + hosts: ['www.youtube.com'], + apiMarks: ['/youtubei/'], + avatarPrefixes: ['https://yt3.ggpht.com/'], + handle: { min: 3, max: 30, extra: '._-', sample: 'example_channel' }, + selectors: { + item: 'ytd-rich-item-renderer, ytd-video-renderer', + accountLink: 'ytd-active-account-header-renderer a[href^="/@"]', + accountAvatar: '#avatar-btn img', + signedOut: 'ytd-button-renderer a[href*="ServiceLogin"]', + itemLink: 'a[href^="/watch"], a[href^="/@"], a[href^="/shorts/"]', + }, + itemPath: '^/(watch|shorts/|@)', + accent: '#ff0033', + }, + 'kick.com': { + label: 'Kick', + hosts: ['kick.com'], + apiMarks: ['/api/'], + avatarPrefixes: ['https://files.kick.com/'], + handle: { min: 3, max: 25, extra: '_', sample: 'example_user' }, + selectors: { + item: '[data-chat-entry]', + accountLink: 'a[data-testid="user-profile-link"]', + accountAvatar: 'button[data-testid="user-menu"] img', + signedOut: 'button[data-testid="login"]', + itemLink: 'a[href^="/"]', + }, + itemPath: '^/[A-Za-z0-9_]{3,25}(/|$)', + accent: '#53fc18', + }, + 'twitch.tv': { + label: 'Twitch', + hosts: ['www.twitch.tv'], + apiMarks: ['gql.twitch.tv'], + avatarPrefixes: ['https://static-cdn.jtvnw.net/'], + handle: { min: 4, max: 25, extra: '_', sample: 'example_user' }, + selectors: { + item: '[data-a-target="chat-line-message"]', + accountLink: '[data-a-target="user-display-name"]', + accountAvatar: '[data-a-target="user-menu-toggle"] img', + signedOut: '[data-a-target="login-button"]', + itemLink: 'a[data-a-target="preview-card-image-link"]', + }, + itemPath: '^/[A-Za-z0-9_]{4,25}(/|$)', + accent: '#9146ff', + }, +}; + +const HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/; + +/** + * @typedef {{ name?: string, site: string, global?: string, identifier?: string, + * hostSource?: string, hostPath?: string, gitUrl?: string }} AppInput + */ + +/** @param {AppInput} input */ +export function normalizeAppOptions(input) { + const raw = String(input.site ?? '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, ''); + if (!raw) throw new UsageError('--site is required (for example youtube.com, kick.com, twitch.tv).'); + const presetKey = raw.replace(/^www\./, ''); + const preset = SITE_PRESETS[/** @type {keyof typeof SITE_PRESETS} */ (presetKey)]; + if (!HOSTNAME.test(raw)) throw new UsageError(`--site "${input.site}" is not a host name like kick.com.`); + const label = preset?.label ?? pascalCase(presetKey.split('.')[0]); + const site = preset ?? { + label, + hosts: [raw], + apiMarks: ['/api/'], + avatarPrefixes: [`https://${raw}/`], + handle: { min: 1, max: 30, extra: '_', sample: 'example_user' }, + selectors: { + item: '[data-example-item]', + accountLink: '[data-example-account] a[href^="/"]', + accountAvatar: '[data-example-account] img', + signedOut: '[data-example-sign-in]', + itemLink: 'a[href^="/"]', + }, + itemPath: '^/[^/]+/?$', + accent: '#3b82f6', + }; + const product = headerValue('App name', input.name || `wayBetter for ${label}`, { max: 60, required: true }); + const slug = slugify(product, 48); + if (!slug) throw new UsageError(`App name "${product}" needs at least one letter or digit.`); + const runtimeGlobal = String(input.global || pascalCase(product)).trim(); + if (!/^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/.test(runtimeGlobal) || runtimeGlobal === 'wayBetter') { + throw new UsageError(`--global "${runtimeGlobal}" must be a JS identifier (and not "wayBetter", which is the alias every app sets).`); + } + const identifier = String(input.identifier || `com.example.${slug.replace(/-/g, '')}`).trim(); + if (!/^[A-Za-z0-9][A-Za-z0-9-]*(\.[A-Za-z0-9][A-Za-z0-9-]*)+$/.test(identifier)) { + throw new UsageError(`--identifier "${identifier}" must be reverse-DNS like com.example.myapp.`); + } + const hostSource = String(input.hostSource || 'submodule'); + if (!['submodule', 'path', 'git'].includes(hostSource)) throw new UsageError('--host-source must be submodule, path or git.'); + if (hostSource === 'path' && !input.hostPath) throw new UsageError('--host-source path needs --host-path .'); + const key = slugify(label, 24) || 'site'; + return { + product, + slug, + crate: slug, + lib: `${slug.replace(/-/g, '_')}_lib`, + label, + site, + runtimeGlobal, + identifier, + hostSource, + hostPath: input.hostPath ? String(input.hostPath).replace(/\\/g, '/') : '', + gitUrl: String(input.gitUrl || 'https://git.crt.fyi/CRT/waybetter.git'), + prefix: `wb-${key}`, + dataKey: camelCase(`wb ${key} plugin`), + origin: `https://${site.hosts[0]}`, + }; +} + +/** @typedef {ReturnType} AppOptions */ + +/** Where `npm run build` writes what native code and Tauri load (tests check these exist). */ +export const APP_OUTPUTS = { runtime: 'src-tauri/runtime/runtime.js', shell: 'dist/index.html' }; + +/** The app's own native commands and who may call them (build.rs manifest and capability files). */ +const COMMANDS = { + shell: ['plugins_list', 'plugin_set_enabled', 'plugins_open_folder'], + tab: ['tab_report'], + site: ['site_ready'], +}; + +/** + * The commands waybetter-host serves for every app (`waybetter_host::commands::SHELL` / `TAB`: + * tab layout and actions, shell raise, external links, window menu, profiles, language; tab + * shortcuts and link drags). The capability files grant them; a test keeps this list in step. + */ +export const HOST_COMMANDS = { + shell: ['tabs_sync', 'tab_navigate', 'tab_action', 'open_external_url', 'shell_focus', 'shell_raise', 'window_system_menu', 'profiles_get', 'profiles_set', 'i18n_get', 'i18n_set'], + tab: ['tab_shortcut', 'tab_link_drag'], +}; +const permission = command => `allow-${command.replace(/_/g, '-')}`; + +/** The shell frame's window calls: its titlebar drag region, resize grips and caption buttons. */ +const WINDOW_PERMISSIONS = [ + 'core:window:allow-start-dragging', 'core:window:allow-start-resize-dragging', 'core:window:allow-internal-toggle-maximize', + 'core:window:allow-minimize', 'core:window:allow-toggle-maximize', 'core:window:allow-is-maximized', 'core:window:allow-close', + 'core:window:allow-set-background-color', +]; + +// --------------------------------------------------------------------------------------------- +// Icons: a small RGBA PNG (Tauri decodes it for the window icon) and an ICO wrapping it (the +// Windows resource). Replace both with real art (`npx tauri icon art.png`). + +function crc32(bytes) { + let crc = ~0; + for (const byte of bytes) { + crc ^= byte; + for (let k = 0; k < 8; k += 1) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); + } + return ~crc >>> 0; +} + +function chunk(type, data) { + const out = Buffer.alloc(12 + data.length); + out.writeUInt32BE(data.length, 0); + out.write(type, 4, 'ascii'); + data.copy(out, 8); + out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length); + return out; +} + +/** A `size`x`size` RGBA PNG: a rounded square in `color` with a lighter ring. */ +export function iconPng(size, color) { + const [r, g, b] = [1, 3, 5].map(i => parseInt(color.slice(i, i + 2), 16)); + const raw = Buffer.alloc((size * 4 + 1) * size); + const radius = size * 0.22; + for (let y = 0; y < size; y += 1) { + raw[y * (size * 4 + 1)] = 0; + for (let x = 0; x < size; x += 1) { + const dx = Math.max(radius - x - 0.5, x + 0.5 - (size - radius), 0); + const dy = Math.max(radius - y - 0.5, y + 0.5 - (size - radius), 0); + const inside = Math.hypot(dx, dy) <= radius; + const ring = Math.abs(Math.hypot(x + 0.5 - size / 2, y + 0.5 - size / 2) - size * 0.26) < size * 0.06; + const at = y * (size * 4 + 1) + 1 + x * 4; + raw[at] = ring ? 255 : r; + raw[at + 1] = ring ? 255 : g; + raw[at + 2] = ring ? 255 : b; + raw[at + 3] = inside ? 255 : 0; + } + } + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); + ihdr.writeUInt32BE(size, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 6; // RGBA + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', ihdr), + chunk('IDAT', deflateSync(raw)), + chunk('IEND', Buffer.alloc(0)), + ]); +} + +/** An ICO with one PNG image (Windows Vista+ and the `ico` crate read PNG entries). */ +export function iconIco(png, size) { + const head = Buffer.alloc(22); + head.writeUInt16LE(0, 0); + head.writeUInt16LE(1, 2); // icon + head.writeUInt16LE(1, 4); // one image + head[6] = size >= 256 ? 0 : size; + head[7] = size >= 256 ? 0 : size; + head.writeUInt16LE(1, 10); // planes + head.writeUInt16LE(32, 12); // bits per pixel + head.writeUInt32LE(png.length, 14); + head.writeUInt32LE(22, 18); + return Buffer.concat([head, png]); +} + +// --------------------------------------------------------------------------------------------- +// Rust + +/** @param {AppOptions} o */ +function hostDependency(o) { + if (o.hostSource === 'git') return `waybetter-host = { git = ${rustStr(o.gitUrl)} }`; + if (o.hostSource === 'path') { + const path = /\/crates\/waybetter-host\/?$/.test(o.hostPath) ? o.hostPath.replace(/\/$/, '') : `${o.hostPath.replace(/\/$/, '')}/crates/waybetter-host`; + return `waybetter-host = { path = ${rustStr(path)} }`; + } + return 'waybetter-host = { path = "../waybetter/crates/waybetter-host" }'; +} + +/** @param {AppOptions} o */ +function cargoToml(o) { + return lines( + '[package]', + `name = ${rustStr(o.crate)}`, + 'version = "0.1.0"', + `description = ${rustStr(`${o.product}: ${o.site.hosts[0]} in a light native window, extended in place`)}`, + '# waybetter-host is GPL-3.0-or-later, so an app built on it is too.', + 'license = "GPL-3.0-or-later"', + 'edition = "2021"', + 'rust-version = "1.88"', + '', + '[lib]', + `name = ${rustStr(o.lib)}`, + 'path = "src/lib.rs"', + '', + '[[bin]]', + `name = ${rustStr(o.crate)}`, + 'path = "src/main.rs"', + 'required-features = ["desktop"]', + '', + '[features]', + '# `desktop` is the Tauri app; without it (`--no-default-features`) the site adapter and plugin', + '# host build and test headless.', + 'default = ["desktop"]', + '# `waybetter-host/app`: the window, shell, tab webviews, plugins and generic commands (`run_app`).', + 'desktop = ["dep:tauri", "dep:tauri-build", "waybetter-host/app"]', + '', + '[build-dependencies]', + 'tauri-build = { version = "2", features = [], optional = true }', + '# The host\'s command list for the app-command manifest (`waybetter_host::commands::manifest`).', + hostDependency(o), + '', + '[dependencies]', + '# The wayBetter framework: security policy, profiles, plugin store, tab payloads and, with', + '# the desktop feature, the app itself (`waybetter_host::app`).', + hostDependency(o), + 'tauri = { version = "2", features = ["unstable"], optional = true }', + 'serde = { version = "1", features = ["derive"] }', + 'serde_json = "1"', + 'url = "2"', + ); +} + +function buildRs() { + const all = [...COMMANDS.shell, ...COMMANDS.tab, ...COMMANDS.site]; + return lines( + 'fn main() {', + ' // The app-command manifest: tauri-build generates an `allow-` permission for each,', + ' // which the capability files grant per webview label. `manifest` adds the commands the', + ' // wayBetter host serves for every app (`waybetter_host::commands`).', + ' #[cfg(feature = "desktop")]', + ' tauri_build::try_build(tauri_build::Attributes::new().app_manifest(', + ` tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&[${all.map(c => `"${c}"`).join(', ')}])),`, + ' ))', + ' .expect("Tauri build configuration must be valid");', + '}', + ); +} + +/** @param {AppOptions} o */ +function siteRs(o) { + const { handle } = o.site; + const extra = [...handle.extra].map(ch => `b'${ch === "'" ? "\\'" : ch}'`); + const byteRule = extra.length ? `b.is_ascii_alphanumeric() || ${extra.map(ch => `b == ${ch}`).join(' || ')}` : 'b.is_ascii_alphanumeric()'; + return lines( + `//! The native half of the ${o.label} site adapter: which webviews are site tabs, the page`, + '//! runtime\'s global, and how the account seen inside a profile is validated.', + '', + 'use waybetter_host::site::{AccountRules, SiteSpec};', + '', + `/// PLACEHOLDER: a handle ${o.label} could really have (without \`@\`). Check the site's own rules.`, + 'pub fn valid_handle(handle: &str) -> bool {', + ` (${handle.min}..=${handle.max}).contains(&handle.len()) && handle.bytes().all(|b| ${byteRule})`, + '}', + '', + 'pub static SITE: SiteSpec = SiteSpec {', + ` product: ${rustStr(o.product)},`, + ' // Exact https origin(s) of site tabs: the only definition of "a site tab".', + ` hosts: &[${o.site.hosts.map(rustStr).join(', ')}],`, + ' // window. of the page runtime (src/runtime/main.ts); plugins use the', + ' // `window.wayBetter` alias.', + ` runtime_global: ${rustStr(o.runtimeGlobal)},`, + ' accounts: AccountRules {', + ' valid_handle,', + ` // PLACEHOLDER: the site's own avatar CDN; other avatar URLs are dropped.`, + ` avatar_prefixes: &[${o.site.avatarPrefixes.map(rustStr).join(', ')}],`, + ' max_name_chars: 50,', + ' max_avatar_len: 512,', + ' },', + '};', + '', + '#[cfg(test)]', + 'mod tests {', + ' use super::*;', + ' use url::Url;', + '', + ' #[test]', + ' fn only_the_exact_site_origin_is_a_site_tab() {', + ` assert!(SITE.is_origin(&Url::parse(${rustStr(`${o.origin}/some/page`)}).unwrap()));`, + ` assert!(!SITE.is_origin(&Url::parse(${rustStr(`http://${o.site.hosts[0]}/`)}).unwrap()));`, + ` assert!(!SITE.is_origin(&Url::parse(${rustStr(`https://user:pass@${o.site.hosts[0]}/`)}).unwrap()));`, + ' assert!(!SITE.is_origin(&Url::parse("https://example.org/").unwrap()));', + ' }', + '', + ' #[test]', + ' fn handles_follow_the_site_rules() {', + ` assert!(valid_handle(${rustStr(handle.sample)}));`, + ' assert!(!valid_handle(""));', + ' assert!(!valid_handle("has space"));', + ' }', + '}', + ); +} + +/** @param {AppOptions} o */ +function pluginsRs(o) { + return lines( + '//! BetterDiscord-style plugins for the site page: `*.plugin.js` files in the app-data', + '//! `plugins` folder and custom CSS, on the waybetter-host plugin store.', + '', + 'use std::path::PathBuf;', + 'use waybetter_host::plugins::{PluginHost, PluginStore};', + '', + 'pub static HOST: PluginHost = PluginHost {', + ` runtime_global: ${rustStr(o.runtimeGlobal)},`, + ' // Plugins run only in the top frame of this exact origin.', + ` origin: ${rustStr(o.origin)},`, + ` product: ${rustStr(o.product)},`, + ` css_element_id: ${rustStr(`${o.prefix}-custom-css`)},`, + ' // Written (disabled) into a freshly created plugins folder.', + ' example: Some(("example.plugin.js", include_str!("../../plugins/example.plugin.js"))),', + ' // First-party plugins shipped with the app: written disabled, upgraded only while untouched.', + ' bundled: &[],', + '};', + '', + '/// The plugin store in `dir` (the app-data `plugins` folder).', + 'pub fn store(dir: PathBuf) -> PluginStore {', + ' PluginStore::new(dir, &HOST)', + '}', + '', + '#[cfg(test)]', + 'mod tests {', + ' use super::*;', + ' use crate::site::SITE;', + '', + ' #[test]', + ' fn plugins_run_on_the_site_origin_with_its_runtime() {', + ' assert_eq!(HOST.origin, SITE.primary_origin());', + ' assert_eq!(HOST.runtime_global, SITE.runtime_global);', + ' }', + '', + ' #[test]', + ' fn the_example_plugin_has_a_header() {', + ' let (file, source) = HOST.example.unwrap();', + ' assert!(waybetter_host::plugins::valid_file_name(file));', + ' assert_eq!(waybetter_host::plugins::parse_meta(file, source).name, "Example");', + ' }', + '}', + ); +} + +/** @param {AppOptions} o */ +function libRs(o) { + return lines( + `//! ${o.product}: ${o.site.hosts[0]} in one light native window (a trusted local shell and one`, + '//! child webview per site tab), extended in place with the wayBetter page runtime and plugins.', + '', + 'pub mod plugins;', + 'pub mod site;', + '', + '#[cfg(feature = "desktop")]', + 'mod desktop;', + '', + '#[cfg(feature = "desktop")]', + 'pub use desktop::run;', + ); +} + +/** @param {AppOptions} o */ +function mainRs(o) { + return lines( + '#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]', + '', + 'fn main() {', + ` ${o.lib}::run();`, + '}', + ); +} + +/** @param {AppOptions} o */ +function desktopRs(o) { + return lines( + '//! The app on the wayBetter host: `waybetter_host::app` makes the window, the trusted local', + '//! `shell` webview filling it and one native child webview per tab (placed over the pane', + '//! rectangles the shell reports), registers the Tauri plugins and serves the generic commands', + '//! (tab layout and actions, shell raise, profiles, language). This file adds the site hooks and', + '//! the app\'s own commands. Every command re-checks its caller: the capability files are not the', + '//! boundary.', + '', + 'use crate::{plugins, site::SITE};', + 'use serde::{Deserialize, Serialize};', + 'use std::sync::{Mutex, MutexGuard};', + 'use tauri::{AppHandle, Manager, State, Webview};', + 'use url::Url;', + 'use waybetter_host::app::{App, AppConfig, NewTab, SiteHooks};', + 'use waybetter_host::bridge::{self, BridgeOptions};', + 'use waybetter_host::host;', + 'use waybetter_host::plugins::{PluginStore, ScriptPlugin};', + 'use waybetter_host::profiles::Account;', + 'use waybetter_host::tabs::TabState;', + '', + '/// The page runtime (src/runtime/main.ts), written by `npm run build`.', + 'const RUNTIME: &str = include_str!("../runtime/runtime.js");', + '', + 'struct AppState {', + ' plugins: Mutex,', + '}', + '', + 'fn store<\'a>(state: &\'a State<\'_, AppState>) -> Result, String> {', + ' state.plugins.lock().map_err(|_| "PLUGINS: state unavailable".to_string())', + '}', + '', + '// ---------------------------------------------------------------------------------------------', + '// Shell-only commands', + '', + '#[tauri::command]', + 'async fn plugins_list(webview: Webview, state: State<\'_, AppState>) -> Result, String> {', + ' host::shell_only(&webview)?;', + ' store(&state)?.list()', + '}', + '', + '/// Turns a plugin on or off and starts/stops it live in every site tab.', + '#[tauri::command]', + 'async fn plugin_set_enabled(', + ' webview: Webview,', + ' app: AppHandle,', + ' state: State<\'_, AppState>,', + ' file: String,', + ' enabled: bool,', + ') -> Result, String> {', + ' host::shell_only(&webview)?;', + ' let store = store(&state)?;', + ' // Built first, so a broken file is reported before it is marked enabled.', + ' let script = if enabled {', + ' store.start_script(&file)?', + ' } else {', + ' waybetter_host::plugins::stop_script(&plugins::HOST, &file)?', + ' };', + ' store.set_enabled(&file, enabled)?;', + ' let list = store.list()?;', + ' drop(store);', + ' host::eval_in_site_tabs(&app, &SITE, &script);', + ' Ok(list)', + '}', + '', + '#[tauri::command]', + 'async fn plugins_open_folder(webview: Webview, state: State<\'_, AppState>) -> Result<(), String> {', + ' host::shell_only(&webview)?;', + ' let dir = {', + ' let store = store(&state)?;', + ' store.ensure()?;', + ' store.dir().to_path_buf()', + ' };', + ' #[cfg(target_os = "windows")]', + ' let opener = "explorer";', + ' #[cfg(target_os = "macos")]', + ' let opener = "open";', + ' #[cfg(not(any(target_os = "windows", target_os = "macos")))]', + ' let opener = "xdg-open";', + ' std::process::Command::new(opener).arg(dir).spawn().map(|_| ()).map_err(|error| format!("PLUGINS: {error}"))', + '}', + '', + '// ---------------------------------------------------------------------------------------------', + '// Tab commands', + '', + '#[derive(Deserialize)]', + '#[serde(rename_all = "camelCase")]', + 'struct TabReport {', + ' url: Option,', + ' title: Option,', + ' account: Option,', + ' #[serde(default)]', + ' signed_out: bool,', + '}', + '', + '#[derive(Clone, Serialize)]', + 'struct TabAccount {', + ' id: String,', + ' /// None: signed out (or a handle the site could not have).', + ' account: Option,', + '}', + '', + '/// Any tab, about itself only: its URL/title for the address bar and, from a tab that is on the', + '/// site right now, the account the site\'s own UI shows.', + '#[tauri::command]', + 'async fn tab_report(webview: Webview, app: AppHandle, report: TabReport) -> Result<(), String> {', + ' let id = host::tab_only(&webview)?;', + ' if report.url.is_some() || report.title.is_some() {', + ' // The URL is the webview\'s own, never the page\'s claim.', + ' let url = webview.url().ok().map(|url| url.to_string());', + ' host::emit_tab_state(&app, TabState::reported(id.clone(), url, report.title, None, None));', + ' }', + ' if (report.account.is_some() || report.signed_out) && host::site_tab_only(&SITE, &webview).is_ok() {', + ' let account = report.account.and_then(|account| account.validated(&SITE.accounts));', + ' host::emit_shell(&app, "tab-account", TabAccount { id, account });', + ' }', + ' Ok(())', + '}', + '', + '#[derive(Clone, Serialize)]', + 'struct SiteReady {', + ' id: String,', + ' url: String,', + '}', + '', + '/// A site-only command: callable only from a `tab-*` webview that is on the exact site origin', + '/// (capability `site-tab`, re-checked here). Add the app\'s own site commands the same way.', + '#[tauri::command]', + 'async fn site_ready(webview: Webview, app: AppHandle) -> Result<(), String> {', + ' let url = host::site_tab_only(&SITE, &webview)?;', + ' let id = host::tab_only(&webview)?;', + ' host::emit_shell(&app, "site-ready", SiteReady { id, url: url.to_string() });', + ' Ok(())', + '}', + '', + '// ---------------------------------------------------------------------------------------------', + '// The site on the wayBetter host', + '', + '/// What only this app knows about its tabs (see `waybetter_host::app::SiteHooks` for the rest:', + '/// legacy domains, link routing, per-tab state, ...).', + 'struct Site;', + '', + 'impl SiteHooks for Site {', + ' fn init_scripts(&self, _app: &AppHandle, _tab: &NewTab) -> Vec {', + ' vec![', + ' // The framework tab bridge: reports each tab\'s URL and title to the address bar and', + ' // forwards its browser shortcuts and link drags to the shell (the shell frame handles both).', + ' bridge::script(BridgeOptions::ALL),', + ' // The runtime checks the origin itself and stays inert on other sites.', + ' RUNTIME.to_owned(),', + ' ]', + ' }', + '', + ' /// Enabled plugins and custom CSS, evaluated natively (the page\'s CSP cannot block them).', + ' fn site_page_loaded(&self, app: &AppHandle, tab: &Webview, _url: &Url) {', + ' let scripts = app', + ' .state::()', + ' .plugins', + ' .lock()', + ' .map(|store| {', + ' let mut scripts: Vec = waybetter_host::plugins::css_script(&plugins::HOST, &store.css()).into_iter().collect();', + ' scripts.extend(store.start_scripts());', + ' scripts', + ' })', + ' .unwrap_or_default();', + ' for script in scripts {', + ' let _ = tab.eval(&script);', + ' }', + ' }', + '}', + '', + '// ---------------------------------------------------------------------------------------------', + '// App', + '', + 'pub fn run() {', + ' let config = AppConfig {', + ' window_size: (1280.0, 820.0),', + ' min_window_size: (720.0, 480.0),', + ' // The shell frame draws the titlebar (tabs in it, caption buttons on Windows).', + ' custom_titlebar: true,', + ' ..AppConfig::new(&SITE, SITE.product)', + ' };', + ' App::new(config, Site)', + ' .setup(|app| {', + ' let store = plugins::store(app.path().app_data_dir()?.join("plugins"));', + ' store.ensure()?;', + ' app.manage(AppState { plugins: Mutex::new(store) });', + ' Ok(())', + ' })', + ` .run(tauri::generate_context!(), tauri::generate_handler![${[...COMMANDS.shell, ...COMMANDS.tab, ...COMMANDS.site].join(', ')}]);`, + '}', + ); +} + +/** @param {AppOptions} o */ +function securityRs(o) { + const quote = list => list.map(c => `"${c}"`).join(', '); + return lines( + `//! Who may call which command, read from the capability files, and whether each command checks`, + '//! its caller first (waybetter-host `testkit`). Runs with `npm run test:rust`.', + '', + 'use waybetter_host::testkit::{assert_guarded, assert_host_guards, Capabilities};', + '', + 'fn capabilities() -> Capabilities {', + ' Capabilities::from_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/capabilities"))', + '}', + '', + '#[test]', + 'fn host_commands_keep_their_callers() {', + ' capabilities().assert_host_commands();', + ' assert_host_guards();', + '}', + '', + '#[test]', + 'fn app_commands_keep_their_callers() {', + ' let caps = capabilities();', + ' let source = include_str!("../src/desktop.rs");', + ` for command in [${quote(COMMANDS.shell)}] {`, + ' caps.assert_shell_only(command);', + ' assert_guarded(source, command, "host::shell_only(&webview)?");', + ' }', + ` for command in [${quote([...COMMANDS.tab, ...COMMANDS.site])}] {`, + ' caps.assert_tab_only(command);', + ' }', + ' assert_guarded(source, "tab_report", "host::tab_only(&webview)?");', + ' assert_guarded(source, "site_ready", "host::site_tab_only(&SITE, &webview)?");', + ' // Only Rust drives the Tauri plugins; no capability exposes their JS APIs.', + ' caps.assert_no_plugin_apis(&["updater", "process", "notification", "deep-link", "single-instance", "window-state", "opener", "dialog"]);', + '}', + ); +} + +/** @param {AppOptions} o */ +function tauriConf(o) { + return { + $schema: 'https://schema.tauri.app/config/2', + productName: o.product, + version: '0.1.0', + identifier: o.identifier, + build: { + beforeDevCommand: 'npm run build', + beforeBuildCommand: 'npm run build', + frontendDist: '../dist', + }, + app: { + withGlobalTauri: true, + // The window is made by waybetter-host (`app::run_app`: a multiwebview window, shell + tab webviews). + windows: [], + security: { + capabilities: ['shell', 'tab-chrome', 'site-tab'], + csp: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src ipc: http://ipc.localhost; object-src 'none'; base-uri 'none'; frame-src 'none'; form-action 'none'", + }, + }, + bundle: { + active: true, + targets: 'all', + icon: ['icons/icon.png', 'icons/icon.ico'], + }, + }; +} + +/** @param {AppOptions} o */ +function capabilities(o) { + const cap = value => `${JSON.stringify({ $schema: '../gen/schemas/desktop-schema.json', ...value }, null, 2)}\n`; + return [ + { + path: 'src-tauri/capabilities/shell.json', + content: cap({ + identifier: 'shell', + description: 'The trusted local shell: tabs (the wayBetter host\'s layout, actions, profiles and language) and plugins. No generic filesystem or shell APIs.', + webviews: [/** policy::SHELL_LABEL */ 'shell'], + local: true, + permissions: ['core:event:default', ...WINDOW_PERMISSIONS, ...HOST_COMMANDS.shell.map(permission), ...COMMANDS.shell.map(permission)], + }), + }, + { + path: 'src-tauri/capabilities/tab-chrome.json', + content: cap({ + identifier: 'tab-chrome', + description: 'Every tab (any site): report its own URL, title and, on the site, its account; forward its shortcuts and link drags. Nothing else.', + webviews: ['tab-*'], + local: false, + remote: { urls: ['https://*/*', 'http://*/*'] }, + permissions: [...COMMANDS.tab.map(permission), ...HOST_COMMANDS.tab.map(permission)], + }), + }, + { + path: 'src-tauri/capabilities/site-tab.json', + content: cap({ + identifier: 'site-tab', + description: `Tabs on ${o.site.hosts.join(', ')} only: the app's short, reviewed list of site commands.`, + webviews: ['tab-*'], + local: false, + remote: { urls: o.site.hosts.map(host => `https://${host}/*`) }, + permissions: COMMANDS.site.map(permission), + }), + }, + ]; +} + +/** @param {AppOptions} o */ +function releaseConfig(o) { + return { + product: o.product, + artifact: o.product.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || o.slug, + desktopDir: '.', + // PLACEHOLDERS: where the signing key lives (never in the repository) and where releases go. + keysDir: `~/.${o.slug}-keys`, + keysDirEnv: 'WAYBETTER_KEYS_DIR', + cdnBase: `https://downloads.example.com/${o.slug}`, + apiBase: 'https://updates.example.com', + outDir: 'releases', + }; +} + +// --------------------------------------------------------------------------------------------- +// TypeScript: site adapter, page runtime, shell + +/** @param {AppOptions} o */ +function siteTs(o) { + const s = o.site.selectors; + return lines( + `// The page half of the ${o.label} site adapter (waybetter/runtime/site): every runtime module`, + '// takes only its piece. Must agree with the native `SiteSpec` in src-tauri/src/site.rs.', + '', + "import type { SiteAdapter } from 'waybetter/runtime/site';", + "import type { SeenAccount } from 'waybetter/runtime/accountReport';", + '', + '/**', + ` * PLACEHOLDER selectors: starting guesses for ${o.site.hosts[0]}. Open the site in devtools and`, + ' * replace each one; sites change their markup, so prefer stable attributes (data-*, aria-*).', + ' */', + 'export const SELECTORS = {', + ' /** One item plugins act on (a post, a message, a video card). */', + ` item: ${str(s.item)},`, + ' /** A link to the signed-in account (its href holds the handle). */', + ` accountLink: ${str(s.accountLink)},`, + ' /** The signed-in account\'s avatar image. */', + ` accountAvatar: ${str(s.accountAvatar)},`, + ' /** Only present on the signed-out page. */', + ` signedOut: ${str(s.signedOut)},`, + ' /** Links to the site\'s own pages that the "links" setting may open beside the pane. */', + ` itemLink: ${str(s.itemLink)},`, + '} as const;', + '', + `/** PLACEHOLDER: paths of the site's own pages a click may divert (see links.clickedUrl). */`, + `const ITEM_PATH = new RegExp(${str(o.site.itemPath)});`, + '', + 'function readAccount(root: ParentNode): SeenAccount | null {', + ' const link = root.querySelector(SELECTORS.accountLink);', + ' if (!link) return null;', + " const handle = (link.getAttribute('href') ?? '').replace(/^\\/+@?/, '').split(/[/?#]/)[0] ?? '';", + ' if (!handle) return null;', + ' const avatar = root.querySelector(SELECTORS.accountAvatar)?.src ?? null;', + " return { handle, name: link.textContent?.trim() || handle, avatar };", + '}', + '', + 'function clickedUrl(target: Element | null, location: Location): string | null {', + ' const anchor = target?.closest(SELECTORS.itemLink);', + ' if (!anchor?.href) return null;', + ' const url = new URL(anchor.href, location.href);', + ' return url.origin === location.origin && ITEM_PATH.test(url.pathname) && url.href !== location.href ? url.href : null;', + '}', + '', + 'export const SITE: SiteAdapter = {', + ` product: ${str(o.product)},`, + ` hosts: [${o.site.hosts.map(str).join(', ')}],`, + ` runtimeGlobal: ${str(o.runtimeGlobal)},`, + ' heavyPath: null,', + ` apiMarks: [${o.site.apiMarks.map(str).join(', ')}],`, + ' xhrMarks: [],', + ' plugins: {', + ` name: ${str(o.runtimeGlobal)},`, + ` product: ${str(o.product)},`, + ` storagePrefix: ${str(`${o.prefix}-plugin:`)},`, + ` styleDataKey: ${str(o.dataKey)},`, + ` toastId: ${str(`${o.prefix}-ui`)},`, + ` toastBackground: ${str(o.site.accent)},`, + ' itemSelector: SELECTORS.item,', + " // Keys that start one of the site's own two-key shortcuts.", + ' chordKeys: [],', + ' },', + ' account: { read: readAccount, signedOut: root => !!root.querySelector(SELECTORS.signedOut) },', + " links: { configKey: 'site', clickedUrl },", + '};', + ); +} + +/** @param {AppOptions} o */ +function addressTs(o) { + return lines( + '// Address bar chips (waybetter/shell/addressModel): how the shell names this site\'s pages.', + '', + "import type { AddressSite, Segment } from 'waybetter/shell/addressModel';", + "import { SITE } from './site.ts';", + '', + 'function label(part: string): string {', + ' try { return decodeURIComponent(part); } catch { return part; }', + '}', + '', + 'export const ADDRESS_SITE: AddressSite = {', + " kind: 'site',", + ' hosts: new Set(SITE.hosts),', + ` label: ${str(o.label)},`, + ' home: origin => `${origin}/`,', + ' // PLACEHOLDER: one chip per path part; name the site\'s own pages (a channel, a video) here.', + ' segments(url): Segment[] {', + " const parts = url.pathname.split('/').filter(Boolean).slice(0, 3);", + " return parts.map((part, index) => ({ label: label(part), href: `${url.origin}/${parts.slice(0, index + 1).join('/')}` }));", + ' },', + '};', + ); +} + +function runtimeTs() { + return lines( + '// The page runtime, injected into every tab and active only on the site\'s origin (top frame).', + '// It sets `window.` (and the `window.wayBetter` alias plugins use) with the', + '// plugin API; native code then evaluates the enabled `*.plugin.js` files against it.', + '', + "import { configureRuntime, isSiteUrl } from 'waybetter/runtime/site';", + "import { createCorePluginApi, type CorePluginApi } from 'waybetter/runtime/pluginApi';", + "import { installAccountReport, type Invoke } from 'waybetter/runtime/accountReport';", + "import { installLinkRouting } from 'waybetter/runtime/linkRouting';", + "import { SITE } from '../site.ts';", + '', + 'type Runtime = {', + ' api: CorePluginApi;', + ' /** Running plugins by file (native start/stop scripts manage this). */', + ' plugins: Record;', + ' /** Load errors by plugin file. */', + ' errors: Record;', + '};', + '', + 'type TauriInternals = { invoke(command: string, args: Record): Promise };', + '', + 'function install(): void {', + ' if (window.top !== window || !isSiteUrl(SITE, location.href)) return;', + ' const globals = window as unknown as Record;', + ' if (globals[SITE.runtimeGlobal]) return;', + ' configureRuntime(SITE);', + ' // No theme engine yet: `api.theme` reports the page\'s own colors. Pass `{ theme: source }`', + ' // (a ThemeSource from waybetter/runtime/themeApi) once the app has themes.', + ' const api = createCorePluginApi(window, SITE.plugins);', + ' const runtime: Runtime = { api, plugins: {}, errors: {} };', + ' globals[SITE.runtimeGlobal] = runtime;', + ' globals.wayBetter = runtime;', + '', + ' const ipc = (globals.__TAURI_INTERNALS__ ?? null) as TauriInternals | null;', + ' const invoke: Invoke | undefined = ipc ? (command, args) => ipc.invoke(command, args) : undefined;', + ' if (SITE.account) installAccountReport(window, SITE.account, invoke);', + ' // "same" until native code configures it: in-page clicks are left alone.', + ' if (SITE.links) installLinkRouting(window, SITE.links);', + " invoke?.('site_ready', {}).catch(() => {});", + '}', + '', + 'try {', + ' install();', + '} catch (error) {', + ' console.error(`[${SITE.product}] runtime failed`, error);', + '}', + ); +} + +/** @param {AppOptions} o */ +function shellTs(o) { + const { handle } = o.site; + const handleChars = handle.extra.replace(/[\\\]^-]/g, ch => `\\${ch}`); + return lines( + '// The shell: the wayBetter shell frame (waybetter/shell/frame) with this site\'s pages and the', + '// app\'s own panel. Tabs in the titlebar, splits, the address bar, the new-tab page, the command', + '// palette (Ctrl+K) and the account switcher are the framework\'s; native code places each tab\'s', + '// webview over its pane (tabs_sync).', + '', + "import { createRoot } from 'react-dom/client';", + "import { createI18n } from 'waybetter/i18n';", + "import en from 'waybetter/locales/en.json' with { type: 'json' };", + "import { isSiteUrl } from 'waybetter/runtime/site';", + "import { parseAddress } from 'waybetter/shell/addressModel';", + "import { createShell, type ShellSite } from 'waybetter/shell/frame';", + "import { ADDRESS_SITE } from '../address.ts';", + "import { SITE } from '../site.ts';", + "import { Panel } from './Panel.tsx';", + "import './app.css';", + '', + `const ORIGIN = ${str(o.origin)};`, + '', + '/** English; merge `waybetter/locales/.json` (and your own catalog) for other languages. */', + "const i18n = createI18n({ source: en.messages, available: ['en'] });", + '', + 'const site: ShellSite = {', + ` name: ${str(o.label)},`, + ' product: SITE.product,', + " logo: './icon.png',", + ' homeUrl: `${ORIGIN}/`,', + " // PLACEHOLDER: the site's own sign-in and sign-out pages.", + ' loginUrl: `${ORIGIN}/login`,', + ' logoutUrl: `${ORIGIN}/logout`,', + ' isSiteUrl: url => isSiteUrl(SITE, url),', + ' // Same rules as src-tauri/src/site.rs (valid_handle, avatar_prefixes).', + ` accounts: { handle: /^[A-Za-z0-9${handleChars}]{${handle.min},${handle.max}}$/, avatarPrefixes: [${o.site.avatarPrefixes.map(str).join(', ')}], handlePrefix: '@' },`, + " // PLACEHOLDER: the site's search page.", + ' searchUrl: text => `${ORIGIN}/search?q=${encodeURIComponent(text)}`,', + ' address: url => parseAddress(url, ADDRESS_SITE),', + " panel: { id: 'app', title: SITE.product, component: Panel },", + ' newTab: {', + ` search: () => ${str(`Search ${o.label}`)},`, + " links: [{ id: 'home', label: () => 'Home', icon: 'home', url: home => home }],", + ' },', + ' palette: {', + " placeholder: () => 'Search tabs, pages and settings',", + " sections: [{ id: 'plugins', label: () => 'Plugins', keywords: 'extensions js', icon: 'grid' }],", + ' },', + ' // Native features this app does not wire up yet (waybetter-host workspaces, sync, devmode,', + ' // plugins::commands): the frame shows nothing of them until they are switched on here.', + ' features: { workspaces: false, sync: false, developer: false, pluginCommands: false },', + '};', + '', + 'const { core, event, window: tauriWindow } = window.__TAURI__;', + 'const Shell = createShell(site, { native: { invoke: core.invoke, listen: event.listen, currentWindow: tauriWindow.getCurrentWindow }, i18n });', + "createRoot(document.getElementById('root')!).render();", + ); +} + +function panelTsx() { + return lines( + '// The app\'s own tab (Ctrl+Shift+W, the brand button, Ctrl+K "Plugins"): its settings. Here: the', + '// plugins in the plugins folder, each switched on or off live in every site tab.', + '', + "import { useEffect, useState } from 'react';", + '', + 'type Plugin = { file: string; name: string; description: string; version: string; author: string; enabled: boolean };', + '', + 'export function Panel(_props: { section?: { name: string; nonce: number } }) {', + ' const [plugins, setPlugins] = useState([]);', + " const [error, setError] = useState('');", + ' const { invoke } = window.__TAURI__.core;', + " const run = (promise: Promise) => promise.then(list => { if (list) setPlugins(list); setError(''); }, failure => setError(String(failure)));", + " useEffect(() => { void run(invoke('plugins_list')); }, []);", + ' return
', + '

Plugins

', + ' {error &&

{error}

}', + ' {plugins.map(plugin => )}', + " ", + '
;', + '}', + ); +} + +function tauriTypes() { + return lines( + '// `window.__TAURI__` in the shell (tauri.conf.json: app.withGlobalTauri): what the shell frame and', + '// the panel call. Swap for `@tauri-apps/api` if you prefer imports.', + '', + 'type TauriWindow = {', + ' minimize(): Promise;', + ' toggleMaximize(): Promise;', + ' close(): Promise;', + " startResizeDragging(direction: 'North' | 'South' | 'East' | 'West' | 'NorthEast' | 'NorthWest' | 'SouthEast' | 'SouthWest'): Promise;", + ' isMaximized(): Promise;', + ' onResized(handler: () => void): Promise<() => void>;', + ' setBackgroundColor(color: [number, number, number, number]): Promise;', + '};', + '', + 'interface Window {', + ' __TAURI__: {', + ' core: { invoke(command: string, args?: Record): Promise };', + ' event: { listen(event: string, handler: (event: { payload: T }) => void): Promise<() => void> };', + ' window: { getCurrentWindow(): TauriWindow };', + ' };', + '}', + ); +} + +/** @param {AppOptions} o */ +function indexHtml(o) { + return lines( + '', + '', + '', + ' ', + ' ', + ' ', + ` ${o.product.replace(/[<&]/g, ch => (ch === '<' ? '<' : '&'))}`, + ' ', + ' ', + ' ', + ' ', + '', + '', + '
', + '', + '', + ); +} + +/** @param {AppOptions} o */ +function appCss(o) { + return lines( + "/* The app's own panel. The shell frame's styles come with it (dockview and the frame's CSS,", + ' bundled into dist/shell.css); its colors are the --wb-c-* tokens (Night Ink by default). */', + `:root { --app-accent: ${o.site.accent}; }`, + '.app-panel { height: 100%; box-sizing: border-box; overflow: auto; padding: 24px 28px; color: var(--wb-c-text, #eef0f7); background: var(--wb-c-ground, #07080c); font: 14px/1.45 system-ui, sans-serif; }', + '.app-panel h1 { margin: 0 0 16px; font-size: 18px; }', + '.app-row { display: flex; gap: 10px; align-items: flex-start; padding: 10px 0; border-bottom: 1px solid var(--wb-c-line, #1e2333); }', + '.app-row small { display: block; color: var(--wb-c-muted, #8a90a6); }', + '.app-panel button { margin-top: 16px; font: inherit; color: inherit; background: var(--wb-c-raised, #141823); border: 1px solid var(--wb-c-line, #1e2333); border-radius: 8px; padding: 6px 12px; cursor: pointer; }', + '.app-panel input { accent-color: var(--app-accent); }', + '.app-error { color: #ffb4b4; }', + ); +} + +/** @param {AppOptions} o */ +function examplePlugin(o) { + return lines( + '/**', + ' * @name Example', + ` * @description Example plugin for ${o.product}: outlines each item and says hello. Turn it on in Plugins.`, + ' * @version 1.0.0', + ` * @author ${o.product}`, + ' */', + 'module.exports = class Example {', + ' start() {', + ' const api = window.wayBetter.api;', + ' this.scope = api.scope();', + ` this.scope.css('example', ${str(`${o.site.selectors.item} { outline: 1px dashed var(--wb-accent); }`)});`, + " this.scope.ui.toast('Example plugin started', { tone: 'success' });", + ' }', + '', + ' stop() {', + ' this.scope.dispose();', + ' }', + '};', + ); +} + +function buildMjs() { + return lines( + '// Builds the page runtime (one IIFE that native code injects into tabs) and the shell (the local', + '// page Tauri serves from dist/: the wayBetter shell frame, bundled with its styles), both with', + "// `waybetter/build`, and writes the shell's first-frame script.", + "import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs';", + "import { buildRuntime } from 'waybetter/build';", + "import { bootScript } from 'waybetter/shell/frame/boot';", + '', + "mkdirSync('dist', { recursive: true });", + `await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)} });`, + 'await buildRuntime({', + " entry: 'src/shell/main.tsx',", + " outfile: 'dist/shell.js',", + " format: 'esm',", + " jsx: 'automatic',", + ' minify: false,', + ' // CSS imports (dockview, the frame, app.css) are bundled into dist/shell.css.', + ' inlineCss: false,', + " // Developer mode's syntax check loads acorn; this app does not switch developer mode on.", + " external: ['acorn'],", + '});', + "writeFileSync('dist/boot.js', bootScript());", + "copyFileSync('src/shell/index.html', 'dist/index.html');", + "copyFileSync('src-tauri/icons/icon.png', 'dist/icon.png');", + "console.log('built dist/ and " + APP_OUTPUTS.runtime + "');", + ); +} + +/** @param {AppOptions} o */ +function readme(o) { + const submodule = o.hostSource === 'submodule'; + return lines( + `# ${o.product}`, + '', + `${o.site.hosts[0]} in one light native window, extended in place: a wayBetter app made with`, + '`npm create waybetter`. It is the same system as every wayBetter app: a Tauri 2 window with a', + 'trusted local **shell** and one native child webview per **tab**, the **page runtime** injected', + 'into tabs on the site, and a small **site adapter**.', + '', + '## Run it', + '', + '```sh', + ...(submodule ? [`git init && git submodule add ${o.gitUrl} waybetter # the framework (host crate)`] : []), + 'npm install', + 'npm run build # dist/ (shell) and ' + APP_OUTPUTS.runtime + ' (page runtime)', + 'npm run tauri dev # the app', + 'npm run test:rust # site adapter + plugin host tests, headless', + '```', + '', + 'Requires Node 18+, Rust 1.88+ and the Tauri 2 prerequisites for your platform.', + '', + '## Layout', + '', + '```', + 'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)', + 'src/address.ts address bar chips for the site\'s pages', + 'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, account report', + 'src/shell/main.tsx the shell: the wayBetter shell frame (createShell) with this site\'s pages', + 'src/shell/Panel.tsx the app\'s own tab (its settings: the plugins)', + 'plugins/example.plugin.js written (disabled) into a new plugins folder', + 'src-tauri/src/site.rs SiteSpec: the native half (hosts, runtime global, account rules)', + 'src-tauri/src/plugins.rs the plugin store (PluginHost)', + 'src-tauri/src/desktop.rs config, site hooks and the app\'s own commands (waybetter_host::app runs the rest)', + 'src-tauri/capabilities/ shell / tab-chrome / site-tab, keyed by webview label', + 'src-tauri/tests/security.rs who may call what (waybetter_host::testkit)', + 'waybetter.release.json `npm run release`: signed builds and the update manifest (PLACEHOLDER URLs)', + '```', + '', + '## Make it yours', + '', + `1. Open ${o.origin} in a browser's devtools and replace every PLACEHOLDER in \`src/site.ts\``, + ' and `src-tauri/src/site.rs` (selectors, handle rules, the avatar CDN).', + '2. Keep `hosts` and the runtime global identical in `site.ts` and `site.rs`.', + '3. Add site-only commands like `site_ready`: `host::site_tab_only(&SITE, &webview)?` first,', + ' then list them in `build.rs`, `capabilities/site-tab.json` and `tests/security.rs`.', + '4. Next steps from the framework: account profiles (`waybetter_host::profiles`), split panes', + ' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes', + ' (`waybetter/runtime/themeApi`, `theme.schema.json`), signed updates (`updater: true` in the', + ' `AppConfig`, `plugins.updater` and `bundle.createUpdaterArtifacts` in tauri.conf.json, then', + ' `waybetter.release.json` and `npm run release`).', + '', + '## Security model', + '', + '- Only the local `shell` webview may call shell commands (`host::shell_only`), the host\'s too.', + '- Any tab may only report about itself (`tab_report`); the URL used is the webview\'s own.', + '- Tabs on the exact site origin may call the short list in `site-tab.json`, re-checked natively.', + '- Plugins are files the owner copies into the plugins folder; native code evaluates them only', + ' in the site\'s top frame.', + '', + 'License: GPL-3.0-or-later (waybetter-host is GPL-3.0-or-later).', + ); +} + +/** @param {AppOptions} o */ +export function appFiles(o) { + const png = iconPng(64, o.site.accent); + const json = value => `${JSON.stringify(value, null, 2)}\n`; + const pkg = { + name: o.slug, + version: '0.1.0', + private: true, + type: 'module', + license: 'GPL-3.0-or-later', + description: `${o.product}: ${o.site.hosts[0]} in a light native window, extended in place.`, + scripts: { + build: 'node scripts/build.mjs', + typecheck: 'tsc -p tsconfig.json', + tauri: 'tauri', + 'test:rust': 'cargo test --manifest-path src-tauri/Cargo.toml --no-default-features', + release: 'waybetter release windows', + 'release:macos': 'waybetter release macos', + }, + dependencies: { dockview: '^4.0.0', react: '^19.0.0', 'react-dom': '^19.0.0', waybetter: '^0.4.0' }, + devDependencies: { '@tauri-apps/cli': '^2.0.0', '@types/react': '^19.0.0', '@types/react-dom': '^19.0.0', esbuild: '^0.25.0', typescript: '^5.9.0' }, + }; + const tsconfig = { + compilerOptions: { + target: 'ES2022', + lib: ['ES2022', 'DOM', 'DOM.Iterable'], + module: 'ESNext', + moduleResolution: 'Bundler', + allowImportingTsExtensions: true, + resolveJsonModule: true, + jsx: 'react-jsx', + noEmit: true, + strict: true, + noUnusedLocals: true, + skipLibCheck: true, + isolatedModules: true, + types: [], + }, + include: ['src'], + }; + return [ + { path: 'README.md', content: readme(o) }, + { path: 'package.json', content: json(pkg) }, + { path: 'tsconfig.json', content: json(tsconfig) }, + { path: '.gitignore', content: lines('node_modules/', 'dist/', 'releases/', 'src-tauri/target/', 'src-tauri/gen/', APP_OUTPUTS.runtime) }, + { path: 'waybetter.release.json', content: json(releaseConfig(o)) }, + { path: 'scripts/build.mjs', content: buildMjs() }, + { path: 'src/site.ts', content: siteTs(o) }, + { path: 'src/address.ts', content: addressTs(o) }, + { path: 'src/runtime/main.ts', content: runtimeTs() }, + { path: 'src/shell/main.tsx', content: shellTs(o) }, + { path: 'src/shell/Panel.tsx', content: panelTsx() }, + { path: 'src/shell/index.html', content: indexHtml(o) }, + { path: 'src/shell/app.css', content: appCss(o) }, + { path: 'src/tauri.d.ts', content: tauriTypes() }, + { path: 'plugins/example.plugin.js', content: examplePlugin(o) }, + { path: 'src-tauri/Cargo.toml', content: cargoToml(o) }, + { path: 'src-tauri/build.rs', content: buildRs() }, + { path: 'src-tauri/tauri.conf.json', content: json(tauriConf(o)) }, + ...capabilities(o), + { path: 'src-tauri/icons/icon.png', content: png }, + { path: 'src-tauri/icons/icon.ico', content: iconIco(png, 64) }, + { path: 'src-tauri/src/main.rs', content: mainRs(o) }, + { path: 'src-tauri/src/lib.rs', content: libRs(o) }, + { path: 'src-tauri/src/site.rs', content: siteRs(o) }, + { path: 'src-tauri/src/plugins.rs', content: pluginsRs(o) }, + { path: 'src-tauri/src/desktop.rs', content: desktopRs(o) }, + { path: 'src-tauri/tests/security.rs', content: securityRs(o) }, + // Replaced by `npm run build`; here so `cargo check` works before the first build. + { path: APP_OUTPUTS.runtime, content: lines('// Placeholder: `npm run build` writes the page runtime here (src/runtime/main.ts).') }, + ]; +} diff --git a/packages/create-waybetter/src/cli.js b/packages/create-waybetter/src/cli.js new file mode 100644 index 0000000..26ec01e --- /dev/null +++ b/packages/create-waybetter/src/cli.js @@ -0,0 +1,253 @@ +// `npm create waybetter`: scaffolds a wayBetter plugin, theme or app. Interactive when run in a +// terminal without the answers; fully flag-driven otherwise (`--yes` takes the defaults). + +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { createInterface } from 'node:readline/promises'; +import { parseArgs } from 'node:util'; +import { SITE_PRESETS, appFiles, normalizeAppOptions } from './app.js'; +import { UsageError, slugify } from './names.js'; +import { PLUGIN_APPS, normalizePluginOptions, pluginFiles } from './plugin.js'; +import { THEME_MODES, THEME_PRESETS, normalizeThemeOptions, themeFiles } from './theme.js'; + +export const KINDS = ['plugin', 'theme', 'app']; + +/** @type {import('node:util').ParseArgsConfig['options']} */ +const OPTIONS = ({ + type: { type: 'string', short: 't' }, + name: { type: 'string', short: 'n' }, + description: { type: 'string' }, + author: { type: 'string' }, + 'plugin-version': { type: 'string' }, + ts: { type: 'boolean' }, + typescript: { type: 'boolean' }, + app: { type: 'string' }, + mode: { type: 'string' }, + preset: { type: 'string' }, + bg: { type: 'string' }, + text: { type: 'string' }, + accent: { type: 'string' }, + font: { type: 'string' }, + 'post-font': { type: 'string' }, + radius: { type: 'string' }, + schema: { type: 'string' }, + site: { type: 'string', short: 's' }, + global: { type: 'string' }, + identifier: { type: 'string' }, + 'host-source': { type: 'string' }, + 'host-path': { type: 'string' }, + 'git-url': { type: 'string' }, + yes: { type: 'boolean', short: 'y' }, + force: { type: 'boolean' }, + 'dry-run': { type: 'boolean' }, + help: { type: 'boolean', short: 'h' }, + version: { type: 'boolean', short: 'v' }, +}); + +export const HELP = `Usage: npm create waybetter [plugin|theme|app] [dir] -- [options] + npx create-waybetter [plugin|theme|app] [dir] [options] + +Scaffolds a wayBetter plugin, theme or whole app. Asks for anything missing when run in a +terminal; --yes takes the defaults instead. + +Common + -t, --type plugin, theme or app + -n, --name display name (plugin/theme name, or the app's product name) + --author plugin/theme author (default "you") + --description + -y, --yes no questions; use defaults for anything not given + --force write into a directory that is not empty + --dry-run print the files instead of writing them + -h, --help this help + -v, --version print the create-waybetter version + +Plugin (one *.plugin.js with the header the plugin store reads) + --plugin-version plugin version (default 1.0.0) + --ts a TypeScript project (types from the waybetter package) + --app x: wayBetter for X (adds api.tweet/account/users); any: another app + +Theme (JSON with "$schema" pointing at the waybetter theme schema) + --preset ${Object.keys(THEME_PRESETS).join(', ')} (seed colors, default midnight) + --mode ${THEME_MODES.join(', ')} + --bg, --text, --accent <#hex> seed colors; the rest of the palette is derived + --font interface fonts, e.g. "Geist, system-ui" + --post-font post text fonts + --radius <0-28> card corner radius (default 16) + --schema "$schema" as the unpkg URL (default) or ./node_modules path + +App (Tauri 2 + waybetter-host + the waybetter runtime and shell models) + -s, --site ${Object.keys(SITE_PRESETS).join(', ')} or any host name + --global the page runtime's window global (default from the name) + --identifier Tauri bundle identifier (default com.example.) + --host-source submodule (default: ../waybetter as a git submodule), path or git + --host-path with --host-source path: the waybetter repository (or its host crate) + --git-url the waybetter repository for submodule/git + +Examples + npm create waybetter plugin -- --name "Hide Trends" + npm create waybetter theme my-theme -- --name "Midnight Mint" --accent "#3ddc97" --yes + npm create waybetter app wb-kick -- --site kick.com --yes +`; + +/** @typedef {{ stdout: { write(text: string): unknown }, stderr: { write(text: string): unknown }, stdin: NodeJS.ReadableStream & { isTTY?: boolean }, cwd: string }} Io */ + +function packageVersion() { + try { + return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version; + } catch { + return 'unknown'; + } +} + +/** Minimal line prompts over readline (no dependencies). */ +function prompter(io) { + /** @type {import('node:readline/promises').Interface | null} */ + let rl = null; + const ask = async (question, fallback = '') => { + rl ??= createInterface({ input: io.stdin, output: /** @type {any} */ (io.stdout) }); + const answer = (await rl.question(`${question}${fallback ? ` (${fallback})` : ''}: `)).trim(); + return answer || fallback; + }; + return { + ask, + async choose(question, choices, fallback) { + for (;;) { + const answer = (await ask(`${question} [${choices.join('/')}]`, fallback)).toLowerCase(); + if (choices.includes(answer)) return answer; + io.stdout.write(` Choose one of: ${choices.join(', ')}\n`); + } + }, + async confirm(question, fallback) { + const answer = (await ask(`${question} [y/n]`, fallback ? 'y' : 'n')).toLowerCase(); + return answer.startsWith('y'); + }, + close() { rl?.close(); }, + }; +} + +/** + * Runs the CLI. Returns the exit code; never calls process.exit (tests call it in-process). + * @param {string[]} argv arguments after the program name + * @param {Partial} [ioInput] + */ +export async function main(argv, ioInput = {}) { + /** @type {Io} */ + const io = { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin, cwd: process.cwd(), ...ioInput }; + let parsed; + try { + parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true }); + } catch (error) { + io.stderr.write(`${/** @type {Error} */ (error).message}\n\nRun with --help for usage.\n`); + return 1; + } + /** @type {Record} */ + const values = parsed.values; + const positionals = parsed.positionals; + if (values.help) { io.stdout.write(HELP); return 0; } + if (values.version) { io.stdout.write(`${packageVersion()}\n`); return 0; } + + const interactive = !values.yes && Boolean(io.stdin.isTTY); + const ui = prompter(io); + try { + // `npm create waybetter plugin [dir]`: a leading kind is the type. + let type = values.type ?? (KINDS.includes(positionals[0] ?? '') ? positionals.shift() : undefined); + if (!type) { + if (!interactive) throw new UsageError('--type is required (plugin, theme or app) when not asking questions.'); + type = await ui.choose('What do you want to make?', KINDS, 'plugin'); + } + if (!KINDS.includes(type)) throw new UsageError(`--type must be one of: ${KINDS.join(', ')}.`); + const ask = async (value, question, fallback) => value ?? (interactive ? await ui.ask(question, fallback) : fallback); + + /** @type {Array<{ path: string, content: string | Uint8Array }>} */ + let files; + let defaultDir; + let next; + const warnings = []; + if (type === 'plugin') { + const name = await ask(values.name, 'Plugin name', 'My Plugin'); + const options = normalizePluginOptions({ + name, + description: await ask(values.description, 'Description', `${name}, a wayBetter plugin.`), + author: await ask(values.author, 'Author', 'you'), + version: values['plugin-version'], + typescript: values.ts ?? values.typescript ?? (interactive ? await ui.confirm('TypeScript?', false) : false), + app: values.app ?? (interactive ? await ui.choose('Which app is it for? (x = wayBetter for X)', PLUGIN_APPS, 'x') : 'x'), + }); + files = pluginFiles(options); + defaultDir = options.id; + next = options.typescript + ? ['npm install', 'npm run build', `copy dist/${options.file} into wayBetter → Plugins → Open folder, then Rescan`] + : [`copy ${options.file} into wayBetter → Plugins → Open folder, then Rescan`]; + } else if (type === 'theme') { + const name = await ask(values.name, 'Theme name', 'My Theme'); + const preset = await ask(values.preset, `Start from (${Object.keys(THEME_PRESETS).join(', ')})`, 'midnight'); + const seed = THEME_PRESETS[/** @type {keyof typeof THEME_PRESETS} */ (preset)] ?? THEME_PRESETS.midnight; + const options = normalizeThemeOptions({ + name, + preset, + author: await ask(values.author, 'Author', 'you'), + description: values.description, + mode: values.mode, + bg: await ask(values.bg, 'Background color', seed.bg), + text: await ask(values.text, 'Text color', seed.text), + accent: await ask(values.accent, 'Accent color', seed.accent), + font: values.font, + postFont: values['post-font'], + radius: values.radius, + schema: values.schema, + }); + warnings.push(...options.warnings); + files = themeFiles(options); + defaultDir = options.id; + next = [`import ${options.id}.theme.json in wayBetter → Appearance → Import`]; + } else { + const site = await ask(values.site, `Site (${Object.keys(SITE_PRESETS).join(', ')} or any host)`, 'kick.com'); + const label = SITE_PRESETS[/** @type {keyof typeof SITE_PRESETS} */ (site.replace(/^www\./, ''))]?.label; + const options = normalizeAppOptions({ + site, + name: await ask(values.name, 'App name', label ? `wayBetter for ${label}` : undefined), + global: values.global, + identifier: values.identifier, + hostSource: values['host-source'], + hostPath: values['host-path'], + gitUrl: values['git-url'], + }); + files = appFiles(options); + defaultDir = options.slug; + next = [ + ...(options.hostSource === 'submodule' ? [`git init && git submodule add ${options.gitUrl} waybetter`] : []), + 'npm install', 'npm run build', 'npm run tauri dev', + 'then replace the PLACEHOLDER selectors in src/site.ts and src-tauri/src/site.rs', + ]; + } + + const dirArg = positionals[0] ?? (interactive ? await ui.ask('Directory', defaultDir) : defaultDir); + const target = resolve(io.cwd, dirArg || defaultDir || slugify(type)); + if (values['dry-run']) { + io.stdout.write(`Would write ${files.length} files to ${target}:\n`); + for (const file of files) io.stdout.write(` ${file.path}\n`); + return 0; + } + if (existsSync(target) && readdirSync(target).length > 0 && !values.force) { + throw new UsageError(`${target} is not empty. Pick another directory or pass --force.`); + } + for (const file of files) { + const path = join(target, file.path); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, file.content); + } + const shown = relative(io.cwd, target) || '.'; + io.stdout.write(`\nCreated a wayBetter ${type} in ${shown} (${files.length} files).\n`); + for (const warning of warnings) io.stdout.write(` note: ${warning}\n`); + io.stdout.write(`\nNext:\n${shown === '.' ? '' : ` cd ${shown}\n`}${next.map(step => ` ${step}\n`).join('')}`); + return 0; + } catch (error) { + if (error instanceof UsageError) { + io.stderr.write(`${error.message}\n`); + return 1; + } + throw error; + } finally { + ui.close(); + } +} diff --git a/packages/create-waybetter/src/names.js b/packages/create-waybetter/src/names.js new file mode 100644 index 0000000..70c99c5 --- /dev/null +++ b/packages/create-waybetter/src/names.js @@ -0,0 +1,73 @@ +// Names and small validators shared by the generators. Pure; no I/O. + +/** A usage error: shown to the user as-is, exit code 1, no stack. */ +export class UsageError extends Error {} + +/** `Hide Trends!` -> `hide-trends` (ASCII letters and digits, dashes between). */ +export function slugify(value, max = 64) { + return String(value) + .normalize('NFKD') + .replace(/\p{M}/gu, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, max) + .replace(/-+$/, ''); +} + +/** `hide trends 2` -> `HideTrends2`; always a valid JS/Rust type identifier. */ +export function pascalCase(value) { + const words = String(value).normalize('NFKD').replace(/\p{M}/gu, '').replace(/[^A-Za-z0-9]+/g, ' ').trim().split(/\s+/).filter(Boolean); + const name = words.map(word => word[0].toUpperCase() + word.slice(1)).join(''); + return /^[A-Za-z]/.test(name) ? name : `Plugin${name}`; +} + +/** `wayBetter for Kick` -> `wayBetterForKick` (camelCase, for `data-*` keys). */ +export function camelCase(value) { + const name = pascalCase(value); + return name[0].toLowerCase() + name.slice(1); +} + +/** + * A value for a `@name` / `@description` / ... plugin header line, or a theme string. The plugin + * store reads each header line up to its end, drops control characters and keeps 300 characters + * (waybetter-host `plugins::parse_meta`), so values are one line and cannot end the comment. + */ +export function headerValue(label, value, { max = 300, required = false } = {}) { + const text = String(value ?? '').trim(); + if (required && !text) throw new UsageError(`${label} is required.`); + if (/[\u0000-\u001f\u007f]/.test(text)) throw new UsageError(`${label} must be one line of text.`); + if (text.includes('*/')) throw new UsageError(`${label} cannot contain "*/".`); + if (text.length > max) throw new UsageError(`${label} is longer than ${max} characters.`); + return text; +} + +/** Semver-ish plugin version (`1.0.0`, `0.3.1-beta.2`). */ +export function versionValue(value) { + const text = String(value ?? '1.0.0').trim() || '1.0.0'; + if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(text)) throw new UsageError(`Version "${text}" is not like 1.0.0.`); + return text; +} + +export const HEX = /^#[0-9a-fA-F]{6}$/; + +/** `#abc` / `abc123` / `#ABC123` -> `#aabbcc` style lowercase six-digit hex. */ +export function hexValue(label, value) { + let text = String(value ?? '').trim().toLowerCase(); + if (!text.startsWith('#')) text = `#${text}`; + const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(text); + if (short) text = `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`; + if (!HEX.test(text)) throw new UsageError(`${label} must be a hex color like #1d9bf0 (got "${value}").`); + return text; +} + +/** A JS/TS string literal. */ +export const str = value => JSON.stringify(String(value)); + +/** A Rust string literal (JSON escapes are valid Rust escapes for the characters we allow). */ +export function rustStr(value) { + return JSON.stringify(String(value)).replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => `\\u{${hex}}`); +} + +/** Joins lines with `\n` and ends the file with one newline. */ +export const lines = (...parts) => `${parts.flat().join('\n').replace(/\n+$/, '')}\n`; diff --git a/packages/create-waybetter/src/plugin.js b/packages/create-waybetter/src/plugin.js new file mode 100644 index 0000000..8c4f643 --- /dev/null +++ b/packages/create-waybetter/src/plugin.js @@ -0,0 +1,426 @@ +// `npm create waybetter -- plugin`: one BetterDiscord-style `*.plugin.js` file (a class with +// start/stop and the header the plugin store reads), optionally as a small TypeScript project +// whose build writes that file. The example uses the real plugin API: `api.scope()`, storage, +// observe, onKey, the UI kit (`scope.ui`: toast with an action, a settings dialog built with +// `ui.h`) and the theme API (`api.theme`, `--wb-*` CSS variables). + +import { UsageError, headerValue, lines, pascalCase, slugify, str, versionValue } from './names.js'; + +/** Which app the plugin targets: wayBetter for X adds post/account readers to the core API. */ +export const PLUGIN_APPS = ['x', 'any']; + +/** + * @typedef {{ name: string, description?: string, author?: string, version?: string, + * typescript?: boolean, app?: string }} PluginInput + * @typedef {{ name: string, description: string, author: string, version: string, + * typescript: boolean, app: 'x' | 'any', id: string, className: string, file: string }} PluginOptions + * @typedef {{ path: string, content: string | Uint8Array }} OutputFile + */ + +/** @param {PluginInput} input @returns {PluginOptions} */ +export function normalizePluginOptions(input) { + const name = headerValue('Plugin name', input.name, { max: 60, required: true }); + const id = slugify(name, 48); + if (!id) throw new UsageError(`Plugin name "${name}" needs at least one letter or digit.`); + const app = String(input.app ?? 'x'); + if (!PLUGIN_APPS.includes(app)) throw new UsageError(`--app must be one of: ${PLUGIN_APPS.join(', ')}.`); + return { + name, + description: headerValue('Description', input.description || `${name}, a wayBetter plugin.`, { max: 200 }), + author: headerValue('Author', input.author || 'you', { max: 60 }), + version: versionValue(input.version), + typescript: Boolean(input.typescript), + app: /** @type {'x' | 'any'} */ (app), + id, + className: pascalCase(name), + // A bare `name.plugin.js`: letters, digits, `-` only (waybetter-host `valid_file_name`). + file: `${id}.plugin.js`, + }; +} + +/** @param {PluginOptions} o */ +function header(o) { + return lines( + '/**', + ` * @name ${o.name}`, + ` * @description ${o.description}`, + ` * @version ${o.version}`, + ` * @author ${o.author}`, + ' */', + ); +} + +/** The item a badge is added to, and how its text is read. @param {PluginOptions} o */ +function itemParts(o) { + if (o.app === 'x') { + return { + selector: `'article[data-testid="tweet"]'`, + selectorNote: '// One post on X.', + text: 'this.api.tweet(item)?.text ?? \'\'', + anchor: `item.querySelector('[data-testid="User-Name"]') ?? item`, + }; + } + return { + selector: `'[data-example-item]'`, + selectorNote: '// PLACEHOLDER: a selector for one item of your app\'s site (a post, a message, a video).', + text: `item.textContent ?? ''`, + anchor: 'item', + }; +} + +/** @param {PluginOptions} o */ +function jsSource(o) { + const item = itemParts(o); + return lines( + header(o).trimEnd(), + '// Made with `npm create waybetter`. The API is documented in PLUGINS.md (wayBetter for X:', + '// docs/PLUGINS.md) and in the waybetter package README (plugin UI kit, themes).', + '', + `const ID = ${str(o.id)}; // storage namespace and CSS id`, + `const ITEM = ${item.selector}; ${item.selectorNote}`, + '', + `module.exports = class ${o.className} {`, + ' start() {', + ' const api = window.wayBetter.api;', + ' this.api = api;', + ' // A scope collects everything the plugin adds; stop() undoes it all with scope.dispose().', + ' this.scope = api.scope();', + ' this.store = api.storage(ID);', + ' this.settings = { badges: true, ...this.store.get(\'settings\', {}) };', + '', + ' // Plugin CSS follows the active theme through the --wb-* variables.', + ' this.scope.css(ID, `', + ' .${ID}-badge { margin-inline-start: 8px; padding: 1px 8px; border: 1px solid var(--wb-border);', + ' border-radius: var(--wb-button-radius); background: var(--wb-surface); color: var(--wb-muted);', + ' font: 500 12px/18px var(--wb-font); white-space: nowrap; }', + ' html[data-${ID}-off] .${ID}-badge { display: none; }', + ' `);', + ' this.apply();', + ' this.scope.defer(() => document.documentElement.removeAttribute(`data-${ID}-off`));', + '', + ' // Once for every matching element, now and as the page renders more (batched per frame).', + ' this.scope.observe(ITEM, item => this.decorate(item));', + '', + ' // A single-key shortcut, skipped while typing: Shift+W opens the settings.', + ' this.scope.onKey(event => { if (event.key === \'W\') this.openSettings(); });', + '', + ' if (!this.store.get(\'welcomed\', false)) {', + ' this.store.set(\'welcomed\', true);', + ` this.scope.ui.toast(${str(`${o.name} is on`)}, { tone: 'success', action: { label: 'Settings', onClick: () => this.openSettings() } });`, + ' }', + ' }', + '', + ' decorate(item) {', + ` const text = ${item.text};`, + ' const words = text.trim() ? text.trim().split(/\\s+/).length : 0;', + ' // scope.add: removed again on dispose.', + ' const badge = this.scope.add(document.createElement(\'span\'));', + ' badge.className = `${ID}-badge`;', + ' badge.textContent = `${words} ${words === 1 ? \'word\' : \'words\'}`;', + ` ${item.anchor}.append(badge);`, + ' }', + '', + ' apply() {', + ' document.documentElement.toggleAttribute(`data-${ID}-off`, !this.settings.badges);', + ' }', + '', + ' openSettings() {', + ' const ui = this.scope.ui; // scoped: the dialog closes if the plugin stops', + ' const h = ui.h; // safe element builder: strings become text, on* functions listeners', + ' const theme = this.api.theme.current();', + ' const badges = h(\'input\', { type: \'checkbox\', checked: this.settings.badges });', + ' ui.dialog({', + ` title: ${str(o.name)},`, + ' message: `Drawn in the active theme: ${theme.name || theme.id}, ${theme.mode}.`,', + ' content: body => body.append(', + ' h(\'label\', { class: \'wb-check\' }, badges, h(\'span\', null, \'Show word counts\', h(\'small\', null, \'A small badge on each item.\'))),', + ' ),', + ' actions: [', + ' { label: \'Cancel\' },', + ' { label: \'Save\', tone: \'primary\', default: true, onClick: handle => {', + ' const next = { ...this.settings, badges: badges.checked };', + ' if (!this.store.set(\'settings\', next)) {', + ' handle.setError(\'Could not save.\');', + ' return false; // keeps the dialog open', + ' }', + ' this.settings = next;', + ' this.apply();', + ' ui.toast(\'Saved\', { tone: \'success\' });', + ' } },', + ' ],', + ' });', + ' }', + '', + ' stop() {', + ' this.scope?.dispose();', + ' this.scope = null;', + ' }', + '};', + ); +} + +/** @param {PluginOptions} o */ +function tsSource(o) { + const item = itemParts(o); + return lines( + header(o).trimEnd(), + '// Made with `npm create waybetter`. `npm run build` writes dist/' + o.file + ' (header first).', + '', + "import type { PluginScope, PluginStorage } from 'waybetter/runtime/pluginApi';", + "import type { PluginApi } from './waybetter-env';", + '', + `const ID = ${str(o.id)}; // storage namespace and CSS id`, + `const ITEM = ${item.selector}; ${item.selectorNote}`, + '', + 'type Settings = { badges: boolean };', + '', + `export default class ${o.className} {`, + ' private api!: PluginApi;', + ' private scope: PluginScope | null = null;', + ' private store!: PluginStorage;', + ' private settings: Settings = { badges: true };', + '', + ' start(): void {', + ' const api = window.wayBetter.api;', + ' this.api = api;', + ' // A scope collects everything the plugin adds; stop() undoes it all with scope.dispose().', + ' const scope = this.scope = api.scope();', + ' this.store = api.storage(ID);', + ' this.settings = { badges: true, ...this.store.get>(\'settings\', {}) };', + '', + ' // Plugin CSS follows the active theme through the --wb-* variables.', + ' scope.css(ID, `', + ' .${ID}-badge { margin-inline-start: 8px; padding: 1px 8px; border: 1px solid var(--wb-border);', + ' border-radius: var(--wb-button-radius); background: var(--wb-surface); color: var(--wb-muted);', + ' font: 500 12px/18px var(--wb-font); white-space: nowrap; }', + ' html[data-${ID}-off] .${ID}-badge { display: none; }', + ' `);', + ' this.apply();', + ' scope.defer(() => document.documentElement.removeAttribute(`data-${ID}-off`));', + '', + ' // Once for every matching element, now and as the page renders more (batched per frame).', + ' scope.observe(ITEM, item => this.decorate(scope, item));', + '', + ' // A single-key shortcut, skipped while typing: Shift+W opens the settings.', + ' scope.onKey(event => { if (event.key === \'W\') this.openSettings(); });', + '', + ' if (!this.store.get(\'welcomed\', false)) {', + ' this.store.set(\'welcomed\', true);', + ` scope.ui.toast(${str(`${o.name} is on`)}, { tone: 'success', action: { label: 'Settings', onClick: () => this.openSettings() } });`, + ' }', + ' }', + '', + ' private decorate(scope: PluginScope, item: Element): void {', + ` const text = ${item.text};`, + ' const words = text.trim() ? text.trim().split(/\\s+/).length : 0;', + ' // scope.add: removed again on dispose.', + ' const badge = scope.add(document.createElement(\'span\'));', + ' badge.className = `${ID}-badge`;', + ' badge.textContent = `${words} ${words === 1 ? \'word\' : \'words\'}`;', + ` ${item.anchor}.append(badge);`, + ' }', + '', + ' private apply(): void {', + ' document.documentElement.toggleAttribute(`data-${ID}-off`, !this.settings.badges);', + ' }', + '', + ' private openSettings(): void {', + ' if (!this.scope) return;', + ' const ui = this.scope.ui; // scoped: the dialog closes if the plugin stops', + ' const h = ui.h; // safe element builder: strings become text, on* functions listeners', + ' const theme = this.api.theme.current();', + ' const badges = h(\'input\', { type: \'checkbox\', checked: this.settings.badges }) as HTMLInputElement;', + ' ui.dialog({', + ` title: ${str(o.name)},`, + ' message: `Drawn in the active theme: ${theme.name || theme.id}, ${theme.mode}.`,', + ' content: body => body.append(', + ' h(\'label\', { class: \'wb-check\' }, badges, h(\'span\', null, \'Show word counts\', h(\'small\', null, \'A small badge on each item.\'))),', + ' ),', + ' actions: [', + ' { label: \'Cancel\' },', + ' { label: \'Save\', tone: \'primary\', default: true, onClick: handle => {', + ' const next: Settings = { ...this.settings, badges: badges.checked };', + ' if (!this.store.set(\'settings\', next)) {', + ' handle.setError(\'Could not save.\');', + ' return false; // keeps the dialog open', + ' }', + ' this.settings = next;', + ' this.apply();', + ' ui.toast(\'Saved\', { tone: \'success\' });', + ' return true;', + ' } },', + ' ],', + ' });', + ' }', + '', + ' stop(): void {', + ' this.scope?.dispose();', + ' this.scope = null;', + ' }', + '}', + ); +} + +/** Types of `window.wayBetter` for the TypeScript project. @param {PluginOptions} o */ +function envTypes(o) { + const x = o.app === 'x'; + return lines( + '// `window.wayBetter`: the page runtime plugins run against. The core API and its types come', + '// from the `waybetter` package; an app adds its own readers on top (wayBetter for X: posts,', + '// the signed-in account and users, see docs/PLUGINS.md).', + "import type { CorePluginApi } from 'waybetter/runtime/pluginApi';", + x ? "import type { SeenAccount } from 'waybetter/runtime/accountReport';" : '', + '', + x ? lines( + '/** A rendered post, read by `api.tweet(element)`. */', + 'export type TweetInfo = {', + ' id: string;', + ' url: string;', + ' handle: string;', + ' name: string;', + ' /** Emoji as characters, t.co links as the destination X shows. */', + ' text: string;', + ' /** ISO timestamp of the post\'s `