create-waybetter: the app skeleton runs on run_app, testkit, waybetter/build and waybetter release

The generated desktop.rs is config + SiteHooks + its own commands; build.rs uses
commands::manifest; capability files grant the host's commands; tests/security.rs uses testkit;
scripts/build.mjs uses buildRuntime; waybetter.release.json and release scripts (placeholder URLs).
A test keeps HOST_COMMANDS in step with commands.rs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
CRTkafa 2026-09-29 11:51:25 +07:00
parent dfbed5b318
commit d97aba5048
2 changed files with 178 additions and 147 deletions

View file

@ -131,12 +131,22 @@ export function normalizeAppOptions(input) {
/** Where `npm run build` writes what native code and Tauri load (tests check these exist). */ /** 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' }; export const APP_OUTPUTS = { runtime: 'src-tauri/runtime/runtime.js', shell: 'dist/index.html' };
/** The native commands and who may call them (build.rs manifest and capability files). */ /** The app's own native commands and who may call them (build.rs manifest and capability files). */
const COMMANDS = { const COMMANDS = {
shell: ['tabs_sync', 'plugins_list', 'plugin_set_enabled', 'plugins_open_folder'], shell: ['plugins_list', 'plugin_set_enabled', 'plugins_open_folder'],
tab: ['tab_report'], tab: ['tab_report'],
site: ['site_ready'], 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, '-')}`; const permission = command => `allow-${command.replace(/_/g, '-')}`;
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
@ -246,14 +256,17 @@ function cargoToml(o) {
'# `desktop` is the Tauri app; without it (`--no-default-features`) the site adapter and plugin', '# `desktop` is the Tauri app; without it (`--no-default-features`) the site adapter and plugin',
'# host build and test headless.', '# host build and test headless.',
'default = ["desktop"]', 'default = ["desktop"]',
'desktop = ["dep:tauri", "dep:tauri-build", "waybetter-host/tauri"]', '# `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]', '[build-dependencies]',
'tauri-build = { version = "2", features = [], optional = true }', 'tauri-build = { version = "2", features = [], optional = true }',
'# The host\'s command list for the app-command manifest (`waybetter_host::commands::manifest`).',
hostDependency(o),
'', '',
'[dependencies]', '[dependencies]',
'# The wayBetter framework: security policy, profiles, plugin store, tab payloads and, with', '# The wayBetter framework: security policy, profiles, plugin store, tab payloads and, with',
'# the desktop feature, its Tauri glue.', '# the desktop feature, the app itself (`waybetter_host::app`).',
hostDependency(o), hostDependency(o),
'tauri = { version = "2", features = ["unstable"], optional = true }', 'tauri = { version = "2", features = ["unstable"], optional = true }',
'serde = { version = "1", features = ["derive"] }', 'serde = { version = "1", features = ["derive"] }',
@ -267,10 +280,11 @@ function buildRs() {
return lines( return lines(
'fn main() {', 'fn main() {',
' // The app-command manifest: tauri-build generates an `allow-<command>` permission for each,', ' // The app-command manifest: tauri-build generates an `allow-<command>` permission for each,',
' // which the capability files grant per webview label.', ' // 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")]', ' #[cfg(feature = "desktop")]',
' tauri_build::try_build(tauri_build::Attributes::new().app_manifest(', ' tauri_build::try_build(tauri_build::Attributes::new().app_manifest(',
` tauri_build::AppManifest::new().commands(&[${all.map(c => `"${c}"`).join(', ')}]),`, ` tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&[${all.map(c => `"${c}"`).join(', ')}])),`,
' ))', ' ))',
' .expect("Tauri build configuration must be valid");', ' .expect("Tauri build configuration must be valid");',
'}', '}',
@ -410,21 +424,24 @@ function mainRs(o) {
/** @param {AppOptions} o */ /** @param {AppOptions} o */
function desktopRs(o) { function desktopRs(o) {
return lines( return lines(
'//! The native window: the trusted local `shell` webview fills it, and each tab is a native', '//! The app on the wayBetter host: `waybetter_host::app` makes the window, the trusted local',
'//! child webview placed over the pane rectangle the shell reports (`tabs_sync`). Every', '//! `shell` webview filling it and one native child webview per tab (placed over the pane',
'//! command re-checks its caller: the capability files are not the boundary.', '//! 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 crate::{plugins, site::SITE};',
'use serde::{Deserialize, Serialize};', 'use serde::{Deserialize, Serialize};',
'use std::collections::HashSet;',
'use std::sync::{Mutex, MutexGuard};', 'use std::sync::{Mutex, MutexGuard};',
'use tauri::webview::{NewWindowResponse, PageLoadEvent};', 'use tauri::{AppHandle, Manager, State, Webview};',
'use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, State, Webview, WebviewBuilder, WebviewUrl};', 'use url::Url;',
'use waybetter_host::app::{App, AppConfig, NewTab, SiteHooks};',
'use waybetter_host::bridge::{self, BridgeOptions};', 'use waybetter_host::bridge::{self, BridgeOptions};',
'use waybetter_host::host;',
'use waybetter_host::plugins::{PluginStore, ScriptPlugin};', 'use waybetter_host::plugins::{PluginStore, ScriptPlugin};',
'use waybetter_host::profiles::Account;', 'use waybetter_host::profiles::Account;',
'use waybetter_host::tabs::{parse_web_url, TabLayout, TabState};', 'use waybetter_host::tabs::TabState;',
'use waybetter_host::{host, policy};',
'', '',
'/// The page runtime (src/runtime/main.ts), written by `npm run build`.', '/// The page runtime (src/runtime/main.ts), written by `npm run build`.',
'const RUNTIME: &str = include_str!("../runtime/runtime.js");', 'const RUNTIME: &str = include_str!("../runtime/runtime.js");',
@ -440,49 +457,6 @@ function desktopRs(o) {
'// ---------------------------------------------------------------------------------------------', '// ---------------------------------------------------------------------------------------------',
'// Shell-only commands', '// Shell-only commands',
'', '',
'/// Reconciles tab webviews with the shell\'s panes: creates missing ones, places and shows or',
'/// hides all of them, and closes webviews whose tab is gone.',
'#[tauri::command]',
'async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>) -> Result<(), String> {',
' host::shell_only(&webview)?;',
' let window = webview.window();',
' let scale = window.scale_factor().map_err(|error| format!("TAB: {error}"))?;',
' let size = window.inner_size().map_err(|error| format!("TAB: {error}"))?.to_logical::<f64>(scale);',
' let maximized = window.is_maximized().unwrap_or(false);',
' let frameless = !window.is_decorated().unwrap_or(true);',
' let mut keep = HashSet::new();',
' for item in items {',
' if !policy::valid_tab_id(&item.id) {',
' return Err("VALIDATION: invalid tab id".into());',
' }',
' // One account profile in this skeleton; see waybetter-host `profiles` to add more.',
' if item.profile != waybetter_host::profiles::DEFAULT_PROFILE {',
' return Err("VALIDATION: unknown profile".into());',
' }',
' keep.insert(item.id.clone());',
' let rect = policy::clamp_tab_rect(item.x, item.y, item.width, item.height, size.width, size.height, maximized, frameless)?;',
' 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 tab = match host::tab_webview(&app, &item.id) {',
' Some(tab) => tab,',
' None => {',
' let url = parse_web_url(&item.url)?;',
' window',
' .add_child(tab_builder(&app, &item.id, url), LogicalPosition::new(x, y), LogicalSize::new(width, height))',
' .map_err(|error| format!("TAB: {error}"))?',
' }',
' };',
' host::place_child(&tab, x, y, width, height);',
' host::set_tab_visible(&tab, visible, item.parked || rect.is_none());',
' }',
' for existing in window.webviews() {',
' if policy::tab_id(existing.label()).is_some_and(|id| !keep.contains(id)) {',
' let _ = existing.close();',
' }',
' }',
' Ok(())',
'}',
'',
'#[tauri::command]', '#[tauri::command]',
'async fn plugins_list(webview: Webview, state: State<\'_, AppState>) -> Result<Vec<ScriptPlugin>, String> {', 'async fn plugins_list(webview: Webview, state: State<\'_, AppState>) -> Result<Vec<ScriptPlugin>, String> {',
' host::shell_only(&webview)?;', ' host::shell_only(&webview)?;',
@ -584,76 +558,99 @@ function desktopRs(o) {
'}', '}',
'', '',
'// ---------------------------------------------------------------------------------------------', '// ---------------------------------------------------------------------------------------------',
'// Tab webviews', '// The site on the wayBetter host',
'', '',
'fn tab_builder(app: &AppHandle, id: &str, url: url::Url) -> WebviewBuilder<tauri::Wry> {', '/// What only this app knows about its tabs (see `waybetter_host::app::SiteHooks` for the rest:',
' let (load_app, load_id) = (app.clone(), id.to_owned());', '/// legacy domains, link routing, per-tab state, ...).',
' let (title_app, title_id) = (app.clone(), id.to_owned());', 'struct Site;',
' WebviewBuilder::new(policy::tab_label(id), WebviewUrl::External(url))', '',
' // The framework tab bridge: reports each tab\'s URL and title to the address bar; it', 'impl SiteHooks for Site {',
' // may call only `tab_report` (shortcut and link-drag forwarding are off: this shell', ' fn init_scripts(&self, _app: &AppHandle, _tab: &NewTab) -> Vec<String> {',
' // does not handle them yet).', ' vec![',
' .initialization_script(bridge::script(BridgeOptions::REPORT_ONLY))', ' // The framework tab bridge: reports each tab\'s URL and title to the address bar; it',
' // The runtime checks the origin itself and stays inert on other sites.', ' // may call only `tab_report` (shortcut and link-drag forwarding are off: this shell',
' .initialization_script(RUNTIME)', ' // does not handle them yet).',
' // Pop-ups are refused in this skeleton; open them as tabs with `tabs::OpenRequest`.', ' bridge::script(BridgeOptions::REPORT_ONLY),',
' .on_new_window(|_, _| NewWindowResponse::Deny)', ' // The runtime checks the origin itself and stays inert on other sites.',
' .on_page_load(move |tab, payload| {', ' RUNTIME.to_owned(),',
' let finished = matches!(payload.event(), PageLoadEvent::Finished);', ' ]',
' host::emit_tab_state(', ' }',
' &load_app,', '',
' TabState { id: load_id.clone(), url: Some(payload.url().to_string()), loading: Some(!finished), ..Default::default() },', ' /// 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) {',
' // Enabled plugins and custom CSS, evaluated natively (the page\'s CSP cannot block them).', ' let scripts = app',
' if finished && SITE.is_origin(payload.url()) {', ' .state::<AppState>()',
' let scripts = load_app', ' .plugins',
' .state::<AppState>()', ' .lock()',
' .plugins', ' .map(|store| {',
' .lock()', ' let mut scripts: Vec<String> = waybetter_host::plugins::css_script(&plugins::HOST, &store.css()).into_iter().collect();',
' .map(|store| {', ' scripts.extend(store.start_scripts());',
' let mut scripts: Vec<String> = waybetter_host::plugins::css_script(&plugins::HOST, &store.css()).into_iter().collect();', ' scripts',
' scripts.extend(store.start_scripts());', ' })',
' scripts', ' .unwrap_or_default();',
' })', ' for script in scripts {',
' .unwrap_or_default();', ' let _ = tab.eval(&script);',
' for script in scripts {', ' }',
' let _ = tab.eval(&script);', ' }',
' }',
' }',
' })',
' .on_document_title_changed(move |_, title| {',
' host::emit_tab_state(&title_app, TabState { id: title_id.clone(), title: Some(title), ..Default::default() });',
' })',
'}', '}',
'', '',
'// ---------------------------------------------------------------------------------------------', '// ---------------------------------------------------------------------------------------------',
'// App', '// App',
'', '',
'pub fn run() {', 'pub fn run() {',
' tauri::Builder::default()', ' let config = AppConfig {',
' window_size: (1280.0, 820.0),',
' min_window_size: (720.0, 480.0),',
' // This shell draws no titlebar of its own: keep the OS frame.',
' custom_titlebar: false,',
' ..AppConfig::new(&SITE, SITE.product)',
' };',
' App::new(config, Site)',
' .setup(|app| {', ' .setup(|app| {',
' let store = plugins::store(app.path().app_data_dir()?.join("plugins"));', ' let store = plugins::store(app.path().app_data_dir()?.join("plugins"));',
' store.ensure()?;', ' store.ensure()?;',
' app.manage(AppState { plugins: Mutex::new(store) });', ' app.manage(AppState { plugins: Mutex::new(store) });',
'',
' let window = tauri::window::WindowBuilder::new(app, policy::MAIN_LABEL)',
' .title(SITE.product)',
' .inner_size(1280.0, 820.0)',
' .min_inner_size(720.0, 480.0)',
' .build()?;',
' let size = window.inner_size()?.to_logical::<f64>(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()',
' .on_navigation(|url| policy::local_navigation_allowed(url, cfg!(debug_assertions)))',
' .on_new_window(|_, _| NewWindowResponse::Deny);',
' let shell = window.add_child(shell, LogicalPosition::new(0.0, 0.0), LogicalSize::new(size.width, size.height))?;',
' host::attach_shell(&shell);',
' Ok(())', ' Ok(())',
' })', ' })',
` .invoke_handler(tauri::generate_handler![${[...COMMANDS.shell, ...COMMANDS.tab, ...COMMANDS.site].join(', ')}])`, ` .run(tauri::generate_context!(), tauri::generate_handler![${[...COMMANDS.shell, ...COMMANDS.tab, ...COMMANDS.site].join(', ')}]);`,
' .run(tauri::generate_context!())', '}',
` .expect(${rustStr(`failed to run ${o.product}`)});`, );
}
/** @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"]);',
'}', '}',
); );
} }
@ -672,7 +669,7 @@ function tauriConf(o) {
}, },
app: { app: {
withGlobalTauri: true, withGlobalTauri: true,
// The window is made in desktop.rs (a multiwebview window: shell + tab webviews). // The window is made by waybetter-host (`app::run_app`: a multiwebview window, shell + tab webviews).
windows: [], windows: [],
security: { security: {
capabilities: ['shell', 'tab-chrome', 'site-tab'], capabilities: ['shell', 'tab-chrome', 'site-tab'],
@ -695,21 +692,21 @@ function capabilities(o) {
path: 'src-tauri/capabilities/shell.json', path: 'src-tauri/capabilities/shell.json',
content: cap({ content: cap({
identifier: 'shell', identifier: 'shell',
description: 'The trusted local shell: tabs and plugins. No generic filesystem or shell APIs.', 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'], webviews: [/** policy::SHELL_LABEL */ 'shell'],
local: true, local: true,
permissions: ['core:event:default', ...COMMANDS.shell.map(permission)], permissions: ['core:event:default', ...HOST_COMMANDS.shell.map(permission), ...COMMANDS.shell.map(permission)],
}), }),
}, },
{ {
path: 'src-tauri/capabilities/tab-chrome.json', path: 'src-tauri/capabilities/tab-chrome.json',
content: cap({ content: cap({
identifier: 'tab-chrome', identifier: 'tab-chrome',
description: 'Every tab (any site): report its own URL, title and, on the site, its account. Nothing else.', 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-*'], webviews: ['tab-*'],
local: false, local: false,
remote: { urls: ['https://*/*', 'http://*/*'] }, remote: { urls: ['https://*/*', 'http://*/*'] },
permissions: COMMANDS.tab.map(permission), permissions: [...COMMANDS.tab.map(permission), ...HOST_COMMANDS.tab.map(permission)],
}), }),
}, },
{ {
@ -726,6 +723,21 @@ function capabilities(o) {
]; ];
} }
/** @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 // TypeScript: site adapter, page runtime, shell
@ -1064,26 +1076,20 @@ function examplePlugin(o) {
function buildMjs() { function buildMjs() {
return lines( return lines(
'// Builds the two bundles: the page runtime (one IIFE that native code injects into tabs) and the', '// Builds the two bundles: the page runtime (one IIFE that native code injects into tabs,',
'// shell (the local page Tauri serves from dist/).', '// bundled the way every wayBetter app ships it: `waybetter/build`) and the shell (the local page',
"import { build } from 'esbuild';", '// Tauri serves from dist/).',
"import { copyFileSync, mkdirSync } from 'node:fs';", "import { copyFileSync, mkdirSync } from 'node:fs';",
"import { buildRuntime } from 'waybetter/build';",
'', '',
"mkdirSync('dist', { recursive: true });", "mkdirSync('dist', { recursive: true });",
'await build({', `await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)} });`,
" entryPoints: ['src/runtime/main.ts'],", 'await buildRuntime({',
' bundle: true,', " entry: 'src/shell/main.ts',",
" format: 'iife',",
" target: 'es2022',",
` outfile: ${str(APP_OUTPUTS.runtime)},`,
" legalComments: 'none',",
'});',
'await build({',
" entryPoints: ['src/shell/main.ts'],",
' bundle: true,',
" format: 'esm',",
" target: 'es2022',",
" outfile: 'dist/shell.js',", " outfile: 'dist/shell.js',",
" format: 'esm',",
' minify: false,',
' inlineCss: false,',
'});', '});',
"copyFileSync('src/shell/index.html', 'dist/index.html');", "copyFileSync('src/shell/index.html', 'dist/index.html');",
"copyFileSync('src/shell/shell.css', 'dist/shell.css');", "copyFileSync('src/shell/shell.css', 'dist/shell.css');",
@ -1124,8 +1130,10 @@ function readme(o) {
'plugins/example.plugin.js written (disabled) into a new plugins folder', '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/site.rs SiteSpec: the native half (hosts, runtime global, account rules)',
'src-tauri/src/plugins.rs the plugin store (PluginHost)', 'src-tauri/src/plugins.rs the plugin store (PluginHost)',
'src-tauri/src/desktop.rs window, shell, tab webviews and the commands', '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/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', '## Make it yours',
@ -1134,14 +1142,16 @@ function readme(o) {
' and `src-tauri/src/site.rs` (selectors, handle rules, the avatar CDN).', ' 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`.', '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,', '3. Add site-only commands like `site_ready`: `host::site_tab_only(&SITE, &webview)?` first,',
' then list them in `build.rs` and `capabilities/site-tab.json`.', ' 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', '4. Next steps from the framework: account profiles (`waybetter_host::profiles`), split panes',
' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes', ' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes',
' (`waybetter/runtime/themeApi`, `theme.schema.json`), signed updates (`waybetter_host::update`).', ' (`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', '## Security model',
'', '',
'- Only the local `shell` webview may call shell commands (`host::shell_only`).', '- 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.', '- 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.', '- 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', '- Plugins are files the owner copies into the plugins folder; native code evaluates them only',
@ -1167,8 +1177,10 @@ export function appFiles(o) {
typecheck: 'tsc -p tsconfig.json', typecheck: 'tsc -p tsconfig.json',
tauri: 'tauri', tauri: 'tauri',
'test:rust': 'cargo test --manifest-path src-tauri/Cargo.toml --no-default-features', 'test:rust': 'cargo test --manifest-path src-tauri/Cargo.toml --no-default-features',
release: 'waybetter release windows',
'release:macos': 'waybetter release macos',
}, },
dependencies: { waybetter: '^0.2.0' }, dependencies: { waybetter: '^0.3.0' },
devDependencies: { '@tauri-apps/cli': '^2.0.0', esbuild: '^0.25.0', typescript: '^5.9.0' }, devDependencies: { '@tauri-apps/cli': '^2.0.0', esbuild: '^0.25.0', typescript: '^5.9.0' },
}; };
const tsconfig = { const tsconfig = {
@ -1191,7 +1203,8 @@ export function appFiles(o) {
{ path: 'README.md', content: readme(o) }, { path: 'README.md', content: readme(o) },
{ path: 'package.json', content: json(pkg) }, { path: 'package.json', content: json(pkg) },
{ path: 'tsconfig.json', content: json(tsconfig) }, { path: 'tsconfig.json', content: json(tsconfig) },
{ path: '.gitignore', content: lines('node_modules/', 'dist/', 'src-tauri/target/', 'src-tauri/gen/', APP_OUTPUTS.runtime) }, { 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: 'scripts/build.mjs', content: buildMjs() },
{ path: 'src/site.ts', content: siteTs(o) }, { path: 'src/site.ts', content: siteTs(o) },
{ path: 'src/address.ts', content: addressTs(o) }, { path: 'src/address.ts', content: addressTs(o) },
@ -1212,6 +1225,7 @@ export function appFiles(o) {
{ path: 'src-tauri/src/site.rs', content: siteRs(o) }, { path: 'src-tauri/src/site.rs', content: siteRs(o) },
{ path: 'src-tauri/src/plugins.rs', content: pluginsRs(o) }, { path: 'src-tauri/src/plugins.rs', content: pluginsRs(o) },
{ path: 'src-tauri/src/desktop.rs', content: desktopRs(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. // 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).') }, { path: APP_OUTPUTS.runtime, content: lines('// Placeholder: `npm run build` writes the page runtime here (src/runtime/main.ts).') },
]; ];

View file

@ -17,7 +17,8 @@ import { fileURLToPath } from 'node:url';
import vm from 'node:vm'; import vm from 'node:vm';
import { createCorePluginApi } from '../../runtime/src/pluginApi.ts'; import { createCorePluginApi } from '../../runtime/src/pluginApi.ts';
import { themeFromColors } from '../../runtime/src/themeApi.ts'; import { themeFromColors } from '../../runtime/src/themeApi.ts';
import { APP_OUTPUTS, SITE_PRESETS } from '../src/app.js'; import { APP_OUTPUTS, HOST_COMMANDS, SITE_PRESETS } from '../src/app.js';
import { normalizeReleaseConfig } from '../../waybetter/cli/release.mjs';
import { main } from '../src/cli.js'; import { main } from '../src/cli.js';
import { UsageError, headerValue, pascalCase, slugify } from '../src/names.js'; import { UsageError, headerValue, pascalCase, slugify } from '../src/names.js';
import { normalizeThemeOptions, THEME_PRESETS } from '../src/theme.js'; import { normalizeThemeOptions, THEME_PRESETS } from '../src/theme.js';
@ -300,14 +301,23 @@ test('app: every site skeleton is consistent across its native and page halves',
const tsHosts = /hosts: \[([^\]]*)\]/.exec(siteTs)[1]; const tsHosts = /hosts: \[([^\]]*)\]/.exec(siteTs)[1];
assert.equal(rsHosts, tsHosts); assert.equal(rsHosts, tsHosts);
assert.equal(/runtime_global: "([^"]+)"/.exec(siteRs)[1], /runtimeGlobal: "([^"]+)"/.exec(siteTs)[1]); assert.equal(/runtime_global: "([^"]+)"/.exec(siteRs)[1], /runtimeGlobal: "([^"]+)"/.exec(siteTs)[1]);
// Commands: build.rs manifest == generate_handler == capability permissions. // Commands: build.rs manifest == generate_handler; capability permissions == those + the host's.
const manifest = /commands\(&\[([^\]]*)\]\)/.exec(file('src-tauri', 'build.rs'))[1].match(/"([a-z_]+)"/g).map(c => c.slice(1, -1)).sort(); const manifest = /manifest\(&\[([^\]]*)\]\)/.exec(file('src-tauri', 'build.rs'))[1].match(/"([a-z_]+)"/g).map(c => c.slice(1, -1)).sort();
const handler = /generate_handler!\[([^\]]*)\]/.exec(file('src-tauri', 'src', 'desktop.rs'))[1].split(',').map(c => c.trim()).sort(); const handler = /generate_handler!\[([^\]]*)\]/.exec(file('src-tauri', 'src', 'desktop.rs'))[1].split(',').map(c => c.trim()).sort();
assert.deepEqual(handler, manifest); assert.deepEqual(handler, manifest);
const caps = ['shell', 'tab-chrome', 'site-tab'].map(name => JSON.parse(file('src-tauri', 'capabilities', `${name}.json`))); const caps = ['shell', 'tab-chrome', 'site-tab'].map(name => JSON.parse(file('src-tauri', 'capabilities', `${name}.json`)));
const granted = caps.flatMap(cap => cap.permissions).filter(p => p.startsWith('allow-')).map(p => p.slice(6).replace(/-/g, '_')).sort(); const granted = caps.flatMap(cap => cap.permissions).filter(p => p.startsWith('allow-')).map(p => p.slice(6).replace(/-/g, '_')).sort();
assert.deepEqual(granted, manifest); assert.deepEqual(granted, [...manifest, ...HOST_COMMANDS.shell, ...HOST_COMMANDS.tab].sort());
assert.deepEqual(caps[1].permissions, ['allow-tab-report'], 'any tab: only about itself'); assert.deepEqual(caps[1].permissions, ['allow-tab-report', 'allow-tab-shortcut', 'allow-tab-link-drag'], 'any tab: only about itself');
for (const command of HOST_COMMANDS.shell) assert.ok(caps[0].permissions.includes(`allow-${command.replace(/_/g, '-')}`), `the shell has ${command}`);
assert.match(file('src-tauri', 'tests', 'security.rs'), /assert_host_commands\(\)/);
// The release config is one `waybetter release` accepts.
const release = normalizeReleaseConfig(JSON.parse(file('waybetter.release.json')), join(work, dir));
assert.equal(release.tauriDir, join(work, dir, 'src-tauri'));
assert.match(release.artifact, /^[A-Za-z0-9._-]+$/);
// The runtime is bundled by the framework.
assert.match(file('scripts', 'build.mjs'), /from 'waybetter\/build'/);
assert.ok(EXPORTS.includes('./build'));
assert.deepEqual(caps[2].remote.urls, JSON.parse(`[${tsHosts}]`).map(host => `https://${host}/*`)); assert.deepEqual(caps[2].remote.urls, JSON.parse(`[${tsHosts}]`).map(host => `https://${host}/*`));
assert.equal(caps[0].local, true); assert.equal(caps[0].local, true);
assert.deepEqual(JSON.parse(file('src-tauri', 'tauri.conf.json')).app.security.capabilities.sort(), ['shell', 'site-tab', 'tab-chrome']); assert.deepEqual(JSON.parse(file('src-tauri', 'tauri.conf.json')).app.security.capabilities.sort(), ['shell', 'site-tab', 'tab-chrome']);
@ -327,6 +337,13 @@ test('app: every site skeleton is consistent across its native and page halves',
assert.match(read('app-youtube-com', 'src-tauri', 'Cargo.toml'), /waybetter-host = \{ path = ".*\/crates\/waybetter-host" \}/); assert.match(read('app-youtube-com', 'src-tauri', 'Cargo.toml'), /waybetter-host = \{ path = ".*\/crates\/waybetter-host" \}/);
}); });
test('app: the host command list matches waybetter-host (commands.rs)', () => {
const source = readFileSync(join(HOST_CRATE, 'src', 'commands.rs'), 'utf8');
const list = name => new RegExp(`pub const ${name}: &\\[&str\\] = &\\[([^\\]]*)\\]`).exec(source)[1].match(/"([a-z0-9_]+)"/g).map(c => c.slice(1, -1));
assert.deepEqual(HOST_COMMANDS.shell, list('SHELL'));
assert.deepEqual(HOST_COMMANDS.tab, list('TAB'));
});
test('app: host crate sources (submodule default, git)', async () => { test('app: host crate sources (submodule default, git)', async () => {
assert.equal((await create('app', 'app-sub', '--site', 'twitch.tv', '--yes')).code, 0); assert.equal((await create('app', 'app-sub', '--site', 'twitch.tv', '--yes')).code, 0);
assert.match(read('app-sub', 'src-tauri', 'Cargo.toml'), /waybetter-host = \{ path = "\.\.\/waybetter\/crates\/waybetter-host" \}/); assert.match(read('app-sub', 'src-tauri', 'Cargo.toml'), /waybetter-host = \{ path = "\.\.\/waybetter\/crates\/waybetter-host" \}/);
@ -356,7 +373,7 @@ test('app: the Rust resolves against waybetter-host (cargo metadata)', { skip: !
assert.ok(app, 'the app crate'); assert.ok(app, 'the app crate');
const host = app.dependencies.find(dep => dep.name === 'waybetter-host'); const host = app.dependencies.find(dep => dep.name === 'waybetter-host');
assert.ok(host?.path, 'waybetter-host as a path dependency'); assert.ok(host?.path, 'waybetter-host as a path dependency');
assert.deepEqual(app.features.desktop.sort(), ['dep:tauri', 'dep:tauri-build', 'waybetter-host/tauri']); assert.deepEqual(app.features.desktop.sort(), ['dep:tauri', 'dep:tauri-build', 'waybetter-host/app']);
}); });
test('app: cargo check (desktop) and cargo test (headless) of the generated Rust', { skip: (!hasCargo && 'cargo not found') || (process.env.WAYBETTER_SKIP_CARGO_CHECK === '1' && 'WAYBETTER_SKIP_CARGO_CHECK=1') }, () => { test('app: cargo check (desktop) and cargo test (headless) of the generated Rust', { skip: (!hasCargo && 'cargo not found') || (process.env.WAYBETTER_SKIP_CARGO_CHECK === '1' && 'WAYBETTER_SKIP_CARGO_CHECK=1') }, () => {