Desktop app shell (apps/desktop): Tauri 2 + React 19 around the storebound sidecar
- Rust host: spawns storebound serve --stdio with fixed args, hands over a per-session secret, mints confirm tokens only after a native dialog showing the summary and the dry run - every app command re-checks window label and page origin; one capability (main window, app commands + event listen only, no plugin API in the webview); strict CSP; tests/security.rs pins it - store keys picked in native dialogs, kept in the OS keychain, passed per call in memory only - plugins: shell (Rust only), single-instance, deep-link storebound://, window-state, opener, dialog, notification, updater (placeholder endpoint and key until signing), process - app-centric UI: Portfolio, App (Releases, Catalog, Listings, Health, Reviews, TestFlight), App folders, Accounts, Dependencies, Settings; light / dark with the storebound.dev tokens, reduced motion, home folder shown as ~ - macOS menu: Cmd+Q quits, Edit menu, Window menu keeps the main window; Linux DMABUF fix - Bun workspace (npm files unchanged), ci runs desktop typecheck, build, cargo test and clippy; scrub covers home paths; docs/desktop.md (protocol, safety, dependency sources and licenses)
This commit is contained in:
parent
ab13d95898
commit
61a1e832a0
60 changed files with 9355 additions and 7 deletions
13
apps/desktop/index.html
Normal file
13
apps/desktop/index.html
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="color-scheme" content="light dark" />
|
||||||
|
<title>storebound</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
31
apps/desktop/package.json
Normal file
31
apps/desktop/package.json
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
{
|
||||||
|
"name": "@storebound/desktop",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"type": "module",
|
||||||
|
"description": "storebound desktop: every game's releases on both stores in one window (Tauri shell around the storebound CLI sidecar).",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite --host 127.0.0.1 --port 1420 --strictPort",
|
||||||
|
"build": "tsc --noEmit && vite build",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"test": "bun test tests",
|
||||||
|
"sidecar": "bun ../../tools/build-sidecars.ts --host",
|
||||||
|
"tauri": "tauri",
|
||||||
|
"app:dev": "bun run sidecar && tauri dev",
|
||||||
|
"app:build:debug": "bun run sidecar && tauri build --debug --no-bundle"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tauri-apps/api": "^2.12.0",
|
||||||
|
"react": "^19.2.0",
|
||||||
|
"react-dom": "^19.2.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tauri-apps/cli": "^2.12.1",
|
||||||
|
"@types/react": "^19.2.0",
|
||||||
|
"@types/react-dom": "^19.2.0",
|
||||||
|
"@vitejs/plugin-react": "^4.7.0",
|
||||||
|
"typescript": "5.9.3",
|
||||||
|
"vite": "^6.3.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
6173
apps/desktop/src-tauri/Cargo.lock
generated
Normal file
6173
apps/desktop/src-tauri/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
53
apps/desktop/src-tauri/Cargo.toml
Normal file
53
apps/desktop/src-tauri/Cargo.toml
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
[package]
|
||||||
|
name = "storebound-desktop"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "storebound desktop: every game's releases on both stores in one window"
|
||||||
|
license = "MIT"
|
||||||
|
edition = "2021"
|
||||||
|
rust-version = "1.85"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "storebound_desktop"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "storebound-desktop"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
tauri-build = { version = "2", features = [] }
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tauri = { version = "2.12", features = [] }
|
||||||
|
# Spawns the storebound sidecar from Rust only; no capability grants the plugin's JS API.
|
||||||
|
tauri-plugin-shell = "2"
|
||||||
|
tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
|
||||||
|
tauri-plugin-deep-link = "2"
|
||||||
|
tauri-plugin-window-state = "2"
|
||||||
|
# Opener, dialog, notification, updater and process are driven from Rust only (no JS permissions).
|
||||||
|
tauri-plugin-opener = "2"
|
||||||
|
tauri-plugin-dialog = "2"
|
||||||
|
tauri-plugin-notification = "2"
|
||||||
|
tauri-plugin-updater = "2"
|
||||||
|
tauri-plugin-process = "2"
|
||||||
|
# Store credentials: macOS Keychain, Windows Credential Manager, Secret Service on Linux.
|
||||||
|
keyring = { version = "3", features = ["apple-native", "windows-native", "sync-secret-service", "crypto-rust"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
hmac = "0.12"
|
||||||
|
sha2 = "0.10"
|
||||||
|
base64 = "0.22"
|
||||||
|
getrandom = "0.3"
|
||||||
|
url = "2"
|
||||||
|
tokio = { version = "1", features = ["sync", "time"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
codegen-units = 1
|
||||||
|
lto = true
|
||||||
|
opt-level = "s"
|
||||||
|
panic = "abort"
|
||||||
|
strip = true
|
||||||
11
apps/desktop/src-tauri/build.rs
Normal file
11
apps/desktop/src-tauri/build.rs
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
// App command manifest: every #[tauri::command] gets an `allow-<name>` permission, and a command no capability lists
|
||||||
|
// is denied. The list lives in src/commands_list.rs so tests/security.rs can compare it with the capability files.
|
||||||
|
include!("src/commands_list.rs");
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
tauri_build::try_build(
|
||||||
|
tauri_build::Attributes::new()
|
||||||
|
.app_manifest(tauri_build::AppManifest::new().commands(COMMANDS)),
|
||||||
|
)
|
||||||
|
.expect("tauri build script failed");
|
||||||
|
}
|
||||||
25
apps/desktop/src-tauri/capabilities/main.json
Normal file
25
apps/desktop/src-tauri/capabilities/main.json
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
{
|
||||||
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
|
"identifier": "main-window",
|
||||||
|
"description": "The main window with the app's own bundled pages only (no remote content). It may listen to app events (sidecar progress, deep links) and call the storebound app commands; every command re-checks the window label and page origin in Rust. No plugin API is granted to the webview: the sidecar is spawned from Rust with fixed arguments, dialogs, the opener, notifications, the updater and process control are driven from Rust only, and credentials never reach the page.",
|
||||||
|
"windows": ["main"],
|
||||||
|
"local": true,
|
||||||
|
"permissions": [
|
||||||
|
"core:event:allow-listen",
|
||||||
|
"core:event:allow-unlisten",
|
||||||
|
"allow-app-info",
|
||||||
|
"allow-sidecar-status",
|
||||||
|
"allow-sidecar-call",
|
||||||
|
"allow-write-with-confirm",
|
||||||
|
"allow-projects-list",
|
||||||
|
"allow-project-add",
|
||||||
|
"allow-project-remove",
|
||||||
|
"allow-project-set-accounts",
|
||||||
|
"allow-accounts-list",
|
||||||
|
"allow-account-add-play",
|
||||||
|
"allow-account-add-apple",
|
||||||
|
"allow-account-remove",
|
||||||
|
"allow-portfolio-status",
|
||||||
|
"allow-open-external"
|
||||||
|
]
|
||||||
|
}
|
||||||
BIN
apps/desktop/src-tauri/icons/128x128.png
Normal file
BIN
apps/desktop/src-tauri/icons/128x128.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.3 KiB |
BIN
apps/desktop/src-tauri/icons/128x128@2x.png
Normal file
BIN
apps/desktop/src-tauri/icons/128x128@2x.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
BIN
apps/desktop/src-tauri/icons/32x32.png
Normal file
BIN
apps/desktop/src-tauri/icons/32x32.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
BIN
apps/desktop/src-tauri/icons/icon.icns
Normal file
BIN
apps/desktop/src-tauri/icons/icon.icns
Normal file
Binary file not shown.
BIN
apps/desktop/src-tauri/icons/icon.ico
Normal file
BIN
apps/desktop/src-tauri/icons/icon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
BIN
apps/desktop/src-tauri/icons/icon.png
Normal file
BIN
apps/desktop/src-tauri/icons/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
1
apps/desktop/src-tauri/icons/icon.svg
Normal file
1
apps/desktop/src-tauri/icons/icon.svg
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#6366f1"/><stop offset="1" stop-color="#4338ca"/></linearGradient></defs><rect x="100" y="100" width="824" height="824" rx="185" fill="url(#g)"/><path d="M512 288v384M336 464 512 288l176 176M256 640v176h512V640" fill="none" stroke="#fff" stroke-width="88" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||||
|
After Width: | Height: | Size: 461 B |
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-account-add-apple"
|
||||||
|
description = "Enables the account_add_apple command without any pre-configured scope."
|
||||||
|
commands.allow = ["account_add_apple"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-account-add-apple"
|
||||||
|
description = "Denies the account_add_apple command without any pre-configured scope."
|
||||||
|
commands.deny = ["account_add_apple"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-account-add-play"
|
||||||
|
description = "Enables the account_add_play command without any pre-configured scope."
|
||||||
|
commands.allow = ["account_add_play"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-account-add-play"
|
||||||
|
description = "Denies the account_add_play command without any pre-configured scope."
|
||||||
|
commands.deny = ["account_add_play"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-account-remove"
|
||||||
|
description = "Enables the account_remove command without any pre-configured scope."
|
||||||
|
commands.allow = ["account_remove"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-account-remove"
|
||||||
|
description = "Denies the account_remove command without any pre-configured scope."
|
||||||
|
commands.deny = ["account_remove"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-accounts-list"
|
||||||
|
description = "Enables the accounts_list command without any pre-configured scope."
|
||||||
|
commands.allow = ["accounts_list"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-accounts-list"
|
||||||
|
description = "Denies the accounts_list command without any pre-configured scope."
|
||||||
|
commands.deny = ["accounts_list"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-app-info"
|
||||||
|
description = "Enables the app_info command without any pre-configured scope."
|
||||||
|
commands.allow = ["app_info"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-app-info"
|
||||||
|
description = "Denies the app_info command without any pre-configured scope."
|
||||||
|
commands.deny = ["app_info"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-open-external"
|
||||||
|
description = "Enables the open_external command without any pre-configured scope."
|
||||||
|
commands.allow = ["open_external"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-open-external"
|
||||||
|
description = "Denies the open_external command without any pre-configured scope."
|
||||||
|
commands.deny = ["open_external"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-portfolio-status"
|
||||||
|
description = "Enables the portfolio_status command without any pre-configured scope."
|
||||||
|
commands.allow = ["portfolio_status"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-portfolio-status"
|
||||||
|
description = "Denies the portfolio_status command without any pre-configured scope."
|
||||||
|
commands.deny = ["portfolio_status"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-project-add"
|
||||||
|
description = "Enables the project_add command without any pre-configured scope."
|
||||||
|
commands.allow = ["project_add"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-project-add"
|
||||||
|
description = "Denies the project_add command without any pre-configured scope."
|
||||||
|
commands.deny = ["project_add"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-project-remove"
|
||||||
|
description = "Enables the project_remove command without any pre-configured scope."
|
||||||
|
commands.allow = ["project_remove"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-project-remove"
|
||||||
|
description = "Denies the project_remove command without any pre-configured scope."
|
||||||
|
commands.deny = ["project_remove"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-project-set-accounts"
|
||||||
|
description = "Enables the project_set_accounts command without any pre-configured scope."
|
||||||
|
commands.allow = ["project_set_accounts"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-project-set-accounts"
|
||||||
|
description = "Denies the project_set_accounts command without any pre-configured scope."
|
||||||
|
commands.deny = ["project_set_accounts"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-projects-list"
|
||||||
|
description = "Enables the projects_list command without any pre-configured scope."
|
||||||
|
commands.allow = ["projects_list"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-projects-list"
|
||||||
|
description = "Denies the projects_list command without any pre-configured scope."
|
||||||
|
commands.deny = ["projects_list"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-sidecar-call"
|
||||||
|
description = "Enables the sidecar_call command without any pre-configured scope."
|
||||||
|
commands.allow = ["sidecar_call"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-sidecar-call"
|
||||||
|
description = "Denies the sidecar_call command without any pre-configured scope."
|
||||||
|
commands.deny = ["sidecar_call"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-sidecar-status"
|
||||||
|
description = "Enables the sidecar_status command without any pre-configured scope."
|
||||||
|
commands.allow = ["sidecar_status"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-sidecar-status"
|
||||||
|
description = "Denies the sidecar_status command without any pre-configured scope."
|
||||||
|
commands.deny = ["sidecar_status"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-write-with-confirm"
|
||||||
|
description = "Enables the write_with_confirm command without any pre-configured scope."
|
||||||
|
commands.allow = ["write_with_confirm"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-write-with-confirm"
|
||||||
|
description = "Denies the write_with_confirm command without any pre-configured scope."
|
||||||
|
commands.deny = ["write_with_confirm"]
|
||||||
134
apps/desktop/src-tauri/src/accounts.rs
Normal file
134
apps/desktop/src-tauri/src/accounts.rs
Normal file
|
|
@ -0,0 +1,134 @@
|
||||||
|
//! Store accounts. The secret part (Play service account JSON, App Store Connect .p8 key with its key id and issuer)
|
||||||
|
//! goes into the OS credential store under the service `dev.storebound.desktop`; only a label, the kind and the
|
||||||
|
//! creation time are kept in the app data folder. Secrets are never sent to the webview: they are read from the
|
||||||
|
//! keychain right before a sidecar call and handed to it in that call's params (memory only), which passes them to
|
||||||
|
//! the storebound command as environment variables.
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{Map, Value};
|
||||||
|
|
||||||
|
pub const KEYRING_SERVICE: &str = "dev.storebound.desktop";
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum AccountKind {
|
||||||
|
Play,
|
||||||
|
Apple,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the app keeps on disk and shows: no secret, no key id, no email.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Account {
|
||||||
|
pub id: String,
|
||||||
|
pub label: String,
|
||||||
|
pub kind: AccountKind,
|
||||||
|
pub created: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The keychain entry of one account (JSON).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||||
|
pub enum Secret {
|
||||||
|
Play { service_account: String },
|
||||||
|
Apple { key_id: String, issuer_id: String, p8: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Secret {
|
||||||
|
pub fn kind(&self) -> AccountKind {
|
||||||
|
match self {
|
||||||
|
Secret::Play { .. } => AccountKind::Play,
|
||||||
|
Secret::Apple { .. } => AccountKind::Apple,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The env names storebound reads (cli/lib/credentials.ts), as a sidecar `credentials` object.
|
||||||
|
pub fn to_credentials(&self, into: &mut Map<String, Value>) {
|
||||||
|
match self {
|
||||||
|
Secret::Play { service_account } => {
|
||||||
|
into.insert("PLAY_SERVICE_ACCOUNT".into(), Value::String(service_account.clone()));
|
||||||
|
}
|
||||||
|
Secret::Apple { key_id, issuer_id, p8 } => {
|
||||||
|
into.insert("ASC_KEY_ID".into(), Value::String(key_id.clone()));
|
||||||
|
into.insert("ASC_ISSUER_ID".into(), Value::String(issuer_id.clone()));
|
||||||
|
into.insert("ASC_P8".into(), Value::String(p8.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Google service account JSON key: client_email and a PEM private key.
|
||||||
|
pub fn check_service_account(text: &str) -> Result<String, String> {
|
||||||
|
let v: Value = serde_json::from_str(text).map_err(|_| "not a JSON file".to_string())?;
|
||||||
|
let email = v.get("client_email").and_then(Value::as_str).unwrap_or_default();
|
||||||
|
let key = v.get("private_key").and_then(Value::as_str).unwrap_or_default();
|
||||||
|
if email.is_empty() || !key.contains("PRIVATE KEY") {
|
||||||
|
return Err("not a Google service account key (client_email / private_key missing)".into());
|
||||||
|
}
|
||||||
|
// Store the compact form: no file path, nothing else from the disk.
|
||||||
|
serde_json::to_string(&v).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// App Store Connect key id: 10 upper-case letters or digits.
|
||||||
|
pub fn check_key_id(s: &str) -> Result<String, String> {
|
||||||
|
let s = s.trim();
|
||||||
|
if s.len() == 10 && s.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()) {
|
||||||
|
Ok(s.to_string())
|
||||||
|
} else {
|
||||||
|
Err("key id: 10 letters or digits, as shown in App Store Connect > Users and Access > Integrations".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// App Store Connect issuer id: a UUID.
|
||||||
|
pub fn check_issuer_id(s: &str) -> Result<String, String> {
|
||||||
|
let s = s.trim().to_ascii_lowercase();
|
||||||
|
let parts: Vec<&str> = s.split('-').collect();
|
||||||
|
let lens = [8, 4, 4, 4, 12];
|
||||||
|
let ok = parts.len() == 5
|
||||||
|
&& parts.iter().zip(lens).all(|(p, n)| p.len() == n && p.chars().all(|c| c.is_ascii_hexdigit()));
|
||||||
|
if ok {
|
||||||
|
Ok(s)
|
||||||
|
} else {
|
||||||
|
Err("issuer id: the UUID shown above the keys in App Store Connect".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_p8(text: &str) -> Result<String, String> {
|
||||||
|
if text.contains("-----BEGIN PRIVATE KEY-----") && text.contains("-----END PRIVATE KEY-----") {
|
||||||
|
Ok(text.trim().to_string() + "\n")
|
||||||
|
} else {
|
||||||
|
Err("not an App Store Connect .p8 key (BEGIN PRIVATE KEY missing)".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_label(s: &str) -> Result<String, String> {
|
||||||
|
let s = s.trim();
|
||||||
|
if s.is_empty() || s.chars().count() > 60 || s.chars().any(char::is_control) {
|
||||||
|
return Err("name: 1 to 60 characters".into());
|
||||||
|
}
|
||||||
|
Ok(s.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where secrets live. The OS keychain in the app; a map in tests.
|
||||||
|
pub trait SecretStore: Send + Sync {
|
||||||
|
fn set(&self, id: &str, secret: &Secret) -> Result<(), String>;
|
||||||
|
fn get(&self, id: &str) -> Result<Secret, String>;
|
||||||
|
fn delete(&self, id: &str) -> Result<(), String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Keychain;
|
||||||
|
|
||||||
|
impl SecretStore for Keychain {
|
||||||
|
fn set(&self, id: &str, secret: &Secret) -> Result<(), String> {
|
||||||
|
let json = serde_json::to_string(secret).map_err(|e| e.to_string())?;
|
||||||
|
keyring::Entry::new(KEYRING_SERVICE, id).and_then(|e| e.set_password(&json)).map_err(|e| format!("keychain: {e}"))
|
||||||
|
}
|
||||||
|
fn get(&self, id: &str) -> Result<Secret, String> {
|
||||||
|
let json = keyring::Entry::new(KEYRING_SERVICE, id).and_then(|e| e.get_password()).map_err(|e| format!("keychain: {e}"))?;
|
||||||
|
serde_json::from_str(&json).map_err(|_| "keychain: unreadable entry".to_string())
|
||||||
|
}
|
||||||
|
fn delete(&self, id: &str) -> Result<(), String> {
|
||||||
|
match keyring::Entry::new(KEYRING_SERVICE, id).and_then(|e| e.delete_credential()) {
|
||||||
|
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||||
|
Err(e) => Err(format!("keychain: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
375
apps/desktop/src-tauri/src/commands.rs
Normal file
375
apps/desktop/src-tauri/src/commands.rs
Normal file
|
|
@ -0,0 +1,375 @@
|
||||||
|
//! App commands. Each one first checks the calling window and page (policy::require_main). Secrets never cross into
|
||||||
|
//! the webview: account files are picked in native dialogs and read here, and credentials go from the keychain
|
||||||
|
//! straight into the sidecar call.
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::{json, Map, Value};
|
||||||
|
use tauri::{AppHandle, Manager, State, WebviewWindow};
|
||||||
|
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
|
||||||
|
use tauri_plugin_opener::OpenerExt;
|
||||||
|
|
||||||
|
use crate::accounts::{self, Account, AccountKind, Secret, SecretStore};
|
||||||
|
use crate::policy::{self, Kind};
|
||||||
|
use crate::sidecar::{Fail, Sidecar};
|
||||||
|
use crate::store::{self, Project, State as Saved};
|
||||||
|
|
||||||
|
pub struct AppState {
|
||||||
|
pub sidecar: Sidecar,
|
||||||
|
pub data_dir: PathBuf,
|
||||||
|
pub saved: Mutex<Saved>,
|
||||||
|
pub secrets: Box<dyn SecretStore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Res<T> = Result<T, Fail>;
|
||||||
|
|
||||||
|
fn guard(w: &WebviewWindow) -> Res<()> {
|
||||||
|
let url = w.url().map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
policy::require_main(w.label(), &url, cfg!(debug_assertions)).map_err(Fail::host)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn saved(s: &AppState) -> Res<std::sync::MutexGuard<'_, Saved>> {
|
||||||
|
s.saved.lock().map_err(|_| Fail::host("state poisoned"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn persist(s: &AppState, st: &Saved) -> Res<()> {
|
||||||
|
store::save(&s.data_dir, st).map_err(Fail::host)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Project folder + credentials of its mapped accounts, as sidecar params.
|
||||||
|
fn project_params(s: &AppState, project_id: &str) -> Res<(Project, Map<String, Value>)> {
|
||||||
|
let p = saved(s)?.projects.iter().find(|p| p.id == project_id).cloned().ok_or_else(|| Fail::host("unknown project"))?;
|
||||||
|
let mut creds = Map::new();
|
||||||
|
for id in [&p.play_account, &p.apple_account].into_iter().flatten() {
|
||||||
|
// A missing keychain entry is not fatal: the command says which credential it lacks.
|
||||||
|
if let Ok(secret) = s.secrets.get(id) {
|
||||||
|
secret.to_credentials(&mut creds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((p, creds))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct AppInfo {
|
||||||
|
version: &'static str,
|
||||||
|
identifier: String,
|
||||||
|
platform: &'static str,
|
||||||
|
debug: bool,
|
||||||
|
/// Shown as "~" in paths, so screenshots do not carry the account name.
|
||||||
|
home: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn app_info(window: WebviewWindow, app: AppHandle) -> Res<AppInfo> {
|
||||||
|
guard(&window)?;
|
||||||
|
Ok(AppInfo {
|
||||||
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
|
identifier: app.config().identifier.clone(),
|
||||||
|
platform: std::env::consts::OS,
|
||||||
|
debug: cfg!(debug_assertions),
|
||||||
|
home: app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn sidecar_status(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>) -> Res<Value> {
|
||||||
|
guard(&window)?;
|
||||||
|
let r = state.sidecar.get(&app).await?;
|
||||||
|
let tools = r.call("system.tools", json!({})).await.unwrap_or(Value::Null);
|
||||||
|
Ok(json!({ "running": r.alive(), "version": r.version, "protocol": r.protocol, "methods": r.methods, "tools": tools }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A read (or dry-run write) through the sidecar. Writes from here are always dry runs (policy::sanitize_js_call).
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, method: String, project_id: Option<String>, params: Option<Value>) -> Res<Value> {
|
||||||
|
guard(&window)?;
|
||||||
|
let r = state.sidecar.get(&app).await?;
|
||||||
|
let kind = r.kind(&method);
|
||||||
|
let mut p = policy::sanitize_js_call(&method, kind, ¶ms.unwrap_or(Value::Null)).map_err(Fail::host)?;
|
||||||
|
if matches!(kind, Some(Kind::Read | Kind::Write)) {
|
||||||
|
let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?;
|
||||||
|
let (proj, creds) = project_params(&state, &id)?;
|
||||||
|
let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?;
|
||||||
|
o.insert("project".into(), Value::String(proj.path));
|
||||||
|
if !creds.is_empty() && method != "project.inspect" {
|
||||||
|
o.insert("credentials".into(), Value::Object(creds));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.call(&method, p).await
|
||||||
|
}
|
||||||
|
|
||||||
|
const DIALOG_LINES: usize = 28;
|
||||||
|
const DIALOG_CHARS: usize = 2_400;
|
||||||
|
|
||||||
|
/// Last lines of a dry run for the dialog (native alerts do not scroll well).
|
||||||
|
pub fn dialog_excerpt(output: &str) -> String {
|
||||||
|
let lines: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||||
|
let start = lines.len().saturating_sub(DIALOG_LINES);
|
||||||
|
let mut s = lines[start..].join("\n");
|
||||||
|
if s.chars().count() > DIALOG_CHARS {
|
||||||
|
s = s.chars().rev().take(DIALOG_CHARS).collect::<Vec<_>>().into_iter().rev().collect();
|
||||||
|
s = format!("...{s}");
|
||||||
|
}
|
||||||
|
if start > 0 {
|
||||||
|
s = format!("({start} earlier lines in the app log)\n{s}");
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The home folder as "~" in dialog text, so a screenshot or screen share does not carry the account name.
|
||||||
|
pub fn tilde(text: &str, home: Option<&str>) -> String {
|
||||||
|
match home.map(|h| h.trim_end_matches(['/', '\\'])) {
|
||||||
|
Some(h) if h.len() > 1 => text.replace(h, "~"),
|
||||||
|
_ => text.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Human summary shown above the dry run in the confirm dialog.
|
||||||
|
pub fn dialog_summary(title: &str, description: &str, project: &str, network: bool, destructive: bool) -> String {
|
||||||
|
let mut s = format!("{title} · {project}\n\n{description}\n\n");
|
||||||
|
s.push_str(if network { "This changes your store records (not public until you submit or release in the console)." } else { "This changes local files only." });
|
||||||
|
if destructive {
|
||||||
|
s.push_str("\nIt replaces what is there now.");
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dry run, then a native dialog with the summary and the dry run, then (only on Apply) the real run with a confirm
|
||||||
|
/// token minted here for exactly this method, project and arguments.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, method: String, project_id: String, args: Option<Value>) -> Res<Value> {
|
||||||
|
guard(&window)?;
|
||||||
|
let r = state.sidecar.get(&app).await?;
|
||||||
|
if r.kind(&method) != Some(Kind::Write) {
|
||||||
|
return Err(Fail::host(format!("{method} is not a write method")));
|
||||||
|
}
|
||||||
|
let d = r.descriptor(&method).cloned().ok_or_else(|| Fail::host("unknown method"))?;
|
||||||
|
let args = match args.unwrap_or(json!({})) {
|
||||||
|
Value::Object(o) => Value::Object(o),
|
||||||
|
_ => return Err(Fail::host("args must be an object")),
|
||||||
|
};
|
||||||
|
let (proj, creds) = project_params(&state, &project_id)?;
|
||||||
|
let mut dry_params = json!({ "project": proj.path, "args": args, "dryRun": true });
|
||||||
|
if !creds.is_empty() {
|
||||||
|
dry_params["credentials"] = Value::Object(creds.clone());
|
||||||
|
}
|
||||||
|
let dry = r.call(&method, dry_params).await?;
|
||||||
|
if dry["ok"] != Value::Bool(true) {
|
||||||
|
return Ok(json!({ "confirmed": false, "stage": "dry-run", "dryRun": dry }));
|
||||||
|
}
|
||||||
|
let text = format!(
|
||||||
|
"{}\n\nDry run ({}):\n{}",
|
||||||
|
dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive),
|
||||||
|
dry["command"].as_str().unwrap_or_default(),
|
||||||
|
dialog_excerpt(dry["output"].as_str().unwrap_or_default())
|
||||||
|
);
|
||||||
|
let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string());
|
||||||
|
let text = tilde(&text, home.as_deref());
|
||||||
|
let w = window.clone();
|
||||||
|
let title = format!("Apply: {}", d.title);
|
||||||
|
let yes = tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
w.app_handle()
|
||||||
|
.dialog()
|
||||||
|
.message(text)
|
||||||
|
.title(title)
|
||||||
|
.kind(MessageDialogKind::Warning)
|
||||||
|
.buttons(MessageDialogButtons::OkCancelCustom("Apply".into(), "Cancel".into()))
|
||||||
|
.parent(&w)
|
||||||
|
.blocking_show()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
if !yes {
|
||||||
|
return Ok(json!({ "confirmed": false, "stage": "dialog", "dryRun": dry }));
|
||||||
|
}
|
||||||
|
let bound = json!({ "project": proj.path, "args": args });
|
||||||
|
let token = r.mint(&method, &bound).map_err(Fail::host)?;
|
||||||
|
let mut real = json!({ "project": proj.path, "args": args, "dryRun": false, "confirmToken": token });
|
||||||
|
if !creds.is_empty() {
|
||||||
|
real["credentials"] = Value::Object(creds);
|
||||||
|
}
|
||||||
|
let result = r.call(&method, real).await?;
|
||||||
|
Ok(json!({ "confirmed": true, "stage": "done", "dryRun": dry, "result": result }))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn projects_list(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<Project>> {
|
||||||
|
guard(&window)?;
|
||||||
|
Ok(saved(&state)?.projects.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
const CONFIG_NAMES: [&str; 3] = ["storebound.config.ts", "storebound.config.js", "storebound.config.json"];
|
||||||
|
|
||||||
|
pub fn has_config(dir: &Path) -> bool {
|
||||||
|
CONFIG_NAMES.iter().any(|n| dir.join(n).is_file())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Native folder picker; the folder must contain storebound.config.ts and load (project.inspect). None = cancelled.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn project_add(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>) -> Res<Option<Project>> {
|
||||||
|
guard(&window)?;
|
||||||
|
let w = window.clone();
|
||||||
|
let picked = tauri::async_runtime::spawn_blocking(move || w.app_handle().dialog().file().set_title("Add a game folder (with storebound.config.ts)").set_parent(&w).blocking_pick_folder())
|
||||||
|
.await
|
||||||
|
.map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
let Some(picked) = picked else { return Ok(None) };
|
||||||
|
let dir = picked.into_path().map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
let dir = std::fs::canonicalize(&dir).unwrap_or(dir);
|
||||||
|
if !has_config(&dir) {
|
||||||
|
return Err(Fail::host(format!("no storebound.config.ts in {}", dir.display())));
|
||||||
|
}
|
||||||
|
let path = dir.to_string_lossy().to_string();
|
||||||
|
if saved(&state)?.projects.iter().any(|p| p.path == path) {
|
||||||
|
return Err(Fail::host("this folder is already in the list"));
|
||||||
|
}
|
||||||
|
let r = state.sidecar.get(&app).await?;
|
||||||
|
let summary = r.call("project.inspect", json!({ "project": path })).await?;
|
||||||
|
let project = Project {
|
||||||
|
id: store::new_id()?,
|
||||||
|
path,
|
||||||
|
name: summary["name"].as_str().unwrap_or("?").to_string(),
|
||||||
|
play_account: None,
|
||||||
|
apple_account: None,
|
||||||
|
added: store::now_iso(),
|
||||||
|
};
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
st.projects.push(project.clone());
|
||||||
|
persist(&state, &st)?;
|
||||||
|
Ok(Some(project))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn project_remove(window: WebviewWindow, state: State<'_, AppState>, id: String) -> Res<()> {
|
||||||
|
guard(&window)?;
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
st.projects.retain(|p| p.id != id);
|
||||||
|
persist(&state, &st)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn project_set_accounts(window: WebviewWindow, state: State<'_, AppState>, id: String, play: Option<String>, apple: Option<String>) -> Res<Project> {
|
||||||
|
guard(&window)?;
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
let kind_of = |acc: &Option<String>| acc.as_ref().map(|a| st.accounts.iter().find(|x| &x.id == a).map(|x| x.kind));
|
||||||
|
if let Some(k) = kind_of(&play) {
|
||||||
|
if k != Some(AccountKind::Play) {
|
||||||
|
return Err(Fail::host("not a Google Play account"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(k) = kind_of(&apple) {
|
||||||
|
if k != Some(AccountKind::Apple) {
|
||||||
|
return Err(Fail::host("not an App Store Connect account"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let p = st.projects.iter_mut().find(|p| p.id == id).ok_or_else(|| Fail::host("unknown project"))?;
|
||||||
|
p.play_account = play;
|
||||||
|
p.apple_account = apple;
|
||||||
|
let out = p.clone();
|
||||||
|
persist(&state, &st)?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn accounts_list(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<Account>> {
|
||||||
|
guard(&window)?;
|
||||||
|
Ok(saved(&state)?.accounts.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_account(state: &AppState, label: &str, secret: Secret) -> Res<Account> {
|
||||||
|
let label = accounts::check_label(label).map_err(Fail::host)?;
|
||||||
|
let acc = Account { id: store::new_id()?, label, kind: secret.kind(), created: store::now_iso() };
|
||||||
|
state.secrets.set(&acc.id, &secret).map_err(Fail::host)?;
|
||||||
|
let mut st = saved(state)?;
|
||||||
|
st.accounts.push(acc.clone());
|
||||||
|
if let Err(e) = persist(state, &st) {
|
||||||
|
let _ = state.secrets.delete(&acc.id);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
Ok(acc)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn pick_file(window: &WebviewWindow, title: &'static str, filter: (&'static str, &'static [&'static str])) -> Res<Option<String>> {
|
||||||
|
let w = window.clone();
|
||||||
|
let picked = tauri::async_runtime::spawn_blocking(move || w.app_handle().dialog().file().set_title(title).add_filter(filter.0, filter.1).set_parent(&w).blocking_pick_file())
|
||||||
|
.await
|
||||||
|
.map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
let Some(p) = picked else { return Ok(None) };
|
||||||
|
let path = p.into_path().map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
let meta = std::fs::metadata(&path).map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
if meta.len() > 64 * 1024 {
|
||||||
|
return Err(Fail::host("file too large for a key"));
|
||||||
|
}
|
||||||
|
std::fs::read_to_string(&path).map(Some).map_err(|e| Fail::host(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Google Play: pick the service account JSON key in a native dialog; it goes to the keychain only.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>, label: String) -> Res<Option<Account>> {
|
||||||
|
guard(&window)?;
|
||||||
|
accounts::check_label(&label).map_err(Fail::host)?;
|
||||||
|
let Some(text) = pick_file(&window, "Google Play service account key (JSON)", ("JSON key", &["json"])).await? else { return Ok(None) };
|
||||||
|
let sa = accounts::check_service_account(&text).map_err(Fail::host)?;
|
||||||
|
add_account(&state, &label, Secret::Play { service_account: sa }).map(Some)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// App Store Connect: key id + issuer id typed in the app, the .p8 picked in a native dialog; all to the keychain.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>, label: String, key_id: String, issuer_id: String) -> Res<Option<Account>> {
|
||||||
|
guard(&window)?;
|
||||||
|
accounts::check_label(&label).map_err(Fail::host)?;
|
||||||
|
let key_id = accounts::check_key_id(&key_id).map_err(Fail::host)?;
|
||||||
|
let issuer_id = accounts::check_issuer_id(&issuer_id).map_err(Fail::host)?;
|
||||||
|
let Some(text) = pick_file(&window, "App Store Connect API key (.p8)", ("API key", &["p8"])).await? else { return Ok(None) };
|
||||||
|
let p8 = accounts::check_p8(&text).map_err(Fail::host)?;
|
||||||
|
add_account(&state, &label, Secret::Apple { key_id, issuer_id, p8 }).map(Some)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn account_remove(window: WebviewWindow, state: State<'_, AppState>, id: String) -> Res<()> {
|
||||||
|
guard(&window)?;
|
||||||
|
state.secrets.delete(&id).map_err(Fail::host)?;
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
st.accounts.retain(|a| a.id != id);
|
||||||
|
for p in st.projects.iter_mut() {
|
||||||
|
if p.play_account.as_deref() == Some(id.as_str()) {
|
||||||
|
p.play_account = None;
|
||||||
|
}
|
||||||
|
if p.apple_account.as_deref() == Some(id.as_str()) {
|
||||||
|
p.apple_account = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
persist(&state, &st)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `portfolio.status` over every project. Offline unless `live`; live runs each project with its own accounts.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, live: Option<bool>) -> Res<Value> {
|
||||||
|
guard(&window)?;
|
||||||
|
let projects = saved(&state)?.projects.clone();
|
||||||
|
if projects.is_empty() {
|
||||||
|
return Ok(json!({ "apps": [], "at": store::now_iso() }));
|
||||||
|
}
|
||||||
|
let r = state.sidecar.get(&app).await?;
|
||||||
|
if live != Some(true) {
|
||||||
|
let paths: Vec<&str> = projects.iter().map(|p| p.path.as_str()).collect();
|
||||||
|
return r.call("portfolio.status", json!({ "projects": paths })).await;
|
||||||
|
}
|
||||||
|
let mut all = Vec::new();
|
||||||
|
for p in &projects {
|
||||||
|
let (_, creds) = project_params(&state, &p.id)?;
|
||||||
|
let res = r.call("portfolio.status", json!({ "projects": [p.path], "live": true, "credentials": creds })).await?;
|
||||||
|
all.extend(res["apps"].as_array().cloned().unwrap_or_default());
|
||||||
|
}
|
||||||
|
Ok(json!({ "apps": all, "at": store::now_iso() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn open_external(window: WebviewWindow, app: AppHandle, url: String) -> Res<()> {
|
||||||
|
guard(&window)?;
|
||||||
|
let u = url::Url::parse(&url).map_err(|_| Fail::host("not a URL"))?;
|
||||||
|
if !policy::external_allowed(&u) {
|
||||||
|
return Err(Fail::host("only the store consoles and storebound.dev open from here"));
|
||||||
|
}
|
||||||
|
app.opener().open_url(u.as_str(), None::<&str>).map_err(|e| Fail::host(e.to_string()))
|
||||||
|
}
|
||||||
18
apps/desktop/src-tauri/src/commands_list.rs
Normal file
18
apps/desktop/src-tauri/src/commands_list.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
/// Every app command the webview can call. build.rs turns each into an `allow-<name>` permission (underscores become
|
||||||
|
/// dashes); capabilities/main.json grants them to the `main` window only; tests/security.rs checks both lists match.
|
||||||
|
pub const COMMANDS: &[&str] = &[
|
||||||
|
"app_info",
|
||||||
|
"sidecar_status",
|
||||||
|
"sidecar_call",
|
||||||
|
"write_with_confirm",
|
||||||
|
"projects_list",
|
||||||
|
"project_add",
|
||||||
|
"project_remove",
|
||||||
|
"project_set_accounts",
|
||||||
|
"accounts_list",
|
||||||
|
"account_add_play",
|
||||||
|
"account_add_apple",
|
||||||
|
"account_remove",
|
||||||
|
"portfolio_status",
|
||||||
|
"open_external",
|
||||||
|
];
|
||||||
100
apps/desktop/src-tauri/src/confirm.rs
Normal file
100
apps/desktop/src-tauri/src/confirm.rs
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
//! Confirm tokens, host side. The same scheme as cli/lib/confirm-token.ts (the sidecar verifies):
|
||||||
|
//!
|
||||||
|
//! token = "sbt1." + expiry_ms + "." + nonce + "." + base64url(HMAC-SHA256(secret, payload))
|
||||||
|
//! payload = "storebound-confirm-v1\n" + method + "\n" + canonical(params) + "\n" + expiry_ms + "\n" + nonce
|
||||||
|
//!
|
||||||
|
//! The secret is 32 random bytes made per sidecar start and handed over in `session.hello` on the sidecar's stdin; it
|
||||||
|
//! never leaves this process otherwise. Tokens are minted only by `commands::write_with_confirm`, right after the owner
|
||||||
|
//! pressed the confirm button of the native dialog that showed the dry run.
|
||||||
|
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
|
||||||
|
use hmac::{Hmac, Mac};
|
||||||
|
use serde_json::Value;
|
||||||
|
use sha2::Sha256;
|
||||||
|
|
||||||
|
pub const PREFIX: &str = "sbt1";
|
||||||
|
pub const DOMAIN: &str = "storebound-confirm-v1";
|
||||||
|
/// Lifetime of a minted token: the real call follows the dialog right away.
|
||||||
|
pub const TTL_MS: u64 = 60_000;
|
||||||
|
const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
|
||||||
|
|
||||||
|
/// Canonical JSON, byte for byte what the TypeScript side builds: keys sorted by UTF-16 code units, no whitespace,
|
||||||
|
/// JSON string escaping, numbers only as safe integers, null members kept (JSON has no undefined).
|
||||||
|
pub fn canonical(v: &Value) -> Result<String, String> {
|
||||||
|
let mut out = String::new();
|
||||||
|
write_canonical(v, &mut out)?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_canonical(v: &Value, out: &mut String) -> Result<(), String> {
|
||||||
|
match v {
|
||||||
|
Value::Null => out.push_str("null"),
|
||||||
|
Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
|
||||||
|
Value::Number(n) => {
|
||||||
|
let i = n
|
||||||
|
.as_i64()
|
||||||
|
.filter(|i| (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(i))
|
||||||
|
.ok_or("canonical: only safe integers are allowed as numbers")?;
|
||||||
|
out.push_str(&i.to_string());
|
||||||
|
}
|
||||||
|
Value::String(s) => out.push_str(&serde_json::to_string(s).map_err(|e| e.to_string())?),
|
||||||
|
Value::Array(a) => {
|
||||||
|
out.push('[');
|
||||||
|
for (i, x) in a.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
out.push(',');
|
||||||
|
}
|
||||||
|
write_canonical(x, out)?;
|
||||||
|
}
|
||||||
|
out.push(']');
|
||||||
|
}
|
||||||
|
Value::Object(o) => {
|
||||||
|
let mut keys: Vec<&String> = o.keys().collect();
|
||||||
|
keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
|
||||||
|
out.push('{');
|
||||||
|
for (i, k) in keys.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
out.push(',');
|
||||||
|
}
|
||||||
|
out.push_str(&serde_json::to_string(k).map_err(|e| e.to_string())?);
|
||||||
|
out.push(':');
|
||||||
|
write_canonical(&o[k.as_str()], out)?;
|
||||||
|
}
|
||||||
|
out.push('}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn payload(method: &str, params: &Value, expiry: u64, nonce: &str) -> Result<String, String> {
|
||||||
|
Ok(format!("{DOMAIN}\n{method}\n{}\n{expiry}\n{nonce}", canonical(params)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mac(secret: &[u8], method: &str, params: &Value, expiry: u64, nonce: &str) -> Result<String, String> {
|
||||||
|
let mut m = Hmac::<Sha256>::new_from_slice(secret).map_err(|e| e.to_string())?;
|
||||||
|
m.update(payload(method, params, expiry, nonce)?.as_bytes());
|
||||||
|
Ok(URL_SAFE_NO_PAD.encode(m.finalize().into_bytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A token for exactly (method, params), valid for TTL_MS from `now_ms`.
|
||||||
|
pub fn mint(secret: &[u8], method: &str, params: &Value, now_ms: u64, nonce: &str) -> Result<String, String> {
|
||||||
|
let expiry = now_ms + TTL_MS;
|
||||||
|
Ok(format!("{PREFIX}.{expiry}.{nonce}.{}", mac(secret, method, params, expiry, nonce)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 16 random bytes, base64url (22 characters).
|
||||||
|
pub fn new_nonce() -> Result<String, String> {
|
||||||
|
let mut b = [0u8; 16];
|
||||||
|
getrandom::fill(&mut b).map_err(|e| e.to_string())?;
|
||||||
|
Ok(URL_SAFE_NO_PAD.encode(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The per-session secret.
|
||||||
|
pub fn new_secret() -> Result<[u8; 32], String> {
|
||||||
|
let mut b = [0u8; 32];
|
||||||
|
getrandom::fill(&mut b).map_err(|e| e.to_string())?;
|
||||||
|
Ok(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hex(b: &[u8]) -> String {
|
||||||
|
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||||
|
}
|
||||||
172
apps/desktop/src-tauri/src/lib.rs
Normal file
172
apps/desktop/src-tauri/src/lib.rs
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
//! storebound desktop: a Tauri shell around the storebound CLI, which runs as a sidecar (`storebound serve --stdio`).
|
||||||
|
//! The GUI never talks to a store itself; every store call is a storebound command.
|
||||||
|
pub mod accounts;
|
||||||
|
pub mod commands;
|
||||||
|
pub mod confirm;
|
||||||
|
pub mod policy;
|
||||||
|
pub mod sidecar;
|
||||||
|
pub mod store;
|
||||||
|
|
||||||
|
include!("commands_list.rs");
|
||||||
|
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem, Submenu, WINDOW_SUBMENU_ID};
|
||||||
|
use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime, WindowEvent};
|
||||||
|
use tauri_plugin_deep_link::DeepLinkExt;
|
||||||
|
|
||||||
|
/// WebKitGTK's DMABUF renderer leaves the window blank on some Linux GPU / driver / VM combinations. Turn it off unless
|
||||||
|
/// the user set the variable (WEBKIT_DISABLE_DMABUF_RENDERER=0 keeps DMABUF). Must run before any webview exists.
|
||||||
|
pub fn linux_webkit_env() {
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
if std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none() {
|
||||||
|
// SAFETY: called first thing in main, before any thread is started.
|
||||||
|
unsafe { std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1") };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show_main<R: Runtime>(app: &AppHandle<R>) {
|
||||||
|
if let Some(w) = app.get_webview_window(policy::MAIN) {
|
||||||
|
let _ = w.unminimize();
|
||||||
|
let _ = w.show();
|
||||||
|
let _ = w.set_focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// macOS menu: app menu with Quit (Cmd+Q really quits), Edit (copy / paste in text fields), and a Window menu that
|
||||||
|
/// keeps a permanent entry for the main window, since the automatic list drops a hidden window.
|
||||||
|
fn menu<R: Runtime>(app: &AppHandle<R>) -> tauri::Result<Menu<R>> {
|
||||||
|
let name = "storebound";
|
||||||
|
let app_menu = Submenu::with_items(
|
||||||
|
app,
|
||||||
|
name,
|
||||||
|
true,
|
||||||
|
&[
|
||||||
|
&PredefinedMenuItem::about(app, Some("About storebound"), None)?,
|
||||||
|
&PredefinedMenuItem::separator(app)?,
|
||||||
|
&PredefinedMenuItem::services(app, None)?,
|
||||||
|
&PredefinedMenuItem::separator(app)?,
|
||||||
|
&PredefinedMenuItem::hide(app, None)?,
|
||||||
|
&PredefinedMenuItem::hide_others(app, None)?,
|
||||||
|
&PredefinedMenuItem::show_all(app, None)?,
|
||||||
|
&PredefinedMenuItem::separator(app)?,
|
||||||
|
&PredefinedMenuItem::quit(app, Some("Quit storebound"))?,
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
let edit = Submenu::with_items(
|
||||||
|
app,
|
||||||
|
"Edit",
|
||||||
|
true,
|
||||||
|
&[
|
||||||
|
&PredefinedMenuItem::undo(app, None)?,
|
||||||
|
&PredefinedMenuItem::redo(app, None)?,
|
||||||
|
&PredefinedMenuItem::separator(app)?,
|
||||||
|
&PredefinedMenuItem::cut(app, None)?,
|
||||||
|
&PredefinedMenuItem::copy(app, None)?,
|
||||||
|
&PredefinedMenuItem::paste(app, None)?,
|
||||||
|
&PredefinedMenuItem::select_all(app, None)?,
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
let window = Submenu::with_id_and_items(
|
||||||
|
app,
|
||||||
|
WINDOW_SUBMENU_ID,
|
||||||
|
"Window",
|
||||||
|
true,
|
||||||
|
&[
|
||||||
|
&PredefinedMenuItem::minimize(app, None)?,
|
||||||
|
&PredefinedMenuItem::maximize(app, Some("Zoom"))?,
|
||||||
|
&PredefinedMenuItem::separator(app)?,
|
||||||
|
&MenuItem::with_id(app, "show-main", "storebound", true, Some("CmdOrCtrl+0"))?,
|
||||||
|
&PredefinedMenuItem::separator(app)?,
|
||||||
|
&PredefinedMenuItem::close_window(app, None)?,
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Menu::with_items(app, &[&app_menu, &edit, &window])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_deep_link<R: Runtime>(app: &AppHandle<R>, urls: &[url::Url]) {
|
||||||
|
if let Some(screen) = urls.iter().find_map(policy::deep_link_screen) {
|
||||||
|
show_main(app);
|
||||||
|
let _ = app.emit_to(policy::MAIN, "deep-link", screen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run() {
|
||||||
|
linux_webkit_env();
|
||||||
|
let app = tauri::Builder::default()
|
||||||
|
// single-instance first: a second start (or a storebound:// link) focuses the running app instead
|
||||||
|
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| show_main(app)))
|
||||||
|
.plugin(tauri_plugin_deep_link::init())
|
||||||
|
.plugin(tauri_plugin_window_state::Builder::new().build())
|
||||||
|
.plugin(tauri_plugin_shell::init())
|
||||||
|
.plugin(tauri_plugin_opener::init())
|
||||||
|
.plugin(tauri_plugin_dialog::init())
|
||||||
|
.plugin(tauri_plugin_notification::init())
|
||||||
|
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||||
|
.plugin(tauri_plugin_process::init())
|
||||||
|
.setup(|app| {
|
||||||
|
let data_dir = app.path().app_data_dir()?;
|
||||||
|
app.manage(commands::AppState {
|
||||||
|
sidecar: sidecar::Sidecar::default(),
|
||||||
|
saved: Mutex::new(store::load(&data_dir)),
|
||||||
|
data_dir,
|
||||||
|
secrets: Box::new(accounts::Keychain),
|
||||||
|
});
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
app.set_menu(menu(app.handle())?)?;
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
let _ = menu::<tauri::Wry>;
|
||||||
|
app.on_menu_event(|app, e| {
|
||||||
|
if e.id() == "show-main" {
|
||||||
|
show_main(app);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
#[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
|
||||||
|
app.deep_link().register_all()?;
|
||||||
|
let handle = app.handle().clone();
|
||||||
|
app.deep_link().on_open_url(move |e| handle_deep_link(&handle, &e.urls()));
|
||||||
|
if let Ok(Some(urls)) = app.deep_link().get_current() {
|
||||||
|
handle_deep_link(app.handle(), &urls);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.on_window_event(|w, e| {
|
||||||
|
// macOS: the close button hides the window (the app stays in the Dock and the Window menu);
|
||||||
|
// Cmd+Q and the app menu's Quit still quit. Elsewhere closing the window quits.
|
||||||
|
if cfg!(target_os = "macos") && w.label() == policy::MAIN {
|
||||||
|
if let WindowEvent::CloseRequested { api, .. } = e {
|
||||||
|
api.prevent_close();
|
||||||
|
let _ = w.hide();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
commands::app_info,
|
||||||
|
commands::sidecar_status,
|
||||||
|
commands::sidecar_call,
|
||||||
|
commands::write_with_confirm,
|
||||||
|
commands::projects_list,
|
||||||
|
commands::project_add,
|
||||||
|
commands::project_remove,
|
||||||
|
commands::project_set_accounts,
|
||||||
|
commands::accounts_list,
|
||||||
|
commands::account_add_play,
|
||||||
|
commands::account_add_apple,
|
||||||
|
commands::account_remove,
|
||||||
|
commands::portfolio_status,
|
||||||
|
commands::open_external,
|
||||||
|
])
|
||||||
|
.build(tauri::generate_context!())
|
||||||
|
.expect("storebound desktop failed to start");
|
||||||
|
|
||||||
|
app.run(|app, e| match e {
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
RunEvent::Reopen { .. } => show_main(app),
|
||||||
|
RunEvent::Exit => {
|
||||||
|
if let Some(s) = app.try_state::<commands::AppState>() {
|
||||||
|
s.sidecar.shutdown_now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
});
|
||||||
|
}
|
||||||
6
apps/desktop/src-tauri/src/main.rs
Normal file
6
apps/desktop/src-tauri/src/main.rs
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
// No console window on Windows release builds.
|
||||||
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
storebound_desktop::run();
|
||||||
|
}
|
||||||
142
apps/desktop/src-tauri/src/policy.rs
Normal file
142
apps/desktop/src-tauri/src/policy.rs
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
//! Who may call what. Pure functions, so tests/security.rs can pin every rule.
|
||||||
|
//!
|
||||||
|
//! The capability file already limits the app commands to the `main` window with local content; every command checks
|
||||||
|
//! again here (window label and the exact origin of the page that called), so a future second window, a stray
|
||||||
|
//! navigation or a remote page can never reach them, whatever the capability files say.
|
||||||
|
use serde_json::{Map, Value};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
/// The one window that may call app commands.
|
||||||
|
pub const MAIN: &str = "main";
|
||||||
|
|
||||||
|
/// The only arguments the sidecar is ever started with.
|
||||||
|
pub const SIDECAR_ARGS: [&str; 2] = ["serve", "--stdio"];
|
||||||
|
/// Name of the sidecar binary (`bundle.externalBin` = binaries/storebound).
|
||||||
|
pub const SIDECAR: &str = "storebound";
|
||||||
|
|
||||||
|
/// Dev server origin (`build.devUrl`); accepted only in debug builds.
|
||||||
|
pub const DEV_HOST: &str = "127.0.0.1";
|
||||||
|
pub const DEV_PORT: u16 = 1420;
|
||||||
|
|
||||||
|
/// The app's own bundled pages: `tauri://localhost` (macOS, Linux) or `http(s)://tauri.localhost` (Windows).
|
||||||
|
/// No port, no user info, nothing that only looks similar. In debug builds also the Vite dev server.
|
||||||
|
pub fn is_local_origin(url: &Url, dev: bool) -> bool {
|
||||||
|
if !url.username().is_empty() || url.password().is_some() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let host = url.host_str().unwrap_or_default();
|
||||||
|
match url.scheme() {
|
||||||
|
"tauri" => host == "localhost" && url.port().is_none(),
|
||||||
|
"http" | "https" if host == "tauri.localhost" => url.port().is_none(),
|
||||||
|
"http" if dev => host == DEV_HOST && url.port() == Some(DEV_PORT),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn require_main(label: &str, url: &Url, dev: bool) -> Result<(), String> {
|
||||||
|
if label != MAIN {
|
||||||
|
return Err(format!("not allowed from window '{label}'"));
|
||||||
|
}
|
||||||
|
if !is_local_origin(url, dev) {
|
||||||
|
return Err("not allowed from this page".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Method kinds the sidecar announces in its `session.hello` descriptors.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Kind {
|
||||||
|
Read,
|
||||||
|
Write,
|
||||||
|
System,
|
||||||
|
Portfolio,
|
||||||
|
Session,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Kind {
|
||||||
|
pub fn parse(s: &str) -> Option<Kind> {
|
||||||
|
Some(match s {
|
||||||
|
"read" => Kind::Read,
|
||||||
|
"write" => Kind::Write,
|
||||||
|
"system" => Kind::System,
|
||||||
|
"portfolio" => Kind::Portfolio,
|
||||||
|
"session" => Kind::Session,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Params keys the webview may send for a sidecar method. The project folder comes from the host's project list (the
|
||||||
|
/// webview names a project id), and `confirmToken`, `credentials` and `dryRun` are the host's: tokens are minted only
|
||||||
|
/// after the native dialog, credentials come from the keychain.
|
||||||
|
const JS_PARAM_KEYS: &[&str] = &["args", "live"];
|
||||||
|
|
||||||
|
/// Checks a webview call to the sidecar and returns the params to send. Writes from the webview are always dry runs;
|
||||||
|
/// the real run goes through `write_with_confirm` (native dialog, then a host-minted token).
|
||||||
|
pub fn sanitize_js_call(method: &str, kind: Option<Kind>, params: &Value) -> Result<Value, String> {
|
||||||
|
let kind = kind.ok_or_else(|| format!("unknown method: {method}"))?;
|
||||||
|
match kind {
|
||||||
|
Kind::Session => return Err(format!("{method} is the host's")),
|
||||||
|
Kind::Portfolio => return Err(format!("{method}: use portfolio_status")),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
let empty = Map::new();
|
||||||
|
let obj = match params {
|
||||||
|
Value::Object(o) => o,
|
||||||
|
Value::Null => &empty,
|
||||||
|
_ => return Err("params must be an object".into()),
|
||||||
|
};
|
||||||
|
for k in obj.keys() {
|
||||||
|
if !JS_PARAM_KEYS.contains(&k.as_str()) {
|
||||||
|
return Err(format!("param '{k}' is not allowed from the window"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = obj.clone();
|
||||||
|
if kind == Kind::Write {
|
||||||
|
out.insert("dryRun".into(), Value::Bool(true));
|
||||||
|
}
|
||||||
|
Ok(Value::Object(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hosts `open_external` may open in the browser: the two store consoles and storebound's own site.
|
||||||
|
pub const EXTERNAL_HOSTS: &[&str] = &[
|
||||||
|
"play.google.com",
|
||||||
|
"appstoreconnect.apple.com",
|
||||||
|
"developer.apple.com",
|
||||||
|
"storebound.dev",
|
||||||
|
// Dependencies screen link-outs
|
||||||
|
"developer.android.com",
|
||||||
|
"ffmpeg.org",
|
||||||
|
"googlechromelabs.github.io",
|
||||||
|
"git-scm.com",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Executable of a Chrome for Testing download, relative to its unpacked folder (app data `tools/chrome/`).
|
||||||
|
pub fn chrome_executable() -> &'static str {
|
||||||
|
if cfg!(target_os = "macos") {
|
||||||
|
"Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
|
||||||
|
} else if cfg!(windows) {
|
||||||
|
"chrome.exe"
|
||||||
|
} else {
|
||||||
|
"chrome"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn external_allowed(url: &Url) -> bool {
|
||||||
|
url.scheme() == "https"
|
||||||
|
&& url.username().is_empty()
|
||||||
|
&& url.password().is_none()
|
||||||
|
&& url.port().is_none()
|
||||||
|
&& url.host_str().is_some_and(|h| EXTERNAL_HOSTS.contains(&h))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deep links the app reacts to: `storebound://<screen>` for a known screen, nothing else.
|
||||||
|
pub const DEEP_LINK_SCREENS: &[&str] = &["portfolio", "apps", "accounts", "dependencies", "settings"];
|
||||||
|
|
||||||
|
pub fn deep_link_screen(url: &Url) -> Option<&'static str> {
|
||||||
|
if url.scheme() != "storebound" {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let host = url.host_str().unwrap_or_default();
|
||||||
|
DEEP_LINK_SCREENS.iter().copied().find(|s| *s == host)
|
||||||
|
}
|
||||||
295
apps/desktop/src-tauri/src/sidecar.rs
Normal file
295
apps/desktop/src-tauri/src/sidecar.rs
Normal file
|
|
@ -0,0 +1,295 @@
|
||||||
|
//! The storebound sidecar: `storebound serve --stdio`, started from Rust only (no capability grants the shell
|
||||||
|
//! plugin to the webview), with the fixed arguments in policy::SIDECAR_ARGS. One process per app run, started on
|
||||||
|
//! first use and again after it stops. Its first request is `session.hello` with a fresh 32-byte secret, so only this
|
||||||
|
//! process can mint the confirm tokens the sidecar accepts for real writes.
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use tauri::{AppHandle, Emitter, Manager, Runtime};
|
||||||
|
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
|
||||||
|
use tauri_plugin_shell::ShellExt;
|
||||||
|
use tokio::sync::oneshot;
|
||||||
|
|
||||||
|
use crate::confirm;
|
||||||
|
use crate::policy::{self, Kind};
|
||||||
|
|
||||||
|
/// A failed call, as the webview sees it.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Fail {
|
||||||
|
pub code: i64,
|
||||||
|
pub message: String,
|
||||||
|
#[serde(skip_serializing_if = "Value::is_null")]
|
||||||
|
pub data: Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fail {
|
||||||
|
pub fn new(code: i64, message: impl Into<String>) -> Fail {
|
||||||
|
Fail { code, message: message.into(), data: Value::Null }
|
||||||
|
}
|
||||||
|
/// The host refused (window, origin, params, state).
|
||||||
|
pub fn host(message: impl Into<String>) -> Fail {
|
||||||
|
Fail::new(-1, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<String> for Fail {
|
||||||
|
fn from(s: String) -> Fail {
|
||||||
|
Fail::host(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Descriptor {
|
||||||
|
pub method: String,
|
||||||
|
pub title: String,
|
||||||
|
pub description: String,
|
||||||
|
pub kind: String,
|
||||||
|
pub network: bool,
|
||||||
|
pub destructive: bool,
|
||||||
|
pub json: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Pending = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Value, Fail>>>>>;
|
||||||
|
|
||||||
|
pub struct Running {
|
||||||
|
child: Mutex<Option<CommandChild>>,
|
||||||
|
secret: [u8; 32],
|
||||||
|
pending: Pending,
|
||||||
|
next: AtomicU64,
|
||||||
|
alive: Arc<AtomicBool>,
|
||||||
|
pub version: String,
|
||||||
|
pub protocol: String,
|
||||||
|
pub methods: Vec<Descriptor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Running {
|
||||||
|
pub fn kind(&self, method: &str) -> Option<Kind> {
|
||||||
|
self.methods.iter().find(|d| d.method == method).and_then(|d| Kind::parse(&d.kind))
|
||||||
|
}
|
||||||
|
pub fn descriptor(&self, method: &str) -> Option<&Descriptor> {
|
||||||
|
self.methods.iter().find(|d| d.method == method)
|
||||||
|
}
|
||||||
|
pub fn mint(&self, method: &str, params: &Value) -> Result<String, String> {
|
||||||
|
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e| e.to_string())?.as_millis() as u64;
|
||||||
|
confirm::mint(&self.secret, method, params, now, &confirm::new_nonce()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(&self, id: u64, method: &str, params: &Value) -> Result<oneshot::Receiver<Result<Value, Fail>>, Fail> {
|
||||||
|
if !self.alive.load(Ordering::SeqCst) {
|
||||||
|
return Err(Fail::host("the storebound sidecar stopped"));
|
||||||
|
}
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.pending.lock().map_err(|_| Fail::host("sidecar state poisoned"))?.insert(id, tx);
|
||||||
|
let mut line = serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })).map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
line.push(b'\n');
|
||||||
|
let mut child = self.child.lock().map_err(|_| Fail::host("sidecar state poisoned"))?;
|
||||||
|
match child.as_mut() {
|
||||||
|
Some(c) => c.write(&line).map_err(|e| Fail::host(format!("sidecar write: {e}")))?,
|
||||||
|
None => return Err(Fail::host("the storebound sidecar stopped")),
|
||||||
|
}
|
||||||
|
Ok(rx)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn call(&self, method: &str, params: Value) -> Result<Value, Fail> {
|
||||||
|
let id = self.next.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let rx = self.send(id, method, ¶ms)?;
|
||||||
|
rx.await.map_err(|_| Fail::host("the storebound sidecar stopped"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn notify(&self, method: &str, params: Value) {
|
||||||
|
let mut line = match serde_json::to_vec(&json!({ "jsonrpc": "2.0", "method": method, "params": params })) {
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(_) => return,
|
||||||
|
};
|
||||||
|
line.push(b'\n');
|
||||||
|
if let Ok(mut c) = self.child.lock() {
|
||||||
|
if let Some(c) = c.as_mut() {
|
||||||
|
let _ = c.write(&line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn alive(&self) -> bool {
|
||||||
|
self.alive.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kill(&self) {
|
||||||
|
self.alive.store(false, Ordering::SeqCst);
|
||||||
|
if let Ok(mut c) = self.child.lock() {
|
||||||
|
if let Some(c) = c.take() {
|
||||||
|
let _ = c.kill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Sidecar {
|
||||||
|
current: tokio::sync::Mutex<Option<Arc<Running>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Progress of a running request, forwarded to the main window as `sidecar-progress`.
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
struct Progress {
|
||||||
|
params: Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sidecar {
|
||||||
|
/// The running sidecar, started (and greeted) if needed.
|
||||||
|
pub async fn get<R: Runtime>(&self, app: &AppHandle<R>) -> Result<Arc<Running>, Fail> {
|
||||||
|
let mut cur = self.current.lock().await;
|
||||||
|
if let Some(r) = cur.as_ref() {
|
||||||
|
if r.alive() {
|
||||||
|
return Ok(r.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let r = Arc::new(start(app).await?);
|
||||||
|
*cur = Some(r.clone());
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn shutdown(&self) {
|
||||||
|
if let Some(r) = self.current.lock().await.take() {
|
||||||
|
r.kill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-async variant for the exit path (the event loop is ending).
|
||||||
|
pub fn shutdown_now(&self) {
|
||||||
|
if let Ok(mut cur) = self.current.try_lock() {
|
||||||
|
if let Some(r) = cur.take() {
|
||||||
|
r.kill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tools the app manages in its data folder (Dependencies screen): `tools/bin` (ffmpeg, ffprobe) goes in front of
|
||||||
|
/// PATH for every storebound command, `tools/chrome/<executable>` is the Chrome for Testing it renders with. Only
|
||||||
|
/// paths that exist are passed.
|
||||||
|
pub fn managed_tool_env(data_dir: &std::path::Path) -> Vec<(String, String)> {
|
||||||
|
let mut env = Vec::new();
|
||||||
|
let bin = data_dir.join("tools").join("bin");
|
||||||
|
if bin.is_dir() {
|
||||||
|
env.push(("STOREBOUND_TOOL_PATH".to_string(), bin.to_string_lossy().to_string()));
|
||||||
|
}
|
||||||
|
let chrome = data_dir.join("tools").join("chrome").join(policy::chrome_executable());
|
||||||
|
if chrome.is_file() {
|
||||||
|
env.push(("STOREBOUND_CHROME".to_string(), chrome.to_string_lossy().to_string()));
|
||||||
|
}
|
||||||
|
env
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn start<R: Runtime>(app: &AppHandle<R>) -> Result<Running, Fail> {
|
||||||
|
let tool_env = app.path().app_data_dir().map(|d| managed_tool_env(&d)).unwrap_or_default();
|
||||||
|
let cmd = app
|
||||||
|
.shell()
|
||||||
|
.sidecar(policy::SIDECAR)
|
||||||
|
.map_err(|e| Fail::host(format!("sidecar missing: {e} (bun tools/build-sidecars.ts --host)")))?
|
||||||
|
.args(policy::SIDECAR_ARGS)
|
||||||
|
.envs(tool_env)
|
||||||
|
.set_raw_out(true)
|
||||||
|
.set_process_group(true);
|
||||||
|
let (mut rx, child) = cmd.spawn().map_err(|e| Fail::host(format!("sidecar did not start: {e}")))?;
|
||||||
|
let pending: Pending = Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
let alive = Arc::new(AtomicBool::new(true));
|
||||||
|
|
||||||
|
let (p, a, handle) = (pending.clone(), alive.clone(), app.clone());
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
let mut out: Vec<u8> = Vec::new();
|
||||||
|
let mut err: Vec<u8> = Vec::new();
|
||||||
|
while let Some(ev) = rx.recv().await {
|
||||||
|
match ev {
|
||||||
|
CommandEvent::Stdout(bytes) => {
|
||||||
|
out.extend_from_slice(&bytes);
|
||||||
|
while let Some(nl) = out.iter().position(|b| *b == b'\n') {
|
||||||
|
let line: Vec<u8> = out.drain(..=nl).collect();
|
||||||
|
route(&handle, &p, &line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CommandEvent::Stderr(bytes) => {
|
||||||
|
err.extend_from_slice(&bytes);
|
||||||
|
while let Some(nl) = err.iter().position(|b| *b == b'\n') {
|
||||||
|
let line: Vec<u8> = err.drain(..=nl).collect();
|
||||||
|
if cfg!(debug_assertions) {
|
||||||
|
eprint!("[sidecar] {}", String::from_utf8_lossy(&line));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CommandEvent::Terminated(_) | CommandEvent::Error(_) => break,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.store(false, Ordering::SeqCst);
|
||||||
|
if let Ok(mut map) = p.lock() {
|
||||||
|
for (_, tx) in map.drain() {
|
||||||
|
let _ = tx.send(Err(Fail::host("the storebound sidecar stopped")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let secret = confirm::new_secret()?;
|
||||||
|
let mut running = Running {
|
||||||
|
child: Mutex::new(Some(child)),
|
||||||
|
secret,
|
||||||
|
pending,
|
||||||
|
next: AtomicU64::new(1),
|
||||||
|
alive,
|
||||||
|
version: String::new(),
|
||||||
|
protocol: String::new(),
|
||||||
|
methods: Vec::new(),
|
||||||
|
};
|
||||||
|
let hello = tokio::time::timeout(
|
||||||
|
Duration::from_secs(20),
|
||||||
|
running.call("session.hello", json!({ "secret": confirm::hex(&secret), "client": { "name": "storebound-desktop", "version": env!("CARGO_PKG_VERSION") } })),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| Fail::host("the storebound sidecar did not answer session.hello"))??;
|
||||||
|
running.protocol = hello["protocol"].as_str().unwrap_or_default().to_string();
|
||||||
|
running.version = hello["server"]["version"].as_str().unwrap_or_default().to_string();
|
||||||
|
if running.protocol != "storebound-desktop/1" {
|
||||||
|
running.kill();
|
||||||
|
return Err(Fail::host(format!("unsupported sidecar protocol '{}'", running.protocol)));
|
||||||
|
}
|
||||||
|
running.methods = hello["methods"]
|
||||||
|
.as_array()
|
||||||
|
.map(|a| {
|
||||||
|
a.iter()
|
||||||
|
.map(|m| Descriptor {
|
||||||
|
method: m["method"].as_str().unwrap_or_default().into(),
|
||||||
|
title: m["title"].as_str().unwrap_or_default().into(),
|
||||||
|
description: m["description"].as_str().unwrap_or_default().into(),
|
||||||
|
kind: m["kind"].as_str().unwrap_or_default().into(),
|
||||||
|
network: m["network"].as_bool().unwrap_or(true),
|
||||||
|
destructive: m["destructive"].as_bool().unwrap_or(true),
|
||||||
|
json: m["json"].as_bool().unwrap_or(false),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
Ok(running)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route<R: Runtime>(app: &AppHandle<R>, pending: &Pending, line: &[u8]) {
|
||||||
|
let Ok(msg) = serde_json::from_slice::<Value>(line) else { return };
|
||||||
|
if let Some(id) = msg.get("id").and_then(Value::as_u64) {
|
||||||
|
let tx = pending.lock().ok().and_then(|mut m| m.remove(&id));
|
||||||
|
if let Some(tx) = tx {
|
||||||
|
let res = match msg.get("error") {
|
||||||
|
Some(e) => Err(Fail {
|
||||||
|
code: e["code"].as_i64().unwrap_or(-32603),
|
||||||
|
message: e["message"].as_str().unwrap_or("error").to_string(),
|
||||||
|
data: e.get("data").cloned().unwrap_or(Value::Null),
|
||||||
|
}),
|
||||||
|
None => Ok(msg.get("result").cloned().unwrap_or(Value::Null)),
|
||||||
|
};
|
||||||
|
let _ = tx.send(res);
|
||||||
|
}
|
||||||
|
} else if msg.get("method").and_then(Value::as_str) == Some("progress") {
|
||||||
|
let _ = app.emit_to(policy::MAIN, "sidecar-progress", Progress { params: msg["params"].clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
74
apps/desktop/src-tauri/src/store.rs
Normal file
74
apps/desktop/src-tauri/src/store.rs
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
//! The app's own small state in its data folder: the project list and account labels (never secrets). Written
|
||||||
|
//! atomically (temp file, then rename) so a crash never leaves half a file.
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::accounts::Account;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Project {
|
||||||
|
pub id: String,
|
||||||
|
/// Absolute folder that holds storebound.config.ts.
|
||||||
|
pub path: String,
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub play_account: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub apple_account: Option<String>,
|
||||||
|
pub added: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct State {
|
||||||
|
#[serde(default)]
|
||||||
|
pub projects: Vec<Project>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub accounts: Vec<Account>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const FILE: &str = "state.json";
|
||||||
|
|
||||||
|
pub fn load(dir: &Path) -> State {
|
||||||
|
fs::read_to_string(dir.join(FILE)).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(dir: &Path, state: &State) -> Result<(), String> {
|
||||||
|
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||||
|
let tmp: PathBuf = dir.join(format!("{FILE}.tmp"));
|
||||||
|
let json = serde_json::to_string_pretty(state).map_err(|e| e.to_string())?;
|
||||||
|
fs::write(&tmp, json + "\n").map_err(|e| e.to_string())?;
|
||||||
|
fs::rename(&tmp, dir.join(FILE)).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Random id (hex) for projects and accounts.
|
||||||
|
pub fn new_id() -> Result<String, String> {
|
||||||
|
let mut b = [0u8; 8];
|
||||||
|
getrandom::fill(&mut b).map_err(|e| e.to_string())?;
|
||||||
|
Ok(crate::confirm::hex(&b))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Current time as an RFC 3339 UTC string, without a date crate.
|
||||||
|
pub fn now_iso() -> String {
|
||||||
|
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||||
|
iso_from_unix(secs)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn iso_from_unix(secs: u64) -> String {
|
||||||
|
let days = (secs / 86_400) as i64;
|
||||||
|
let rem = secs % 86_400;
|
||||||
|
// civil-from-days (Howard Hinnant)
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z - era * 146_097;
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let y = yoe + era * 400;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||||
|
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||||
|
let y = if m <= 2 { y + 1 } else { y };
|
||||||
|
format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
|
||||||
|
}
|
||||||
85
apps/desktop/src-tauri/tauri.conf.json
Normal file
85
apps/desktop/src-tauri/tauri.conf.json
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
|
"productName": "storebound",
|
||||||
|
"mainBinaryName": "storebound-desktop",
|
||||||
|
"version": "../package.json",
|
||||||
|
"identifier": "dev.storebound.desktop",
|
||||||
|
"build": {
|
||||||
|
"frontendDist": "../dist",
|
||||||
|
"devUrl": "http://127.0.0.1:1420",
|
||||||
|
"beforeDevCommand": "bun run dev",
|
||||||
|
"beforeBuildCommand": "bun run build"
|
||||||
|
},
|
||||||
|
"app": {
|
||||||
|
"windows": [
|
||||||
|
{
|
||||||
|
"label": "main",
|
||||||
|
"title": "storebound",
|
||||||
|
"width": 1200,
|
||||||
|
"height": 780,
|
||||||
|
"minWidth": 880,
|
||||||
|
"minHeight": 560,
|
||||||
|
"resizable": true,
|
||||||
|
"center": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"security": {
|
||||||
|
"csp": {
|
||||||
|
"default-src": "'self'",
|
||||||
|
"script-src": "'self'",
|
||||||
|
"style-src": "'self'",
|
||||||
|
"img-src": "'self' data:",
|
||||||
|
"font-src": "'self'",
|
||||||
|
"connect-src": "ipc: http://ipc.localhost",
|
||||||
|
"object-src": "'none'",
|
||||||
|
"base-uri": "'none'",
|
||||||
|
"frame-src": "'none'",
|
||||||
|
"form-action": "'none'"
|
||||||
|
},
|
||||||
|
"devCsp": {
|
||||||
|
"default-src": "'self'",
|
||||||
|
"script-src": "'self'",
|
||||||
|
"style-src": "'self' 'unsafe-inline'",
|
||||||
|
"img-src": "'self' data:",
|
||||||
|
"font-src": "'self'",
|
||||||
|
"connect-src": "ipc: http://ipc.localhost ws://127.0.0.1:1420 http://127.0.0.1:1420",
|
||||||
|
"object-src": "'none'",
|
||||||
|
"base-uri": "'none'",
|
||||||
|
"frame-src": "'none'",
|
||||||
|
"form-action": "'none'"
|
||||||
|
},
|
||||||
|
"freezePrototype": true,
|
||||||
|
"capabilities": ["main-window"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"bundle": {
|
||||||
|
"active": true,
|
||||||
|
"targets": "all",
|
||||||
|
"category": "DeveloperTool",
|
||||||
|
"shortDescription": "Every game's releases on both stores in one window",
|
||||||
|
"copyright": "MIT license, storebound contributors",
|
||||||
|
"externalBin": ["binaries/storebound"],
|
||||||
|
"createUpdaterArtifacts": false,
|
||||||
|
"icon": [
|
||||||
|
"icons/32x32.png",
|
||||||
|
"icons/128x128.png",
|
||||||
|
"icons/128x128@2x.png",
|
||||||
|
"icons/icon.icns",
|
||||||
|
"icons/icon.ico"
|
||||||
|
],
|
||||||
|
"macOS": {
|
||||||
|
"minimumSystemVersion": "11.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"plugins": {
|
||||||
|
"deep-link": {
|
||||||
|
"desktop": {
|
||||||
|
"schemes": ["storebound"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"updater": {
|
||||||
|
"endpoints": ["https://storebound.dev/desktop/latest.json"],
|
||||||
|
"pubkey": "PLACEHOLDER-minisign-public-key-set-in-D5"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
98
apps/desktop/src-tauri/tests/accounts.rs
Normal file
98
apps/desktop/src-tauri/tests/accounts.rs
Normal file
|
|
@ -0,0 +1,98 @@
|
||||||
|
//! Account handling: what is stored where, what is shown, and the key checks. No real keys anywhere.
|
||||||
|
use serde_json::{json, Map};
|
||||||
|
use storebound_desktop::accounts::*;
|
||||||
|
use storebound_desktop::commands::{dialog_excerpt, dialog_summary, has_config, tilde};
|
||||||
|
use storebound_desktop::sidecar::managed_tool_env;
|
||||||
|
use storebound_desktop::store::{self, Project, State};
|
||||||
|
|
||||||
|
const FAKE_PEM: &str = "-----BEGIN PRIVATE KEY-----\nnot-a-real-key\n-----END PRIVATE KEY-----";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shown_metadata_carries_no_secret() {
|
||||||
|
let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into() };
|
||||||
|
let v = serde_json::to_value(&a).unwrap();
|
||||||
|
assert_eq!(v.as_object().unwrap().keys().cloned().collect::<Vec<_>>(), vec!["created", "id", "kind", "label"]);
|
||||||
|
assert_eq!(v["kind"], "play");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn secrets_map_to_the_cli_env_names() {
|
||||||
|
let mut m = Map::new();
|
||||||
|
Secret::Apple { key_id: "ABCDEFGH12".into(), issuer_id: "00000000-0000-0000-0000-000000000000".into(), p8: FAKE_PEM.into() }.to_credentials(&mut m);
|
||||||
|
Secret::Play { service_account: "{}".into() }.to_credentials(&mut m);
|
||||||
|
assert_eq!(m.keys().cloned().collect::<Vec<_>>(), vec!["ASC_ISSUER_ID", "ASC_KEY_ID", "ASC_P8", "PLAY_SERVICE_ACCOUNT"]);
|
||||||
|
let s = Secret::Play { service_account: "{}".into() };
|
||||||
|
let back: Secret = serde_json::from_str(&serde_json::to_string(&s).unwrap()).unwrap();
|
||||||
|
assert_eq!(back, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn key_checks() {
|
||||||
|
let sa = json!({ "type": "service_account", "client_email": "bot@example.com", "private_key": FAKE_PEM }).to_string();
|
||||||
|
assert!(check_service_account(&sa).is_ok());
|
||||||
|
assert!(check_service_account("{\"client_email\":\"x@example.com\"}").is_err());
|
||||||
|
assert!(check_service_account("not json").is_err());
|
||||||
|
assert_eq!(check_key_id(" ABCDEFGH12 ").unwrap(), "ABCDEFGH12");
|
||||||
|
assert!(check_key_id("abc").is_err());
|
||||||
|
assert!(check_key_id("abcdefgh12").is_err());
|
||||||
|
let upper = "00000000-0000-0000-0000-00000000000A";
|
||||||
|
assert_eq!(check_issuer_id(upper).unwrap(), upper.to_ascii_lowercase());
|
||||||
|
assert!(check_issuer_id("0000-0000").is_err());
|
||||||
|
assert!(check_p8(FAKE_PEM).is_ok());
|
||||||
|
assert!(check_p8("hello").is_err());
|
||||||
|
assert!(check_label("").is_err());
|
||||||
|
assert!(check_label("a\u{7}").is_err());
|
||||||
|
assert!(check_label(&"x".repeat(61)).is_err());
|
||||||
|
assert_eq!(check_label(" Studio ").unwrap(), "Studio");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn state_file_round_trip_is_atomic_and_tolerant() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
assert_eq!(store::load(dir.path()), State::default());
|
||||||
|
let st = State {
|
||||||
|
projects: vec![Project { id: "1".into(), path: "/games/a".into(), name: "A".into(), play_account: Some("p".into()), apple_account: None, added: "2026-10-10T00:00:00Z".into() }],
|
||||||
|
accounts: vec![],
|
||||||
|
};
|
||||||
|
store::save(dir.path(), &st).unwrap();
|
||||||
|
assert_eq!(store::load(dir.path()), st);
|
||||||
|
assert!(!dir.path().join("state.json.tmp").exists());
|
||||||
|
let text = std::fs::read_to_string(dir.path().join("state.json")).unwrap();
|
||||||
|
assert!(text.contains("\"playAccount\": \"p\""));
|
||||||
|
std::fs::write(dir.path().join("state.json"), "{broken").unwrap();
|
||||||
|
assert_eq!(store::load(dir.path()), State::default());
|
||||||
|
assert_eq!(store::iso_from_unix(0), "1970-01-01T00:00:00Z");
|
||||||
|
assert_eq!(store::iso_from_unix(1_700_000_000), "2023-11-14T22:13:20Z");
|
||||||
|
assert_eq!(store::new_id().unwrap().len(), 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn managed_tools_are_passed_only_when_present() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
assert!(managed_tool_env(dir.path()).is_empty());
|
||||||
|
std::fs::create_dir_all(dir.path().join("tools/bin")).unwrap();
|
||||||
|
let env = managed_tool_env(dir.path());
|
||||||
|
assert_eq!(env.len(), 1);
|
||||||
|
assert_eq!(env[0].0, "STOREBOUND_TOOL_PATH");
|
||||||
|
assert!(env[0].1.ends_with("bin"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn confirm_dialog_text() {
|
||||||
|
let s = dialog_summary("Push Play listing text", "Title and descriptions.", "Prism Puddle", true, true);
|
||||||
|
assert!(s.starts_with("Push Play listing text · Prism Puddle"));
|
||||||
|
assert!(s.contains("not public until you submit"));
|
||||||
|
assert!(s.contains("replaces"));
|
||||||
|
let out: String = (1..=40).map(|i| format!("line {i}\n")).collect();
|
||||||
|
let ex = dialog_excerpt(&out);
|
||||||
|
assert!(ex.starts_with("(12 earlier lines"));
|
||||||
|
assert!(ex.ends_with("line 40"));
|
||||||
|
assert!(dialog_excerpt(&"x".repeat(5000)).chars().count() < 2_500);
|
||||||
|
assert_eq!(tilde("would write /home/you/a/index.html", Some("/home/you/")), "would write ~/a/index.html");
|
||||||
|
assert_eq!(tilde("/x", None), "/x");
|
||||||
|
assert_eq!(tilde("/x", Some("/")), "/x");
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
assert!(!has_config(dir.path()));
|
||||||
|
std::fs::write(dir.path().join("storebound.config.ts"), "export default {}").unwrap();
|
||||||
|
assert!(has_config(dir.path()));
|
||||||
|
}
|
||||||
43
apps/desktop/src-tauri/tests/confirm.rs
Normal file
43
apps/desktop/src-tauri/tests/confirm.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
//! The host mints exactly the tokens the sidecar verifies: same canonical JSON, same HMAC, same shape as
|
||||||
|
//! cli/lib/confirm-token.ts. The vector is shared with tests/serve.test.ts in the repository root.
|
||||||
|
use serde_json::json;
|
||||||
|
use storebound_desktop::confirm::*;
|
||||||
|
|
||||||
|
fn secret() -> Vec<u8> {
|
||||||
|
(0u8..32).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shared_vector() {
|
||||||
|
let p = json!({ "project": "/tmp/game", "args": { "only": "en-US,tr", "b": [1, true, null, "ü\"\n"] } });
|
||||||
|
assert_eq!(canonical(&p).unwrap(), "{\"args\":{\"b\":[1,true,null,\"ü\\\"\\n\"],\"only\":\"en-US,tr\"},\"project\":\"/tmp/game\"}");
|
||||||
|
assert_eq!(mac(&secret(), "play.listing", &p, 1_700_000_060_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap(), "JhSxUL2ej4cm4yrmlcA23rTCPq3YMKJthbB7n6aixxw");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn canonical_rules() {
|
||||||
|
assert_eq!(canonical(&json!({ "b": 1, "a": [true, null, "x"], "c": { "z": "" } })).unwrap(), "{\"a\":[true,null,\"x\"],\"b\":1,\"c\":{\"z\":\"\"}}");
|
||||||
|
assert!(canonical(&json!({ "f": 0.5 })).is_err());
|
||||||
|
assert!(canonical(&json!({ "f": 9_007_199_254_740_992u64 })).is_err());
|
||||||
|
assert_eq!(canonical(&json!(-9_007_199_254_740_991i64)).unwrap(), "-9007199254740991");
|
||||||
|
// keys sort by UTF-16 code units like JavaScript: "\u{e9}" (U+00E9) after "z", astral after BMP private use
|
||||||
|
assert_eq!(canonical(&json!({ "é": 1, "z": 2, "A": 3 })).unwrap(), "{\"A\":3,\"z\":2,\"é\":1}");
|
||||||
|
assert_eq!(canonical(&json!("\u{1}\t</")).unwrap(), "\"\\u0001\\t</\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn minted_tokens_have_the_sidecar_shape() {
|
||||||
|
let p = json!({ "project": "/p", "args": {} });
|
||||||
|
let t = mint(&secret(), "play.listing", &p, 1_000, "AAAAAAAAAAAAAAAAAAAAAA").unwrap();
|
||||||
|
let parts: Vec<&str> = t.split('.').collect();
|
||||||
|
assert_eq!(parts.len(), 4);
|
||||||
|
assert_eq!(parts[0], "sbt1");
|
||||||
|
assert_eq!(parts[1], (1_000 + TTL_MS).to_string());
|
||||||
|
assert_eq!(parts[3].len(), 43);
|
||||||
|
assert_eq!(parts[3], mac(&secret(), "play.listing", &p, 1_000 + TTL_MS, "AAAAAAAAAAAAAAAAAAAAAA").unwrap());
|
||||||
|
let n = new_nonce().unwrap();
|
||||||
|
assert_eq!(n.len(), 22);
|
||||||
|
assert_ne!(n, new_nonce().unwrap());
|
||||||
|
assert_ne!(new_secret().unwrap(), new_secret().unwrap());
|
||||||
|
assert_eq!(hex(&[0, 15, 255]), "000fff");
|
||||||
|
}
|
||||||
201
apps/desktop/src-tauri/tests/security.rs
Normal file
201
apps/desktop/src-tauri/tests/security.rs
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
//! Security invariants of the desktop shell: capability allow-lists, CSP, the command list, the window / origin
|
||||||
|
//! checks every command runs, what the webview may send to the sidecar, and where links may go.
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use storebound_desktop::policy::*;
|
||||||
|
use storebound_desktop::COMMANDS;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
fn root() -> PathBuf {
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_json(p: &Path) -> Value {
|
||||||
|
serde_json::from_str(&fs::read_to_string(p).unwrap()).unwrap_or_else(|e| panic!("{}: {e}", p.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u(s: &str) -> Url {
|
||||||
|
Url::parse(s).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_capability_for_the_main_window_with_exactly_the_app_commands() {
|
||||||
|
let dir = root().join("capabilities");
|
||||||
|
let files: Vec<PathBuf> = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).collect();
|
||||||
|
assert_eq!(files.len(), 1, "one capability file expected, found {files:?}");
|
||||||
|
let cap = read_json(&files[0]);
|
||||||
|
assert_eq!(cap["identifier"], "main-window");
|
||||||
|
assert_eq!(cap["windows"], json!(["main"]));
|
||||||
|
assert!(cap.get("webviews").is_none(), "no webview-scoped grants");
|
||||||
|
assert!(cap.get("remote").is_none(), "no remote origins");
|
||||||
|
assert_ne!(cap["local"], json!(false));
|
||||||
|
assert!(cap["description"].as_str().unwrap().len() > 80, "capabilities carry a real description");
|
||||||
|
|
||||||
|
let got: BTreeSet<String> = cap["permissions"].as_array().unwrap().iter().map(|p| p.as_str().expect("plain permission ids only").to_string()).collect();
|
||||||
|
let mut want: BTreeSet<String> = COMMANDS.iter().map(|c| format!("allow-{}", c.replace('_', "-"))).collect();
|
||||||
|
want.insert("core:event:allow-listen".into());
|
||||||
|
want.insert("core:event:allow-unlisten".into());
|
||||||
|
assert_eq!(got, want, "capability permissions must be exactly the app commands + event listen");
|
||||||
|
for p in &got {
|
||||||
|
for plugin in ["shell:", "fs:", "dialog:", "opener:", "updater:", "process:", "notification:", "deep-link:", "window-state:", "single-instance:", "http:", "core:webview", "core:window", "core:path", "core:default"] {
|
||||||
|
assert!(!p.starts_with(plugin), "{p}: no plugin or core API is granted to the webview");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_registered_command_is_in_the_list_and_nothing_else() {
|
||||||
|
let lib = fs::read_to_string(root().join("src/lib.rs")).unwrap();
|
||||||
|
let start = lib.find("generate_handler![").unwrap() + "generate_handler![".len();
|
||||||
|
let end = start + lib[start..].find(']').unwrap();
|
||||||
|
let registered: Vec<String> = lib[start..end]
|
||||||
|
.split(',')
|
||||||
|
.map(|s| s.trim().trim_start_matches("commands::").to_string())
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(registered, COMMANDS.iter().map(|s| s.to_string()).collect::<Vec<_>>());
|
||||||
|
// every command checks the caller first
|
||||||
|
let cmds = fs::read_to_string(root().join("src/commands.rs")).unwrap();
|
||||||
|
for c in COMMANDS {
|
||||||
|
let at = cmds.find(&format!("pub fn {c}(")).or_else(|| cmds.find(&format!("pub async fn {c}("))).unwrap_or_else(|| panic!("{c} not in commands.rs"));
|
||||||
|
let body = &cmds[at..];
|
||||||
|
let open = body.find('{').unwrap();
|
||||||
|
let first = body[open + 1..].trim_start();
|
||||||
|
assert!(first.starts_with("guard(&window)?;"), "{c} must start with guard(&window)?");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn csp_is_strict_and_the_config_has_no_backdoors() {
|
||||||
|
let conf = read_json(&root().join("tauri.conf.json"));
|
||||||
|
let csp = &conf["app"]["security"]["csp"];
|
||||||
|
assert_eq!(csp["default-src"], "'self'");
|
||||||
|
assert_eq!(csp["script-src"], "'self'");
|
||||||
|
assert_eq!(csp["style-src"], "'self'");
|
||||||
|
assert_eq!(csp["connect-src"], "ipc: http://ipc.localhost");
|
||||||
|
assert_eq!(csp["object-src"], "'none'");
|
||||||
|
assert_eq!(csp["frame-src"], "'none'");
|
||||||
|
assert_eq!(csp["base-uri"], "'none'");
|
||||||
|
for (k, v) in csp.as_object().unwrap() {
|
||||||
|
let v = v.as_str().unwrap();
|
||||||
|
assert!(!v.contains("unsafe-eval") && !v.contains("unsafe-inline") && !v.contains('*'), "{k}: {v}");
|
||||||
|
assert!(!v.contains("https:") && !v.contains("http://") || v == "ipc: http://ipc.localhost", "{k}: no remote sources: {v}");
|
||||||
|
}
|
||||||
|
assert_eq!(conf["app"]["security"]["capabilities"], json!(["main-window"]));
|
||||||
|
assert_eq!(conf["app"]["security"]["freezePrototype"], json!(true));
|
||||||
|
assert!(conf["app"].get("withGlobalTauri").is_none() || conf["app"]["withGlobalTauri"] == json!(false));
|
||||||
|
let windows = conf["app"]["windows"].as_array().unwrap();
|
||||||
|
assert_eq!(windows.len(), 1);
|
||||||
|
assert_eq!(windows[0]["label"], MAIN);
|
||||||
|
assert!(windows[0].get("url").is_none(), "the main window loads the bundled index only");
|
||||||
|
assert_eq!(conf["bundle"]["externalBin"], json!(["binaries/storebound"]));
|
||||||
|
assert_eq!(conf["plugins"]["deep-link"]["desktop"]["schemes"], json!(["storebound"]));
|
||||||
|
for e in conf["plugins"]["updater"]["endpoints"].as_array().unwrap() {
|
||||||
|
assert!(e.as_str().unwrap().starts_with("https://storebound.dev/"));
|
||||||
|
}
|
||||||
|
assert_eq!(conf["build"]["devUrl"], format!("http://{DEV_HOST}:{DEV_PORT}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn platform_configs_never_replace_the_window_list() {
|
||||||
|
// Tauri merges a platform config's `app.windows` by replacing the whole array (the main window would lose its
|
||||||
|
// label, size or CSP-relevant settings). Keep windows in tauri.conf.json only.
|
||||||
|
for e in fs::read_dir(root()).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
let name = p.file_name().unwrap().to_string_lossy().to_string();
|
||||||
|
if name.starts_with("tauri.") && name.ends_with(".conf.json") && name != "tauri.conf.json" {
|
||||||
|
let c = read_json(&p);
|
||||||
|
assert!(c["app"].get("windows").is_none(), "{name} must not set app.windows");
|
||||||
|
assert!(c["app"]["security"].get("csp").is_none(), "{name} must not change the CSP");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_main_with_local_pages_may_call() {
|
||||||
|
for ok in ["tauri://localhost/", "tauri://localhost/index.html", "http://tauri.localhost/", "https://tauri.localhost/index.html"] {
|
||||||
|
assert!(require_main("main", &u(ok), false).is_ok(), "{ok}");
|
||||||
|
}
|
||||||
|
assert!(require_main("main", &u("http://127.0.0.1:1420/"), true).is_ok());
|
||||||
|
for bad in [
|
||||||
|
"http://127.0.0.1:1420/",
|
||||||
|
"http://localhost:1420/",
|
||||||
|
"https://storebound.dev/",
|
||||||
|
"tauri://evil/",
|
||||||
|
"tauri://localhost:8080/",
|
||||||
|
"http://tauri.localhost:8080/",
|
||||||
|
"http://tauri.localhost.evil.test/",
|
||||||
|
&format!("http://{}@tauri.localhost/", "user"),
|
||||||
|
"file:///tmp/index.html",
|
||||||
|
"data:text/html,hi",
|
||||||
|
] {
|
||||||
|
assert!(require_main("main", &u(bad), false).is_err(), "accepted {bad}");
|
||||||
|
}
|
||||||
|
assert!(require_main("main", &u("http://127.0.0.1:1421/"), true).is_err());
|
||||||
|
assert!(require_main("http://localhost", &u("tauri://localhost/"), false).is_err());
|
||||||
|
assert!(require_main("popup", &u("tauri://localhost/"), false).is_err());
|
||||||
|
assert!(require_main("", &u("tauri://localhost/"), false).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn webview_calls_to_the_sidecar_are_reads_or_dry_runs() {
|
||||||
|
// a write from the webview always becomes a dry run
|
||||||
|
let p = sanitize_js_call("play.listing", Some(Kind::Write), &json!({ "args": { "only": "en-US" } })).unwrap();
|
||||||
|
assert_eq!(p, json!({ "args": { "only": "en-US" }, "dryRun": true }));
|
||||||
|
// the host's keys are refused, so is anything unknown
|
||||||
|
for key in ["confirmToken", "credentials", "dryRun", "project", "projects", "secret", "env"] {
|
||||||
|
let mut o = serde_json::Map::new();
|
||||||
|
o.insert(key.into(), json!(false));
|
||||||
|
assert!(sanitize_js_call("play.listing", Some(Kind::Write), &Value::Object(o.clone())).is_err(), "{key}");
|
||||||
|
assert!(sanitize_js_call("check", Some(Kind::Read), &Value::Object(o)).is_err(), "{key}");
|
||||||
|
}
|
||||||
|
assert!(sanitize_js_call("session.hello", Some(Kind::Session), &json!({})).is_err());
|
||||||
|
assert!(sanitize_js_call("portfolio.status", Some(Kind::Portfolio), &json!({})).is_err());
|
||||||
|
assert!(sanitize_js_call("apple.submit", None, &json!({})).is_err());
|
||||||
|
assert!(sanitize_js_call("check", Some(Kind::Read), &json!([1])).is_err());
|
||||||
|
assert_eq!(sanitize_js_call("system.version", Some(Kind::System), &Value::Null).unwrap(), json!({}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sidecar_starts_with_fixed_arguments_from_one_place() {
|
||||||
|
assert_eq!(SIDECAR_ARGS, ["serve", "--stdio"]);
|
||||||
|
assert_eq!(SIDECAR, "storebound");
|
||||||
|
let mut sites = 0;
|
||||||
|
for e in fs::read_dir(root().join("src")).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
let src = fs::read_to_string(&p).unwrap();
|
||||||
|
let n = src.matches(".sidecar(").count();
|
||||||
|
if n > 0 {
|
||||||
|
assert!(p.ends_with("sidecar.rs"), "{} spawns the sidecar", p.display());
|
||||||
|
assert!(src.contains(".args(policy::SIDECAR_ARGS)"));
|
||||||
|
}
|
||||||
|
assert!(!src.contains(".command("), "{}: no other programs are started", p.display());
|
||||||
|
sites += n;
|
||||||
|
}
|
||||||
|
assert_eq!(sites, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn links_open_only_for_the_consoles_and_the_site() {
|
||||||
|
for ok in ["https://play.google.com/console/", "https://appstoreconnect.apple.com/apps", "https://storebound.dev/docs"] {
|
||||||
|
assert!(external_allowed(&u(ok)), "{ok}");
|
||||||
|
}
|
||||||
|
for bad in [
|
||||||
|
"http://play.google.com/console",
|
||||||
|
"https://play.google.com.evil.test/",
|
||||||
|
&format!("https://{}@appstoreconnect.apple.com/", "user"),
|
||||||
|
"https://storebound.dev:8443/",
|
||||||
|
"file:///etc/passwd",
|
||||||
|
"javascript:alert(1)",
|
||||||
|
"https://evil.test/?https://storebound.dev",
|
||||||
|
] {
|
||||||
|
assert!(!external_allowed(&u(bad)), "{bad}");
|
||||||
|
}
|
||||||
|
assert_eq!(deep_link_screen(&u("storebound://apps")), Some("apps"));
|
||||||
|
assert_eq!(deep_link_screen(&u("storebound://portfolio?x=1")), Some("portfolio"));
|
||||||
|
assert_eq!(deep_link_screen(&u("storebound://write")), None);
|
||||||
|
assert_eq!(deep_link_screen(&u("https://projects")), None);
|
||||||
|
}
|
||||||
156
apps/desktop/src/App.tsx
Normal file
156
apps/desktop/src/App.tsx
Normal file
|
|
@ -0,0 +1,156 @@
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { type Account, api, type AppStatus, errorText, onDeepLink, onProgress, type PortfolioResult, type Project, type SidecarStatus } from './api';
|
||||||
|
import { Accounts } from './screens/Accounts';
|
||||||
|
import { AppFolders } from './screens/AppFolders';
|
||||||
|
import { AppView, type AppTab } from './screens/AppView';
|
||||||
|
import { Dependencies } from './screens/Dependencies';
|
||||||
|
import { Portfolio } from './screens/Portfolio';
|
||||||
|
import { Settings } from './screens/Settings';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* App-centric navigation: Portfolio (every app) -> one App (Releases, Catalog, Listings, Health, Reviews, TestFlight),
|
||||||
|
* plus the workspace screens (app folders, store accounts, settings).
|
||||||
|
*/
|
||||||
|
export type Route =
|
||||||
|
| { screen: 'portfolio' }
|
||||||
|
| { screen: 'app'; appId: string; tab: AppTab }
|
||||||
|
| { screen: 'apps' }
|
||||||
|
| { screen: 'accounts' }
|
||||||
|
| { screen: 'dependencies' }
|
||||||
|
| { screen: 'settings' };
|
||||||
|
|
||||||
|
const WORKSPACE = [['apps', 'App folders'], ['accounts', 'Accounts'], ['dependencies', 'Dependencies'], ['settings', 'Settings']] as const;
|
||||||
|
const DEEP = ['portfolio', 'apps', 'accounts', 'dependencies', 'settings'];
|
||||||
|
|
||||||
|
const ICON = {
|
||||||
|
portfolio: 'M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z',
|
||||||
|
app: 'M7 3h10a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM11 18h2',
|
||||||
|
apps: 'M3 6.5A1.5 1.5 0 0 1 4.5 5H9l2 2h8.5A1.5 1.5 0 0 1 21 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 17.5z',
|
||||||
|
accounts: 'M15 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0zM3 21a8 8 0 0 1 16 0M17 11h4m-2-2v4',
|
||||||
|
dependencies: 'M21 16V8a2 2 0 0 0-1-1.7l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.7l7 4a2 2 0 0 0 2 0l7-4a2 2 0 0 0 1-1.7zM3.3 7 12 12l8.7-5M12 22V12',
|
||||||
|
settings: 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export function Icon({ d }: { d: string }) {
|
||||||
|
return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={d} /></svg>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Mark() {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 32 32" aria-hidden="true">
|
||||||
|
<rect width="32" height="32" rx="8" fill="var(--accent)" />
|
||||||
|
<path d="M16 7v12M10.5 12.5 16 7l5.5 5.5M8 18v5.5h16V18" fill="none" stroke="var(--accent-ink)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Shared app data: app folders, accounts, sidecar state and the last portfolio read. */
|
||||||
|
export interface Data {
|
||||||
|
projects: Project[];
|
||||||
|
accounts: Account[];
|
||||||
|
sidecar: SidecarStatus | null;
|
||||||
|
sidecarError: string | null;
|
||||||
|
portfolio: PortfolioResult | null;
|
||||||
|
portfolioBusy: string | null;
|
||||||
|
portfolioError: string | null;
|
||||||
|
refreshPortfolio: (live?: boolean) => Promise<void>;
|
||||||
|
reload: () => Promise<void>;
|
||||||
|
/** Home folder, for showing paths as ~/... */
|
||||||
|
home: string | null;
|
||||||
|
/** The portfolio entry of an app folder (by project id). */
|
||||||
|
statusOf: (p: Project) => AppStatus | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dev builds only (import.meta.env.DEV is false in release builds, so this is dropped): VITE_START=accounts,
|
||||||
|
* VITE_START=app:catalog ... opens that screen first, for screenshots and manual checks. */
|
||||||
|
function startRoute(projects: Project[]): Route | null {
|
||||||
|
const v = import.meta.env.DEV ? String(import.meta.env.VITE_START ?? '') : '';
|
||||||
|
const [screen, tab] = v.split(':');
|
||||||
|
if (screen === 'app' && projects[0]) return { screen: 'app', appId: projects[0].id, tab: (tab as AppTab) || 'releases' };
|
||||||
|
return DEEP.includes(screen ?? '') ? { screen: screen as 'portfolio' } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function App() {
|
||||||
|
const [route, setRoute] = useState<Route>({ screen: 'portfolio' });
|
||||||
|
const [projects, setProjects] = useState<Project[]>([]);
|
||||||
|
const [accounts, setAccounts] = useState<Account[]>([]);
|
||||||
|
const [sidecar, setSidecar] = useState<SidecarStatus | null>(null);
|
||||||
|
const [sidecarError, setSidecarError] = useState<string | null>(null);
|
||||||
|
const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null);
|
||||||
|
const [portfolioBusy, setPortfolioBusy] = useState<string | null>(null);
|
||||||
|
const [portfolioError, setPortfolioError] = useState<string | null>(null);
|
||||||
|
const [home, setHome] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const reload = useCallback(async () => {
|
||||||
|
const [p, a] = await Promise.all([api.projects(), api.accounts()]);
|
||||||
|
setProjects(prev => { if (!prev.length) { const r = startRoute(p); if (r) setRoute(r); } return p; });
|
||||||
|
setAccounts(a);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const refreshPortfolio = useCallback(async (live = false) => {
|
||||||
|
setPortfolioBusy(live ? 'Reading the stores' : 'Checking'); setPortfolioError(null);
|
||||||
|
try { setPortfolio(await api.portfolio(live)); } catch (e) { setPortfolioError(errorText(e)); } finally { setPortfolioBusy(null); }
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
reload().catch(() => {});
|
||||||
|
api.appInfo().then(i => setHome(i.home), () => {});
|
||||||
|
api.sidecarStatus().then(s => { setSidecar(s); setSidecarError(null); }, e => setSidecarError(errorText(e)));
|
||||||
|
const un = onDeepLink(s => { if (DEEP.includes(s)) setRoute({ screen: s as 'portfolio' }); });
|
||||||
|
const unP = onProgress(p => { if (p.total) setPortfolioBusy(b => (b ? `${b.replace(/ \d+\/\d+$/, '')} ${p.n}/${p.total}` : b)); });
|
||||||
|
return () => { un.then(f => f()); unP.then(f => f()); };
|
||||||
|
}, [reload]);
|
||||||
|
useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]);
|
||||||
|
|
||||||
|
// Keyboard: Cmd/Ctrl+1 portfolio, 2-4 workspace screens.
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return;
|
||||||
|
const order = ['portfolio', 'apps', 'accounts', 'dependencies', 'settings'] as const;
|
||||||
|
const s = order[Number(e.key) - 1];
|
||||||
|
if (s) { e.preventDefault(); setRoute({ screen: s }); }
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey);
|
||||||
|
return () => window.removeEventListener('keydown', onKey);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const statusOf = (p: Project) => portfolio?.apps.find(a => a.project === p.path || a.app?.id === p.path);
|
||||||
|
const data: Data = { projects, accounts, sidecar, sidecarError, portfolio, portfolioBusy, portfolioError, refreshPortfolio, reload, statusOf, home };
|
||||||
|
const current = (r: Route) => (JSON.stringify(r) === JSON.stringify(route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) ? 'page' : undefined);
|
||||||
|
const openApp = (p: Project) => setRoute({ screen: 'app', appId: p.id, tab: route.screen === 'app' ? route.tab : 'releases' });
|
||||||
|
const app = route.screen === 'app' ? projects.find(p => p.id === route.appId) : undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="app">
|
||||||
|
<nav className="side" aria-label="Sections">
|
||||||
|
<div className="brand"><Mark /><span>storebound</span></div>
|
||||||
|
<button className="nav" aria-current={current({ screen: 'portfolio' })} onClick={() => setRoute({ screen: 'portfolio' })} title="Portfolio (Cmd+1)"><Icon d={ICON.portfolio} />Portfolio</button>
|
||||||
|
<div className="side-label" id="apps-label">Apps</div>
|
||||||
|
<div className="side-apps" role="list" aria-labelledby="apps-label">
|
||||||
|
{projects.map(p => (
|
||||||
|
<button key={p.id} role="listitem" className="nav nav-app" aria-current={current({ screen: 'app', appId: p.id, tab: 'releases' })} onClick={() => openApp(p)}>
|
||||||
|
<Icon d={ICON.app} /><span className="nav-text">{p.name}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{!projects.length && <p className="side-empty">No apps yet</p>}
|
||||||
|
</div>
|
||||||
|
<div className="side-label">Workspace</div>
|
||||||
|
{WORKSPACE.map(([s, label], i) => (
|
||||||
|
<button key={s} className="nav" aria-current={current({ screen: s })} onClick={() => setRoute({ screen: s })} title={`${label} (Cmd+${i + 2})`}><Icon d={ICON[s]} />{label}</button>
|
||||||
|
))}
|
||||||
|
<div className="side-foot" aria-live="polite">
|
||||||
|
<span><i className={`dot ${sidecar?.running ? 'on' : sidecarError ? 'off' : ''}`} />{sidecar?.running ? `CLI ${sidecar.version}` : sidecarError ? 'CLI not running' : 'Starting CLI'}</span>
|
||||||
|
<span>{projects.length} app{projects.length === 1 ? '' : 's'} · {accounts.length} account{accounts.length === 1 ? '' : 's'}</span>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<main className="main" id="main">
|
||||||
|
{route.screen === 'portfolio' && <Portfolio data={data} open={openApp} go={s => setRoute({ screen: s })} />}
|
||||||
|
{route.screen === 'app' && app && <AppView data={data} project={app} tab={route.tab} setTab={tab => setRoute({ screen: 'app', appId: app.id, tab })} />}
|
||||||
|
{route.screen === 'apps' && <AppFolders data={data} />}
|
||||||
|
{route.screen === 'accounts' && <Accounts data={data} />}
|
||||||
|
{route.screen === 'dependencies' && <Dependencies data={data} />}
|
||||||
|
{route.screen === 'settings' && <Settings data={data} />}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
53
apps/desktop/src/api.ts
Normal file
53
apps/desktop/src/api.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
// The webview's only way out: the app commands of src-tauri/src/commands.rs. No plugin API is used from here.
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
|
||||||
|
import type { MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol';
|
||||||
|
|
||||||
|
export type {
|
||||||
|
AppIdentity, AppStatus, CatalogParity, MethodDescriptor, PortfolioResult, ProgressParams, ReleaseTrain, StoreRelease, ToolResult,
|
||||||
|
} from '../../../cli/lib/desktop-protocol';
|
||||||
|
|
||||||
|
export interface AppInfo { version: string; identifier: string; platform: string; debug: boolean; home: string | null }
|
||||||
|
export type { ToolStatus } from '../../../cli/lib/tools';
|
||||||
|
export interface LocalTools { tools: import('../../../cli/lib/tools').ToolStatus[] }
|
||||||
|
export interface SidecarStatus { running: boolean; version: string; protocol: string; methods: Pick<MethodDescriptor, 'method' | 'title' | 'description' | 'kind' | 'network' | 'destructive' | 'json'>[]; tools: LocalTools | null }
|
||||||
|
/** An app folder (one storebound.config.ts = one app on iOS and / or Android) and the accounts it uses. */
|
||||||
|
export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string }
|
||||||
|
export type AccountKind = 'play' | 'apple';
|
||||||
|
export interface Account { id: string; label: string; kind: AccountKind; created: string }
|
||||||
|
export interface WriteOutcome { confirmed: boolean; stage: 'dry-run' | 'dialog' | 'done'; dryRun: ToolResult; result?: ToolResult }
|
||||||
|
|
||||||
|
/** What a failed command rejects with (sidecar.rs `Fail`). */
|
||||||
|
export interface Fail { code: number; message: string; data?: unknown }
|
||||||
|
|
||||||
|
export function errorText(e: unknown): string {
|
||||||
|
if (typeof e === 'string') return e;
|
||||||
|
if (e && typeof e === 'object' && 'message' in e && typeof (e as Fail).message === 'string') return (e as Fail).message;
|
||||||
|
return 'Something went wrong';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
appInfo: () => invoke<AppInfo>('app_info'),
|
||||||
|
sidecarStatus: () => invoke<SidecarStatus>('sidecar_status'),
|
||||||
|
/** Reads, or dry runs of writes (the host forces dryRun for writes coming from here). */
|
||||||
|
call: <T = ToolResult>(method: string, projectId?: string, params?: { args?: Record<string, unknown> }) =>
|
||||||
|
invoke<T>('sidecar_call', { method, projectId: projectId ?? null, params: params ?? null }),
|
||||||
|
/** Dry run, native confirm dialog with that dry run, then the real run with a host-minted token. */
|
||||||
|
writeWithConfirm: (method: string, projectId: string, args: Record<string, unknown> = {}) =>
|
||||||
|
invoke<WriteOutcome>('write_with_confirm', { method, projectId, args }),
|
||||||
|
projects: () => invoke<Project[]>('projects_list'),
|
||||||
|
addProject: () => invoke<Project | null>('project_add'),
|
||||||
|
removeProject: (id: string) => invoke<void>('project_remove', { id }),
|
||||||
|
setProjectAccounts: (id: string, play: string | null, apple: string | null) => invoke<Project>('project_set_accounts', { id, play, apple }),
|
||||||
|
accounts: () => invoke<Account[]>('accounts_list'),
|
||||||
|
addPlayAccount: (label: string) => invoke<Account | null>('account_add_play', { label }),
|
||||||
|
addAppleAccount: (label: string, keyId: string, issuerId: string) => invoke<Account | null>('account_add_apple', { label, keyId, issuerId }),
|
||||||
|
removeAccount: (id: string) => invoke<void>('account_remove', { id }),
|
||||||
|
portfolio: (live = false) => invoke<PortfolioResult>('portfolio_status', { live }),
|
||||||
|
openExternal: (url: string) => invoke<void>('open_external', { url }),
|
||||||
|
};
|
||||||
|
|
||||||
|
export const onProgress = (cb: (p: ProgressParams) => void): Promise<UnlistenFn> =>
|
||||||
|
listen<{ params: ProgressParams }>('sidecar-progress', e => cb(e.payload.params));
|
||||||
|
|
||||||
|
export const onDeepLink = (cb: (screen: string) => void): Promise<UnlistenFn> => listen<string>('deep-link', e => cb(e.payload));
|
||||||
11
apps/desktop/src/main.tsx
Normal file
11
apps/desktop/src/main.tsx
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { StrictMode } from 'react';
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
import { App } from './App';
|
||||||
|
import { applyPrefs, loadPrefs } from './prefs';
|
||||||
|
import './styles.css';
|
||||||
|
|
||||||
|
const prefs = loadPrefs();
|
||||||
|
// Dev builds only: VITE_THEME=light|dark forces the theme (screenshots of both themes without clicking).
|
||||||
|
if (import.meta.env.DEV && (import.meta.env.VITE_THEME === 'light' || import.meta.env.VITE_THEME === 'dark')) prefs.theme = import.meta.env.VITE_THEME;
|
||||||
|
applyPrefs(prefs);
|
||||||
|
createRoot(document.getElementById('root')!).render(<StrictMode><App /></StrictMode>);
|
||||||
13
apps/desktop/src/paths.ts
Normal file
13
apps/desktop/src/paths.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
/** Home folder shown as "~", so screenshots and screen shares do not show the account name. */
|
||||||
|
export function shortPath(p: string, home: string | null | undefined): string {
|
||||||
|
if (!home) return p;
|
||||||
|
const h = home.replace(/[\\/]+$/, '');
|
||||||
|
if (p === h) return '~';
|
||||||
|
return p.startsWith(h + '/') || p.startsWith(h + '\\') ? `~${p.slice(h.length)}` : p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every occurrence of the home folder in a log text as "~". */
|
||||||
|
export function tildeText(text: string, home: string | null | undefined): string {
|
||||||
|
const h = home?.replace(/[\\/]+$/, '');
|
||||||
|
return h && h.length > 1 ? text.split(h).join('~') : text;
|
||||||
|
}
|
||||||
31
apps/desktop/src/prefs.ts
Normal file
31
apps/desktop/src/prefs.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
// Per-device UI preferences (theme, motion). Only conveniences live in localStorage; nothing about projects or accounts.
|
||||||
|
export type Theme = 'system' | 'light' | 'dark';
|
||||||
|
export type Motion = 'system' | 'reduce';
|
||||||
|
export interface Prefs { theme: Theme; motion: Motion }
|
||||||
|
|
||||||
|
export const DEFAULT_PREFS: Prefs = { theme: 'system', motion: 'system' };
|
||||||
|
const KEY = 'storebound.prefs.v1';
|
||||||
|
|
||||||
|
export function parsePrefs(raw: string | null): Prefs {
|
||||||
|
try {
|
||||||
|
const v = JSON.parse(raw ?? '{}') as Partial<Prefs>;
|
||||||
|
return {
|
||||||
|
theme: v.theme === 'light' || v.theme === 'dark' ? v.theme : 'system',
|
||||||
|
motion: v.motion === 'reduce' ? 'reduce' : 'system',
|
||||||
|
};
|
||||||
|
} catch { return { ...DEFAULT_PREFS }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadPrefs(): Prefs {
|
||||||
|
try { return parsePrefs(localStorage.getItem(KEY)); } catch { return { ...DEFAULT_PREFS }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function savePrefs(p: Prefs): void {
|
||||||
|
try { localStorage.setItem(KEY, JSON.stringify(p)); } catch { /* private mode: keep it for this run only */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Puts the preferences on <html>: data-theme (light / dark, absent = follow the system) and data-motion. */
|
||||||
|
export function applyPrefs(p: Prefs, root: { dataset: DOMStringMap } = document.documentElement): void {
|
||||||
|
if (p.theme === 'system') delete root.dataset.theme; else root.dataset.theme = p.theme;
|
||||||
|
if (p.motion === 'reduce') root.dataset.motion = 'reduce'; else delete root.dataset.motion;
|
||||||
|
}
|
||||||
88
apps/desktop/src/screens/Accounts.tsx
Normal file
88
apps/desktop/src/screens/Accounts.tsx
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { type Account, api, errorText } from '../api';
|
||||||
|
import type { Data } from '../App';
|
||||||
|
|
||||||
|
const KIND: Record<Account['kind'], string> = { play: 'Google Play', apple: 'App Store Connect' };
|
||||||
|
|
||||||
|
export function Accounts({ data }: { data: Data }) {
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [saved, setSaved] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
|
const [playLabel, setPlayLabel] = useState('');
|
||||||
|
const [appleLabel, setAppleLabel] = useState('');
|
||||||
|
const [keyId, setKeyId] = useState('');
|
||||||
|
const [issuerId, setIssuerId] = useState('');
|
||||||
|
|
||||||
|
const act = async (key: string, fn: () => Promise<Account | null | void>) => {
|
||||||
|
setBusy(key); setError(null); setSaved(null);
|
||||||
|
try {
|
||||||
|
const r = await fn();
|
||||||
|
if (r) setSaved(`Saved "${r.label}" in the system keychain.`);
|
||||||
|
await data.reload();
|
||||||
|
} catch (e) { setError(errorText(e)); } finally { setBusy(null); }
|
||||||
|
};
|
||||||
|
const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel); if (a) setPlayLabel(''); return a; });
|
||||||
|
const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; });
|
||||||
|
const used = (a: Account) => data.projects.filter(p => p.playAccount === a.id || p.appleAccount === a.id).map(p => p.name);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header className="head">
|
||||||
|
<div>
|
||||||
|
<h1>Accounts</h1>
|
||||||
|
<p>Store API keys live in the system keychain (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux). They are never shown again, never written to your app folders and only handed to storebound in memory for a call.</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div className="stack">
|
||||||
|
{error && <div className="notice notice-bad" role="alert">{error}</div>}
|
||||||
|
{saved && <div className="notice notice-ok" role="status">{saved}</div>}
|
||||||
|
<div className="card">
|
||||||
|
{!data.accounts.length ? (
|
||||||
|
<div className="empty"><h2>No accounts</h2><p>Add a Google Play service account or an App Store Connect API key below.</p></div>
|
||||||
|
) : (
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>Name</th><th>Store</th><th>Used by</th><th>Added</th><th><span className="sr">Actions</span></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{data.accounts.map(a => (
|
||||||
|
<tr key={a.id}>
|
||||||
|
<td className="name">{a.label}</td>
|
||||||
|
<td><span className={`tag ${a.kind === 'play' ? 'tag-ok' : 'tag-local'}`}>{KIND[a.kind]}</span></td>
|
||||||
|
<td>{used(a).join(', ') || <span className="tag tag-muted">no project</span>}</td>
|
||||||
|
<td>{a.created.slice(0, 10)}</td>
|
||||||
|
<td style={{ textAlign: 'right' }}><button className="btn btn-quiet" disabled={!!busy} onClick={() => act(`rm-${a.id}`, () => api.removeAccount(a.id))} aria-label={`Remove ${a.label} and delete its key from the keychain`}>Remove</button></td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="grid2">
|
||||||
|
<form className="card card-pad form" onSubmit={e => { e.preventDefault(); addPlay(); }}>
|
||||||
|
<div><h2>Google Play</h2><p className="sub">Service account JSON key with access to your apps in Play Console.</p></div>
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="play-label">Name</label>
|
||||||
|
<input id="play-label" type="text" value={playLabel} onChange={e => setPlayLabel(e.target.value)} placeholder="Studio Play account" maxLength={60} autoComplete="off" />
|
||||||
|
</div>
|
||||||
|
<div><button className="btn btn-primary" type="submit" disabled={!playLabel.trim() || !!busy}>Choose JSON key</button></div>
|
||||||
|
</form>
|
||||||
|
<form className="card card-pad form" onSubmit={e => { e.preventDefault(); addApple(); }}>
|
||||||
|
<div><h2>App Store Connect</h2><p className="sub">Team API key (.p8) from Users and Access, Integrations.</p></div>
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="apple-label">Name</label>
|
||||||
|
<input id="apple-label" type="text" value={appleLabel} onChange={e => setAppleLabel(e.target.value)} placeholder="Studio App Store key" maxLength={60} autoComplete="off" />
|
||||||
|
</div>
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="key-id">Key ID</label>
|
||||||
|
<input id="key-id" type="text" value={keyId} onChange={e => setKeyId(e.target.value.toUpperCase())} placeholder="10 letters or digits" maxLength={10} autoComplete="off" spellCheck={false} />
|
||||||
|
</div>
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor="issuer-id">Issuer ID</label>
|
||||||
|
<input id="issuer-id" type="text" value={issuerId} onChange={e => setIssuerId(e.target.value)} placeholder="UUID shown above the keys" maxLength={36} autoComplete="off" spellCheck={false} />
|
||||||
|
</div>
|
||||||
|
<div><button className="btn btn-primary" type="submit" disabled={!appleLabel.trim() || keyId.length !== 10 || issuerId.length < 36 || !!busy}>Choose .p8 key</button></div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
116
apps/desktop/src/screens/AppFolders.tsx
Normal file
116
apps/desktop/src/screens/AppFolders.tsx
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { api, errorText, onProgress, type Project, type ToolResult, type WriteOutcome } from '../api';
|
||||||
|
import type { Data } from '../App';
|
||||||
|
import { shortPath, tildeText } from '../paths';
|
||||||
|
|
||||||
|
interface Run { title: string; project: string; lines: string[]; result?: ToolResult; outcome?: WriteOutcome; error?: string }
|
||||||
|
|
||||||
|
/** Workspace: the app folders (one storebound.config.ts per app) and which store accounts each app uses. */
|
||||||
|
export function AppFolders({ data }: { data: Data }) {
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
|
const [run, setRun] = useState<Run | null>(null);
|
||||||
|
const logRef = useRef<HTMLPreElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const un = onProgress(p => { if (p.line !== undefined) setRun(r => (r ? { ...r, lines: [...r.lines.slice(-400), p.line!] } : r)); });
|
||||||
|
return () => { un.then(f => f()); };
|
||||||
|
}, []);
|
||||||
|
useEffect(() => { logRef.current?.scrollTo({ top: logRef.current.scrollHeight }); }, [run?.lines.length]);
|
||||||
|
|
||||||
|
const act = async (key: string, fn: () => Promise<void>) => {
|
||||||
|
setBusy(key); setError(null);
|
||||||
|
try { await fn(); } catch (e) { setError(errorText(e)); } finally { setBusy(null); }
|
||||||
|
};
|
||||||
|
const add = () => act('add', async () => { if (await api.addProject()) await data.reload(); });
|
||||||
|
// after an account change the portfolio may read differently
|
||||||
|
const reloadAll = async () => { await data.reload(); };
|
||||||
|
const remove = (p: Project) => act(`rm-${p.id}`, async () => { await api.removeProject(p.id); await data.reload(); });
|
||||||
|
const setAcc = (p: Project, play: string | null, apple: string | null) => act(`acc-${p.id}`, async () => { await api.setProjectAccounts(p.id, play, apple); await reloadAll(); });
|
||||||
|
|
||||||
|
const check = (p: Project) => act(`check-${p.id}`, async () => {
|
||||||
|
setRun({ title: 'Offline check', project: p.name, lines: [] });
|
||||||
|
try { const r = await api.call('check', p.id); setRun(x => x && { ...x, result: r }); } catch (e) { setRun(x => x && { ...x, error: errorText(e) }); }
|
||||||
|
});
|
||||||
|
const gallery = (p: Project) => act(`gallery-${p.id}`, async () => {
|
||||||
|
setRun({ title: 'Review gallery (local file)', project: p.name, lines: [] });
|
||||||
|
try { const o = await api.writeWithConfirm('shots.gallery', p.id); setRun(x => x && { ...x, outcome: o, result: o.result ?? o.dryRun }); } catch (e) { setRun(x => x && { ...x, error: errorText(e) }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Dev builds only: VITE_AUTORUN=gallery starts the confirm flow on the first app once (checks of the native dialog).
|
||||||
|
const autorun = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
const first = data.projects[0];
|
||||||
|
if (!import.meta.env.DEV || import.meta.env.VITE_AUTORUN !== 'gallery' || !first || autorun.current) return;
|
||||||
|
autorun.current = true;
|
||||||
|
gallery(first);
|
||||||
|
}, [data.projects]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
const play = data.accounts.filter(a => a.kind === 'play');
|
||||||
|
const apple = data.accounts.filter(a => a.kind === 'apple');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header className="head">
|
||||||
|
<div>
|
||||||
|
<h1>App folders</h1>
|
||||||
|
<p>One folder per app, with its storebound.config.ts (iOS and Android in the same config). Pick which store accounts each app uses; the keys stay in the system keychain.</p>
|
||||||
|
</div>
|
||||||
|
<div className="actions"><button className="btn btn-primary" onClick={add} disabled={busy === 'add'}>Add app folder</button></div>
|
||||||
|
</header>
|
||||||
|
<div className="stack">
|
||||||
|
{error && <div className="notice notice-bad" role="alert">{error}</div>}
|
||||||
|
{!data.projects.length ? (
|
||||||
|
<div className="card empty"><h2>No app folders</h2><p>Choose a folder that contains storebound.config.ts (run storebound init there first if it has none).</p></div>
|
||||||
|
) : (
|
||||||
|
<div className="card">
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>App</th><th>Google Play account</th><th>App Store Connect account</th><th><span className="sr">Actions</span></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{data.projects.map(p => (
|
||||||
|
<tr key={p.id}>
|
||||||
|
<td><div className="name">{p.name}</div><div className="path selectable" title={p.path}>{shortPath(p.path, data.home)}</div></td>
|
||||||
|
<td>
|
||||||
|
<select aria-label={`Google Play account for ${p.name}`} value={p.playAccount ?? ''} onChange={e => setAcc(p, e.target.value || null, p.appleAccount)}>
|
||||||
|
<option value="">None</option>
|
||||||
|
{play.map(a => <option key={a.id} value={a.id}>{a.label}</option>)}
|
||||||
|
</select>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<select aria-label={`App Store Connect account for ${p.name}`} value={p.appleAccount ?? ''} onChange={e => setAcc(p, p.playAccount, e.target.value || null)}>
|
||||||
|
<option value="">None</option>
|
||||||
|
{apple.map(a => <option key={a.id} value={a.id}>{a.label}</option>)}
|
||||||
|
</select>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<div className="actions" style={{ justifyContent: 'flex-end' }}>
|
||||||
|
<button className="btn" onClick={() => check(p)} disabled={!!busy}>Check</button>
|
||||||
|
<button className="btn" onClick={() => gallery(p)} disabled={!!busy} title="Dry run first, then a confirmation dialog">Review gallery</button>
|
||||||
|
<button className="btn btn-quiet" onClick={() => remove(p)} disabled={!!busy} aria-label={`Remove ${p.name} from the list`}>Remove</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{run && (
|
||||||
|
<div className="card card-pad stack" aria-live="polite">
|
||||||
|
<div>
|
||||||
|
<h2>{run.title} · {run.project}</h2>
|
||||||
|
<p className="sub">
|
||||||
|
{run.error ? 'Failed' : !run.result ? 'Running' : run.outcome
|
||||||
|
? (run.outcome.confirmed ? 'Applied after your confirmation' : run.outcome.stage === 'dialog' ? 'Cancelled in the dialog: nothing was written' : 'The dry run failed: nothing was written')
|
||||||
|
: run.result.ok ? 'Done' : `Exit ${run.result.exitCode}`}
|
||||||
|
{run.result && <> · <code className="selectable">{run.result.command}</code></>}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{run.error && <div className="notice notice-bad">{run.error}</div>}
|
||||||
|
<pre className="log selectable" ref={logRef}>{tildeText(run.result?.output ?? run.lines.join('\n'), data.home) || ' '}</pre>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
92
apps/desktop/src/screens/AppView.tsx
Normal file
92
apps/desktop/src/screens/AppView.tsx
Normal file
|
|
@ -0,0 +1,92 @@
|
||||||
|
import type { Project, ReleaseTrain } from '../api';
|
||||||
|
import type { Data } from '../App';
|
||||||
|
import { phaseText } from './Portfolio';
|
||||||
|
|
||||||
|
export type AppTab = 'releases' | 'catalog' | 'listings' | 'health' | 'reviews' | 'testflight';
|
||||||
|
export const TABS: [AppTab, string][] = [['releases', 'Releases'], ['catalog', 'Catalog'], ['listings', 'Listings'], ['health', 'Health'], ['reviews', 'Reviews'], ['testflight', 'TestFlight']];
|
||||||
|
|
||||||
|
/** What each tab will show, and the CLI command that has it today. */
|
||||||
|
const NEXT: Record<Exclude<AppTab, 'releases' | 'catalog'>, [string, string]> = {
|
||||||
|
listings: ['Store listing text, screenshots and previews per language and store, with the dry-run diff before any upload.', 'storebound check · storebound shots gallery'],
|
||||||
|
health: ['Crash and ANR rates against the store thresholds, worst devices and top issues.', 'storebound health'],
|
||||||
|
reviews: ['Recent reviews on both stores, reply drafts and what still needs an answer.', 'storebound reviews list'],
|
||||||
|
testflight: ['Beta groups, testers and builds with their beta review state.', 'storebound apple testflight status'],
|
||||||
|
};
|
||||||
|
|
||||||
|
function Train({ title, t }: { title: string; t: ReleaseTrain | null }) {
|
||||||
|
return (
|
||||||
|
<div className="card card-pad stack">
|
||||||
|
<div><h2>{title}</h2><p className="sub">{t ? `Version ${t.version}` : 'No version'}</p></div>
|
||||||
|
{t && (
|
||||||
|
<dl className="kv">
|
||||||
|
{(['ios', 'android'] as const).map(s => {
|
||||||
|
const r = t[s];
|
||||||
|
const ph = phaseText(r);
|
||||||
|
return [
|
||||||
|
<dt key={`${s}-k`}>{s === 'ios' ? 'App Store' : 'Google Play'}</dt>,
|
||||||
|
<dd key={`${s}-v`}><span className={`tag tag-${ph.tone}`}>{ph.text}</span>{r?.build && <span className="muted"> build {r.build}</span>}{r?.track && r.track !== 'production' && <span className="muted"> · {r.track}</span>}</dd>,
|
||||||
|
];
|
||||||
|
})}
|
||||||
|
</dl>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AppView({ data, project, tab, setTab }: { data: Data; project: Project; tab: AppTab; setTab: (t: AppTab) => void }) {
|
||||||
|
const e = data.statusOf(project);
|
||||||
|
const ios = e?.app?.platforms.ios, android = e?.app?.platforms.android;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header className="head">
|
||||||
|
<div>
|
||||||
|
<h1>{e?.app?.name ?? project.name}</h1>
|
||||||
|
<p className="actions platforms">
|
||||||
|
<span className={`tag ${ios ? 'tag-local' : 'tag-muted'}`}>iOS {ios ? ios.bundleId : 'not set up'}</span>
|
||||||
|
<span className={`tag ${android ? 'tag-ok' : 'tag-muted'}`}>Android {android ? android.packageName : 'not set up'}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="actions">
|
||||||
|
<button className="btn btn-primary" onClick={() => data.refreshPortfolio(true)} disabled={!!data.portfolioBusy}>{data.portfolioBusy ?? 'Read the stores'}</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div className="tabs" role="tablist" aria-label={`${project.name} sections`}>
|
||||||
|
{TABS.map(([t, label]) => <button key={t} role="tab" aria-selected={tab === t} className="tab" onClick={() => setTab(t)}>{label}</button>)}
|
||||||
|
</div>
|
||||||
|
<div className="stack" role="tabpanel">
|
||||||
|
{data.portfolioError && <div className="notice notice-bad" role="alert">{data.portfolioError}</div>}
|
||||||
|
{tab === 'releases' && (
|
||||||
|
e?.release.source === 'live' ? (
|
||||||
|
<div className="grid2"><Train title="Live" t={e.release.current} /><Train title="Next" t={e.release.next} /></div>
|
||||||
|
) : (
|
||||||
|
<div className="card empty"><h2>Release trains</h2><p>One version across the App Store and Google Play: build, review, TestFlight, phased release and rollout state. Map store accounts to this app in App folders, then read the stores.</p></div>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
{tab === 'catalog' && (
|
||||||
|
<div className="card card-pad stack">
|
||||||
|
<div><h2>In-app catalog</h2><p className="sub">Products and subscriptions are defined once in the config and created on both stores; parity compares them.</p></div>
|
||||||
|
{e?.catalog ? (
|
||||||
|
<dl className="kv">
|
||||||
|
<dt>Products</dt><dd>{e.catalog.products}</dd>
|
||||||
|
<dt>Subscriptions</dt><dd>{e.catalog.subscriptions}</dd>
|
||||||
|
<dt>Compared with</dt><dd>{e.catalog.checked === 'live' ? 'both stores' : 'the config only (read the stores to compare)'}</dd>
|
||||||
|
{e.catalog.checked === 'live' && <>
|
||||||
|
<dt>Missing on iOS</dt><dd>{e.catalog.missingIos.join(', ') || 'none'}</dd>
|
||||||
|
<dt>Missing on Android</dt><dd>{e.catalog.missingAndroid.join(', ') || 'none'}</dd>
|
||||||
|
<dt>Only on one store</dt><dd>{[...e.catalog.onlyIos.map(x => `${x} (iOS)`), ...e.catalog.onlyAndroid.map(x => `${x} (Android)`)].join(', ') || 'none'}</dd>
|
||||||
|
</>}
|
||||||
|
</dl>
|
||||||
|
) : <p className="sub">Not checked yet.</p>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{tab !== 'releases' && tab !== 'catalog' && (
|
||||||
|
<div className="card empty">
|
||||||
|
<h2>{TABS.find(x => x[0] === tab)![1]}</h2>
|
||||||
|
<p>{NEXT[tab][0]}</p>
|
||||||
|
<p className="muted">Today in a terminal: <code className="selectable">{NEXT[tab][1]}</code></p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
69
apps/desktop/src/screens/Dependencies.tsx
Normal file
69
apps/desktop/src/screens/Dependencies.tsx
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { api, errorText, type ToolStatus } from '../api';
|
||||||
|
import type { Data } from '../App';
|
||||||
|
import { shortPath } from '../paths';
|
||||||
|
|
||||||
|
/** Status tag of one tool. */
|
||||||
|
export function toolState(t: ToolStatus): { text: string; tone: 'ok' | 'warn' | 'local' } {
|
||||||
|
if (!t.found) return { text: 'missing', tone: 'warn' };
|
||||||
|
return t.source === 'app' ? { text: 'app copy', tone: 'local' } : { text: 'installed', tone: 'ok' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Local tools storebound uses for screenshots, previews, icons and captures. ffmpeg and Chrome for Testing will be
|
||||||
|
* downloadable into the app's data folder (checksum or signature verified, never system-wide, never bundled);
|
||||||
|
* Xcode and the Android SDK are link-out only. Sources and licenses: docs/desktop.md.
|
||||||
|
*/
|
||||||
|
export function Dependencies({ data }: { data: Data }) {
|
||||||
|
const [tools, setTools] = useState<ToolStatus[] | null>(data.sidecar?.tools?.tools ?? null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
setBusy(true); setError(null);
|
||||||
|
try { setTools((await api.call<{ tools: ToolStatus[] }>('system.tools')).tools); } catch (e) { setError(errorText(e)); } finally { setBusy(false); }
|
||||||
|
}, []);
|
||||||
|
useEffect(() => { if (!tools) refresh(); }, [tools, refresh]);
|
||||||
|
const open = (url: string) => api.openExternal(url).catch(e => setError(errorText(e)));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header className="head">
|
||||||
|
<div>
|
||||||
|
<h1>Dependencies</h1>
|
||||||
|
<p>Local tools for screenshots, app previews, icons and simulator or emulator captures. Store work (listings, products, releases) needs none of them.</p>
|
||||||
|
</div>
|
||||||
|
<div className="actions"><button className="btn" onClick={refresh} disabled={busy}>{busy ? 'Checking' : 'Check again'}</button></div>
|
||||||
|
</header>
|
||||||
|
<div className="stack">
|
||||||
|
{error && <div className="notice notice-bad" role="alert">{error}</div>}
|
||||||
|
<div className="card">
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>Tool</th><th>Status</th><th>Version</th><th>Used for</th><th><span className="sr">Get it</span></th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{(tools ?? []).map(t => {
|
||||||
|
const st = toolState(t);
|
||||||
|
return (
|
||||||
|
<tr key={t.id}>
|
||||||
|
<td><div className="name">{t.name}</div>{t.path && <div className="path selectable" title={t.path}>{shortPath(t.path, data.home)}</div>}</td>
|
||||||
|
<td><span className={`tag tag-${st.tone}`}>{st.text}</span></td>
|
||||||
|
<td className="selectable">{t.version ?? ''}</td>
|
||||||
|
<td className="muted">{t.usedFor}</td>
|
||||||
|
<td style={{ textAlign: 'right' }}>
|
||||||
|
{t.install.kind === 'download'
|
||||||
|
? <button className="btn" disabled title={`${t.install.note} One-click download comes with the next update.`}>Download</button>
|
||||||
|
: <button className="btn btn-quiet" onClick={() => open(t.install.url)} title={t.install.note}>Get it</button>}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{!tools && <tr><td colSpan={5} className="muted">Checking...</td></tr>}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div className="notice notice-info">
|
||||||
|
ffmpeg and Chrome for Testing will download into this app's data folder only, verified before use, and are never part of the installer. Xcode and the Android SDK come from Apple and Google.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
79
apps/desktop/src/screens/Portfolio.tsx
Normal file
79
apps/desktop/src/screens/Portfolio.tsx
Normal file
|
|
@ -0,0 +1,79 @@
|
||||||
|
import type { AppStatus, Project, ReleaseTrain, StoreRelease } from '../api';
|
||||||
|
import type { Data } from '../App';
|
||||||
|
import { shortPath } from '../paths';
|
||||||
|
|
||||||
|
export type Tone = 'ok' | 'warn' | 'bad' | 'muted' | 'local';
|
||||||
|
|
||||||
|
/** Tag text and tone of one app's offline config check. */
|
||||||
|
export function checkState(e: Pick<AppStatus, 'errors' | 'check'>): { text: string; tone: Tone } {
|
||||||
|
if (e.errors.length || !e.check) return { text: 'not loaded', tone: 'bad' };
|
||||||
|
if (e.check.problems.length) return { text: `${e.check.problems.length} problem${e.check.problems.length === 1 ? '' : 's'}`, tone: 'bad' };
|
||||||
|
if (e.check.warnings.length) return { text: `${e.check.warnings.length} warning${e.check.warnings.length === 1 ? '' : 's'}`, tone: 'warn' };
|
||||||
|
return { text: 'config ok', tone: 'ok' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const PHASE_TONE: Record<StoreRelease['phase'], Tone> = { live: 'ok', rollout: 'local', halted: 'bad', approved: 'local', review: 'warn', rejected: 'bad', testing: 'local', draft: 'muted', other: 'muted' };
|
||||||
|
|
||||||
|
/** "live", "rollout 20%", "review" ... for one store of a train. */
|
||||||
|
export function phaseText(r: StoreRelease | null): { text: string; tone: Tone } {
|
||||||
|
if (!r) return { text: 'not on this store', tone: 'muted' };
|
||||||
|
const pct = r.fraction !== null && r.phase === 'rollout' ? ` ${Math.round(r.fraction * 100)}%` : '';
|
||||||
|
return { text: `${r.phase}${pct}`, tone: PHASE_TONE[r.phase] };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function trainText(t: ReleaseTrain | null, source: 'none' | 'live'): string {
|
||||||
|
if (source === 'none') return 'not read';
|
||||||
|
return t ? t.version : 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Portfolio({ data, open, go }: { data: Data; open: (p: Project) => void; go: (s: 'apps') => void }) {
|
||||||
|
const busy = data.portfolioBusy;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header className="head">
|
||||||
|
<div>
|
||||||
|
<h1>Portfolio</h1>
|
||||||
|
<p>Every app in this workspace on iOS and Android: identity, release train (current and next version on both stores), in-app catalog and config check.</p>
|
||||||
|
</div>
|
||||||
|
<div className="actions">
|
||||||
|
<button className="btn" onClick={() => data.refreshPortfolio(false)} disabled={!!busy || !data.projects.length}>Check configs</button>
|
||||||
|
<button className="btn btn-primary" onClick={() => data.refreshPortfolio(true)} disabled={!!busy || !data.projects.length} title="Read-only: App Store Connect and Google Play status with each app's accounts">{busy ?? 'Read the stores'}</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
{data.portfolioError && <div className="notice notice-bad" role="alert">{data.portfolioError}</div>}
|
||||||
|
{!data.projects.length ? (
|
||||||
|
<div className="card empty">
|
||||||
|
<h2>No apps yet</h2>
|
||||||
|
<p>Add an app folder (one storebound.config.ts per app) to see it here.</p>
|
||||||
|
<button className="btn btn-primary" onClick={() => go('apps')}>Add an app folder</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="card">
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>App</th><th>iOS</th><th>Android</th><th>Live</th><th>Next</th><th>Catalog</th><th>Config</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{data.projects.map(p => {
|
||||||
|
const e = data.statusOf(p);
|
||||||
|
const st = e ? checkState(e) : { text: busy ? 'checking' : 'not checked', tone: 'muted' as const };
|
||||||
|
const ios = e?.app?.platforms.ios, android = e?.app?.platforms.android;
|
||||||
|
const cat = e?.catalog;
|
||||||
|
return (
|
||||||
|
<tr key={p.id}>
|
||||||
|
<td><button className="link name" onClick={() => open(p)}>{e?.app?.name ?? p.name}</button><div className="path selectable" title={p.path}>{shortPath(p.path, data.home)}</div></td>
|
||||||
|
<td className="selectable">{ios ? ios.bundleId : <span className="tag tag-muted">none</span>}{e?.storeErrors.ios && <div className="tag tag-bad" title={e.storeErrors.ios}>unreadable</div>}</td>
|
||||||
|
<td className="selectable">{android ? android.packageName : <span className="tag tag-muted">none</span>}{e?.storeErrors.android && <div className="tag tag-bad" title={e.storeErrors.android}>unreadable</div>}</td>
|
||||||
|
<td className="nowrap">{e ? trainText(e.release.current, e.release.source) : ''}</td>
|
||||||
|
<td className="nowrap">{e ? trainText(e.release.next, e.release.source) : ''}</td>
|
||||||
|
<td>{cat ? <span className={`tag tag-${cat.ok ? (cat.checked === 'live' ? 'ok' : 'muted') : 'warn'}`} title={cat.checked === 'live' ? 'compared with both stores' : 'from the config; read the stores to compare'}>{cat.products} products · {cat.subscriptions} subs</span> : ''}</td>
|
||||||
|
<td><span className={`tag tag-${st.tone}`} title={[...(e?.errors ?? []), ...(e?.check?.problems ?? []), ...(e?.check?.warnings ?? [])].join('\n')}>{st.text}</span></td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{data.portfolio && <p className="foot-note">Last read {new Date(data.portfolio.at).toLocaleString()}</p>}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
51
apps/desktop/src/screens/Settings.tsx
Normal file
51
apps/desktop/src/screens/Settings.tsx
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { type AppInfo, api, errorText } from '../api';
|
||||||
|
import type { Data } from '../App';
|
||||||
|
import { applyPrefs, loadPrefs, type Motion, type Prefs, savePrefs, type Theme } from '../prefs';
|
||||||
|
|
||||||
|
function Seg<T extends string>({ label, value, options, onChange }: { label: string; value: T; options: [T, string][]; onChange: (v: T) => void }) {
|
||||||
|
return (
|
||||||
|
<div className="field" role="group" aria-label={label}>
|
||||||
|
<span className="legend">{label}</span>
|
||||||
|
<div className="seg">
|
||||||
|
{options.map(([v, text]) => <button key={v} type="button" aria-pressed={value === v} onClick={() => onChange(v)}>{text}</button>)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Settings({ data }: { data: Data }) {
|
||||||
|
const [prefs, setPrefs] = useState<Prefs>(loadPrefs);
|
||||||
|
const [info, setInfo] = useState<AppInfo | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
useEffect(() => { api.appInfo().then(setInfo, e => setError(errorText(e))); }, []);
|
||||||
|
const update = (p: Prefs) => { setPrefs(p); savePrefs(p); applyPrefs(p); };
|
||||||
|
const tools = data.sidecar?.tools;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<header className="head"><div><h1>Settings</h1><p>Appearance and what this app runs on.</p></div></header>
|
||||||
|
<div className="stack">
|
||||||
|
{error && <div className="notice notice-bad" role="alert">{error}</div>}
|
||||||
|
<div className="card card-pad form">
|
||||||
|
<h2>Appearance</h2>
|
||||||
|
<Seg<Theme> label="Theme" value={prefs.theme} options={[['system', 'System'], ['light', 'Light'], ['dark', 'Dark']]} onChange={theme => update({ ...prefs, theme })} />
|
||||||
|
<Seg<Motion> label="Motion" value={prefs.motion} options={[['system', 'Follow the system'], ['reduce', 'Reduce']]} onChange={motion => update({ ...prefs, motion })} />
|
||||||
|
</div>
|
||||||
|
<div className="card card-pad stack">
|
||||||
|
<h2>About</h2>
|
||||||
|
<dl className="kv">
|
||||||
|
<dt>App</dt><dd>{info ? `storebound desktop ${info.version}${info.debug ? ' (debug build)' : ''}` : ''}</dd>
|
||||||
|
<dt>CLI</dt><dd>{data.sidecar ? `storebound ${data.sidecar.version} · ${data.sidecar.protocol} · ${data.sidecar.methods.length} methods` : data.sidecarError ?? 'starting'}</dd>
|
||||||
|
<dt>Local tools</dt>
|
||||||
|
<dd>{tools ? `${tools.tools.filter(t => t.found).length} of ${tools.tools.length} found (see Dependencies)` : '...'}</dd>
|
||||||
|
<dt>Telemetry</dt><dd>None. The app only talks to the store APIs through storebound, with your keys.</dd>
|
||||||
|
</dl>
|
||||||
|
<div className="actions">
|
||||||
|
<button className="btn" onClick={() => api.openExternal('https://storebound.dev/').catch(e => setError(errorText(e)))}>storebound.dev</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
175
apps/desktop/src/styles.css
Normal file
175
apps/desktop/src/styles.css
Normal file
|
|
@ -0,0 +1,175 @@
|
||||||
|
/* Tokens shared with storebound.dev (site/style.css): slate neutrals, indigo accent, API / LOCAL / UI / YOU tags. */
|
||||||
|
:root {
|
||||||
|
--bg: #f8fafc;
|
||||||
|
--bg-alt: #f1f5f9;
|
||||||
|
--surface: #ffffff;
|
||||||
|
--ink: #0f172a;
|
||||||
|
--ink-2: #334155;
|
||||||
|
--muted: #475569;
|
||||||
|
--line: #e2e8f0;
|
||||||
|
--line-2: #cbd5e1;
|
||||||
|
--accent: #4f46e5;
|
||||||
|
--accent-ink: #ffffff;
|
||||||
|
--accent-soft: #eef2ff;
|
||||||
|
--code-bg: #0f172a;
|
||||||
|
--code-ink: #e2e8f0;
|
||||||
|
--ok-bg: #dcfce7; --ok-ink: #166534;
|
||||||
|
--local-bg: #e0f2fe; --local-ink: #075985;
|
||||||
|
--warn-bg: #fef3c7; --warn-ink: #92400e;
|
||||||
|
--bad-bg: #fce7f3; --bad-ink: #9d174d;
|
||||||
|
--shadow: 0 1px 2px rgba(15, 23, 42, .06), 0 8px 24px -12px rgba(15, 23, 42, .18);
|
||||||
|
--radius: 12px;
|
||||||
|
--font: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||||
|
--mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
|
||||||
|
--speed: .14s;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) {
|
||||||
|
--bg: #0b1120; --bg-alt: #0f172a; --surface: #131c2f;
|
||||||
|
--ink: #f1f5f9; --ink-2: #cbd5e1; --muted: #a5b4c8; --line: #1e293b; --line-2: #334155;
|
||||||
|
--accent: #818cf8; --accent-ink: #0b1120; --accent-soft: #1e1b4b;
|
||||||
|
--code-bg: #060a14;
|
||||||
|
--ok-bg: #14532d; --ok-ink: #bbf7d0; --local-bg: #0c4a6e; --local-ink: #bae6fd;
|
||||||
|
--warn-bg: #451a03; --warn-ink: #fde68a; --bad-bg: #500724; --bad-ink: #fbcfe8;
|
||||||
|
--shadow: 0 1px 2px rgba(0, 0, 0, .4), 0 12px 32px -16px rgba(0, 0, 0, .7);
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--bg: #0b1120; --bg-alt: #0f172a; --surface: #131c2f;
|
||||||
|
--ink: #f1f5f9; --ink-2: #cbd5e1; --muted: #a5b4c8; --line: #1e293b; --line-2: #334155;
|
||||||
|
--accent: #818cf8; --accent-ink: #0b1120; --accent-soft: #1e1b4b;
|
||||||
|
--code-bg: #060a14;
|
||||||
|
--ok-bg: #14532d; --ok-ink: #bbf7d0; --local-bg: #0c4a6e; --local-ink: #bae6fd;
|
||||||
|
--warn-bg: #451a03; --warn-ink: #fde68a; --bad-bg: #500724; --bad-ink: #fbcfe8;
|
||||||
|
--shadow: 0 1px 2px rgba(0, 0, 0, .4), 0 12px 32px -16px rgba(0, 0, 0, .7);
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) { :root { --speed: 0s; } }
|
||||||
|
:root[data-motion="reduce"] { --speed: 0s; }
|
||||||
|
|
||||||
|
*, *::before, *::after { box-sizing: border-box; }
|
||||||
|
html, body, #root { height: 100%; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--ink);
|
||||||
|
font: 14px/1.5 var(--font);
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
user-select: none;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
input, textarea, .selectable, pre, code { user-select: text; -webkit-user-select: text; }
|
||||||
|
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 6px; }
|
||||||
|
h1, h2, h3 { margin: 0; line-height: 1.2; letter-spacing: -.015em; }
|
||||||
|
p { margin: 0; }
|
||||||
|
code, pre { font-family: var(--mono); font-size: 12.5px; }
|
||||||
|
|
||||||
|
.app { display: grid; grid-template-columns: 220px 1fr; height: 100%; }
|
||||||
|
|
||||||
|
/* sidebar */
|
||||||
|
.side { background: var(--bg-alt); border-right: 1px solid var(--line); display: flex; flex-direction: column; padding: 16px 12px; gap: 4px; }
|
||||||
|
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 15px; padding: 4px 8px 16px; }
|
||||||
|
.brand svg { width: 26px; height: 26px; flex: none; }
|
||||||
|
.nav { all: unset; display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; color: var(--ink-2); font-weight: 550; cursor: pointer; transition: background-color var(--speed) ease; }
|
||||||
|
.nav svg { width: 16px; height: 16px; flex: none; }
|
||||||
|
.nav:hover { background: var(--line); }
|
||||||
|
.nav[aria-current="page"] { background: var(--accent-soft); color: var(--ink); }
|
||||||
|
.nav:focus-visible { outline: 2px solid var(--accent); outline-offset: 0; }
|
||||||
|
.side-label { margin: 14px 10px 4px; font-size: 11px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); }
|
||||||
|
.side-apps { display: grid; gap: 2px; max-height: 40vh; overflow: auto; }
|
||||||
|
.side-empty { color: var(--muted); font-size: 12.5px; padding: 4px 10px; }
|
||||||
|
.nav-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.side-foot { margin-top: auto; padding: 10px 8px 0; border-top: 1px solid var(--line); color: var(--muted); font-size: 12px; display: grid; gap: 4px; }
|
||||||
|
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; background: var(--line-2); }
|
||||||
|
.dot.on { background: #16a34a; }
|
||||||
|
.dot.off { background: #dc2626; }
|
||||||
|
|
||||||
|
/* main */
|
||||||
|
.main { overflow: auto; padding: 28px 32px 40px; }
|
||||||
|
.head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 20px; }
|
||||||
|
.head h1 { font-size: 22px; }
|
||||||
|
.head p { color: var(--muted); margin-top: 4px; max-width: 64ch; }
|
||||||
|
.actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
|
||||||
|
.card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); }
|
||||||
|
.card + .card { margin-top: 16px; }
|
||||||
|
.card-pad { padding: 18px 20px; }
|
||||||
|
.card h2 { font-size: 15px; margin-bottom: 4px; }
|
||||||
|
.card .sub { color: var(--muted); font-size: 13px; }
|
||||||
|
|
||||||
|
.btn { all: unset; display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 32px; padding: 0 14px; border-radius: 8px; font-weight: 600; font-size: 13px; cursor: pointer; border: 1px solid var(--line-2); background: var(--surface); color: var(--ink); transition: background-color var(--speed) ease, border-color var(--speed) ease; white-space: nowrap; }
|
||||||
|
.btn:hover { border-color: var(--muted); }
|
||||||
|
.btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
.btn[disabled] { opacity: .55; cursor: not-allowed; }
|
||||||
|
.btn-primary { background: var(--accent); color: var(--accent-ink); border-color: transparent; }
|
||||||
|
.btn-primary:hover { background: color-mix(in srgb, var(--accent) 88%, var(--ink)); border-color: transparent; }
|
||||||
|
.btn-quiet { border-color: transparent; background: transparent; color: var(--muted); }
|
||||||
|
.btn-quiet:hover { color: var(--ink); background: var(--bg-alt); border-color: transparent; }
|
||||||
|
|
||||||
|
table { width: 100%; border-collapse: collapse; }
|
||||||
|
th, td { text-align: left; padding: 10px 14px; border-bottom: 1px solid var(--line); vertical-align: middle; }
|
||||||
|
th { font-size: 11.5px; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); font-weight: 650; background: var(--bg-alt); }
|
||||||
|
th:first-child { border-top-left-radius: var(--radius); }
|
||||||
|
th:last-child { border-top-right-radius: var(--radius); }
|
||||||
|
tr:last-child td { border-bottom: 0; }
|
||||||
|
td .path { color: var(--muted); font-family: var(--mono); font-size: 12px; overflow-wrap: anywhere; }
|
||||||
|
.name { font-weight: 650; }
|
||||||
|
|
||||||
|
.nowrap { white-space: nowrap; }
|
||||||
|
.tag { white-space: nowrap; display: inline-block; font: 700 10.5px/1 var(--mono); letter-spacing: .05em; padding: 5px 8px; border-radius: 999px; text-transform: uppercase; }
|
||||||
|
.tag-ok { background: var(--ok-bg); color: var(--ok-ink); }
|
||||||
|
.tag-local { background: var(--local-bg); color: var(--local-ink); }
|
||||||
|
.tag-warn { background: var(--warn-bg); color: var(--warn-ink); }
|
||||||
|
.tag-bad { background: var(--bad-bg); color: var(--bad-ink); }
|
||||||
|
.tag-muted { background: var(--bg-alt); color: var(--muted); border: 1px solid var(--line); }
|
||||||
|
|
||||||
|
.empty { text-align: center; padding: 48px 24px; color: var(--muted); }
|
||||||
|
.empty h2 { color: var(--ink); margin-bottom: 6px; }
|
||||||
|
.empty .btn { margin-top: 16px; }
|
||||||
|
|
||||||
|
.form { display: grid; gap: 12px; max-width: 520px; align-content: start; }
|
||||||
|
.field { display: grid; gap: 5px; }
|
||||||
|
.field label, .legend { font-weight: 600; font-size: 13px; }
|
||||||
|
.field .hint { color: var(--muted); font-size: 12px; }
|
||||||
|
input[type="text"], select {
|
||||||
|
font: inherit; color: var(--ink); background: var(--bg); border: 1px solid var(--line-2); border-radius: 8px; min-height: 34px; padding: 0 10px;
|
||||||
|
}
|
||||||
|
input[type="text"]:focus-visible, select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||||
|
select { padding-right: 6px; max-width: 220px; }
|
||||||
|
|
||||||
|
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 16px; align-items: start; }
|
||||||
|
.grid2 > .card + .card { margin-top: 0; }
|
||||||
|
.seg { display: inline-flex; border: 1px solid var(--line-2); border-radius: 9px; overflow: hidden; }
|
||||||
|
.seg button { all: unset; padding: 7px 14px; cursor: pointer; font-weight: 600; font-size: 13px; color: var(--ink-2); }
|
||||||
|
.seg button + button { border-left: 1px solid var(--line-2); }
|
||||||
|
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); }
|
||||||
|
.seg button:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||||
|
|
||||||
|
.notice { border-radius: 10px; padding: 10px 14px; font-size: 13px; }
|
||||||
|
.notice-bad { background: var(--bad-bg); color: var(--bad-ink); }
|
||||||
|
.notice-ok { background: var(--ok-bg); color: var(--ok-ink); }
|
||||||
|
.notice-info { background: var(--accent-soft); color: var(--ink); }
|
||||||
|
.stack { display: grid; gap: 12px; }
|
||||||
|
|
||||||
|
.log { background: var(--code-bg); color: var(--code-ink); border-radius: 10px; padding: 12px 14px; max-height: 240px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; }
|
||||||
|
.kv { display: grid; grid-template-columns: 140px 1fr; gap: 6px 16px; font-size: 13px; }
|
||||||
|
.kv dt { color: var(--muted); }
|
||||||
|
.kv dd { margin: 0; }
|
||||||
|
.link { all: unset; cursor: pointer; color: var(--ink); }
|
||||||
|
.link:hover { color: var(--accent); text-decoration: underline; text-underline-offset: 3px; }
|
||||||
|
.link:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||||
|
.muted { color: var(--muted); }
|
||||||
|
.foot-note { margin-top: 10px; color: var(--muted); font-size: 12px; }
|
||||||
|
.platforms { margin-top: 8px; }
|
||||||
|
.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--line); margin-bottom: 16px; }
|
||||||
|
.tab { all: unset; padding: 8px 12px; font-weight: 600; color: var(--muted); cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px; transition: color var(--speed) ease; }
|
||||||
|
.tab:hover { color: var(--ink); }
|
||||||
|
.tab[aria-selected="true"] { color: var(--ink); border-bottom-color: var(--accent); }
|
||||||
|
.tab:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||||
|
.empty p + p { margin-top: 8px; }
|
||||||
|
.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||||
1
apps/desktop/src/vite-env.d.ts
vendored
Normal file
1
apps/desktop/src/vite-env.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
/// <reference types="vite/client" />
|
||||||
66
apps/desktop/tests/prefs.test.ts
Normal file
66
apps/desktop/tests/prefs.test.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { shortPath, tildeText } from '../src/paths';
|
||||||
|
import { applyPrefs, DEFAULT_PREFS, parsePrefs } from '../src/prefs';
|
||||||
|
import { checkState, phaseText, trainText } from '../src/screens/Portfolio';
|
||||||
|
|
||||||
|
describe('prefs', () => {
|
||||||
|
test('parse is tolerant and only keeps known values', () => {
|
||||||
|
expect(parsePrefs(null)).toEqual(DEFAULT_PREFS);
|
||||||
|
expect(parsePrefs('{broken')).toEqual(DEFAULT_PREFS);
|
||||||
|
expect(parsePrefs('{"theme":"dark","motion":"reduce"}')).toEqual({ theme: 'dark', motion: 'reduce' });
|
||||||
|
expect(parsePrefs('{"theme":"neon","motion":"fast"}')).toEqual(DEFAULT_PREFS);
|
||||||
|
});
|
||||||
|
test('apply sets and clears data attributes', () => {
|
||||||
|
const root = { dataset: {} as DOMStringMap };
|
||||||
|
applyPrefs({ theme: 'light', motion: 'reduce' }, root);
|
||||||
|
expect(root.dataset).toEqual({ theme: 'light', motion: 'reduce' });
|
||||||
|
applyPrefs(DEFAULT_PREFS, root);
|
||||||
|
expect(root.dataset).toEqual({});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('paths', () => {
|
||||||
|
test('home shown as ~', () => {
|
||||||
|
expect(shortPath('/home/you/games/a', '/home/you')).toBe('~/games/a');
|
||||||
|
expect(shortPath('/home/you', '/home/you/')).toBe('~');
|
||||||
|
expect(shortPath('/home/you-2/a', '/home/you')).toBe('/home/you-2/a');
|
||||||
|
expect(shortPath('C:\\Users\\you\\a', 'C:\\Users\\you')).toBe('~\\a');
|
||||||
|
expect(shortPath('/x', null)).toBe('/x');
|
||||||
|
expect(tildeText('in /home/you/a and /home/you/b', '/home/you')).toBe('in ~/a and ~/b');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('portfolio', () => {
|
||||||
|
const base = { project: '/g', ok: false, summary: null, errors: [] as string[] };
|
||||||
|
test('check states', () => {
|
||||||
|
expect(checkState({ ...base, check: null })).toEqual({ text: 'not loaded', tone: 'bad' });
|
||||||
|
expect(checkState({ ...base, check: { ok: false, problems: ['a', 'b'], warnings: [] } })).toEqual({ text: '2 problems', tone: 'bad' });
|
||||||
|
expect(checkState({ ...base, check: { ok: true, problems: [], warnings: ['w'] } })).toEqual({ text: '1 warning', tone: 'warn' });
|
||||||
|
expect(checkState({ ...base, check: { ok: true, problems: [], warnings: [] } })).toEqual({ text: 'config ok', tone: 'ok' });
|
||||||
|
});
|
||||||
|
test('release phases and trains', () => {
|
||||||
|
const r = { store: 'android' as const, version: '2.3.0', build: '231', state: 'inProgress', phase: 'rollout' as const, fraction: 0.2, track: 'production' };
|
||||||
|
expect(phaseText(r)).toEqual({ text: 'rollout 20%', tone: 'local' });
|
||||||
|
expect(phaseText(null)).toEqual({ text: 'not on this store', tone: 'muted' });
|
||||||
|
expect(trainText(null, 'none')).toBe('not read');
|
||||||
|
expect(trainText(null, 'live')).toBe('none');
|
||||||
|
expect(trainText({ version: '2.3.0', ios: null, android: r }, 'live')).toBe('2.3.0');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('webview rules', () => {
|
||||||
|
const src = (f: string) => readFileSync(join(import.meta.dir, '..', f), 'utf8');
|
||||||
|
test('only app commands: no plugin JS APIs, no direct network', () => {
|
||||||
|
for (const f of ['src/api.ts', 'src/App.tsx', 'src/main.tsx', 'src/screens/Portfolio.tsx', 'src/screens/AppView.tsx', 'src/screens/AppFolders.tsx', 'src/screens/Accounts.tsx', 'src/screens/Settings.tsx', 'src/screens/Dependencies.tsx']) {
|
||||||
|
const s = src(f);
|
||||||
|
expect(s).not.toMatch(/@tauri-apps\/plugin-/);
|
||||||
|
expect(s).not.toMatch(/\bfetch\(|XMLHttpRequest|WebSocket|eval\(|new Function|dangerouslySetInnerHTML/);
|
||||||
|
}
|
||||||
|
expect(JSON.parse(src('package.json')).dependencies).toEqual({ '@tauri-apps/api': expect.any(String), react: expect.any(String), 'react-dom': expect.any(String) });
|
||||||
|
});
|
||||||
|
test('the confirm token never appears in the webview code', () => {
|
||||||
|
expect(src('src/api.ts')).not.toMatch(/confirmToken|credentials/);
|
||||||
|
});
|
||||||
|
});
|
||||||
21
apps/desktop/tsconfig.json
Normal file
21
apps/desktop/tsconfig.json
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"types": ["bun"],
|
||||||
|
"strict": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"noImplicitOverride": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"resolveJsonModule": true
|
||||||
|
},
|
||||||
|
"include": ["src", "tests", "vite.config.ts"]
|
||||||
|
}
|
||||||
18
apps/desktop/vite.config.ts
Normal file
18
apps/desktop/vite.config.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
import { defineConfig } from 'vite';
|
||||||
|
|
||||||
|
// Tauri loads the dev server from build.devUrl (http://127.0.0.1:1420) and the built files from ../dist.
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
clearScreen: false,
|
||||||
|
server: { host: '127.0.0.1', port: 1420, strictPort: true, watch: { ignored: ['**/src-tauri/**'] } },
|
||||||
|
build: {
|
||||||
|
target: ['safari15', 'chrome110'],
|
||||||
|
outDir: 'dist',
|
||||||
|
emptyOutDir: true,
|
||||||
|
sourcemap: false,
|
||||||
|
// no inline scripts or styles: the CSP is script-src 'self', style-src 'self'
|
||||||
|
assetsInlineLimit: 0,
|
||||||
|
cssCodeSplit: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
85
docs/desktop.md
Normal file
85
docs/desktop.md
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
# storebound desktop (apps/desktop)
|
||||||
|
|
||||||
|
A Tauri 2 window around the storebound CLI: every app in a workspace, on iOS and Android, in one place. It is in
|
||||||
|
development; this page is for contributors.
|
||||||
|
|
||||||
|
## Shape
|
||||||
|
|
||||||
|
- **One source of logic.** The app never calls a store itself. It runs the storebound CLI as a sidecar
|
||||||
|
(`storebound serve --stdio`, compiled with `bun tools/build-sidecars.ts`) and asks it for everything.
|
||||||
|
- **App-centric.** One app = one product with up to two platforms (iOS bundle id / App Store Connect app id, Android
|
||||||
|
package name), one `storebound.config.ts` per app folder, many apps per workspace. Navigation: Portfolio -> App
|
||||||
|
(Releases, Catalog, Listings, Health, Reviews, TestFlight) plus the workspace screens (App folders, Accounts,
|
||||||
|
Dependencies, Settings).
|
||||||
|
- **Release trains.** A version (for example 2.3.0) spans both stores: iOS build and Android versionCode, per-store
|
||||||
|
state (TestFlight, review, live, phased release, rollout fraction). `portfolio.status` returns per app the current
|
||||||
|
train (highest version live on a store) and the next one (highest version above it anywhere).
|
||||||
|
- **Catalog parity.** Products (and subscriptions, once the config has them) are defined once; `portfolio.status`
|
||||||
|
compares the config with both stores (ids missing on a store, ids on one store only).
|
||||||
|
|
||||||
|
Types of the protocol: `cli/lib/desktop-protocol.ts`; pure portfolio logic: `cli/lib/portfolio.ts`.
|
||||||
|
|
||||||
|
## Safety model
|
||||||
|
|
||||||
|
- The sidecar's first request is `session.hello` with a 32-byte secret the Rust host makes per start and writes to
|
||||||
|
the sidecar's stdin. Write methods are dry runs unless the call carries a confirm token: HMAC-SHA256 over the
|
||||||
|
method, the canonical `{ project, args }` and a 60 s expiry, single use. The host mints one only after the owner
|
||||||
|
pressed Apply in a native dialog that shows the summary and the dry run (`write_with_confirm`).
|
||||||
|
- No method submits for review, releases, publishes, resumes or completes a rollout. Under `serve`, the CLI's own
|
||||||
|
terminal confirmations always answer no.
|
||||||
|
- The webview gets no plugin API. It may call the app commands (each re-checks the window label and the page origin
|
||||||
|
in Rust) and listen to two events. Strict CSP, no remote content. `src-tauri/tests/security.rs` pins all of it.
|
||||||
|
- Store keys (Play service account JSON, App Store Connect key id, issuer id and .p8) are picked in native dialogs,
|
||||||
|
stored in the OS keychain (`keyring`), never shown again and passed to the sidecar per call in memory only.
|
||||||
|
|
||||||
|
## Dependencies screen
|
||||||
|
|
||||||
|
storebound needs no local tool for store work. Screenshots, app previews, icons and captures use:
|
||||||
|
|
||||||
|
| tool | used for | how the app gets it |
|
||||||
|
|---|---|---|
|
||||||
|
| ffmpeg, ffprobe | icons, renders, app previews, frame crops | download into the app data folder (planned, see below) |
|
||||||
|
| Chrome / Chrome for Testing | screenshot renders, captions, web captures | system Chrome, or Chrome for Testing downloaded into the app data folder (planned) |
|
||||||
|
| Xcode command line tools, simctl | iOS builds, Simulator captures | link to Apple only |
|
||||||
|
| adb | Android emulator / device captures | link to the Android platform tools only |
|
||||||
|
| git | release notes, analytics compare | link only |
|
||||||
|
|
||||||
|
`system.tools` reports each with its path, version and source (`app` or `system`). The host passes app-managed
|
||||||
|
copies to the sidecar: `STOREBOUND_TOOL_PATH` (app data `tools/bin`, put in front of PATH for every command) and
|
||||||
|
`STOREBOUND_CHROME` (app data `tools/chrome/...`, used as Playwright's `executablePath`). Nothing is installed
|
||||||
|
system-wide and nothing is bundled in the installer.
|
||||||
|
|
||||||
|
Download sources (decided; the one-click download lands in the next desktop phase):
|
||||||
|
|
||||||
|
- **ffmpeg, macOS (arm64, x64):** release builds from ffmpeg.martin-riedl.de (static, notarized zip per tool).
|
||||||
|
- **ffmpeg, Linux (x64, arm64) and Windows (x64):** `ffmpeg-n<major>-latest-<os>-gpl` release builds from
|
||||||
|
github.com/BtbN/FFmpeg-Builds.
|
||||||
|
- **Verification:** the app ships a manifest with the exact URL and SHA-256 of each archive, updated with each
|
||||||
|
desktop release; a download whose hash differs is deleted. The publisher's own checksum files are not trusted on
|
||||||
|
their own (same host as the archive).
|
||||||
|
- **License:** these ffmpeg builds are GPL (v3 for the BtbN `gpl` variants). The app downloads them only on the
|
||||||
|
owner's click, from the original publisher, shows the license and the source link next to the button, and never
|
||||||
|
redistributes them, so the app itself stays MIT.
|
||||||
|
- **Chrome for Testing:** Google's official JSON endpoints
|
||||||
|
(googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json, Stable channel), archives
|
||||||
|
from storage.googleapis.com over HTTPS. Those endpoints publish no hashes, so the app checks the code signature after
|
||||||
|
unpacking (macOS `codesign --verify` with Google's team, Windows Authenticode); on Linux it checks the version banner.
|
||||||
|
Chrome for Testing is under Google's terms for Chrome / Chromium (BSD-style Chromium license plus third-party notices).
|
||||||
|
- **Progress and cancel** go through the same progress events as sidecar jobs; a cancelled download removes its
|
||||||
|
temporary file.
|
||||||
|
|
||||||
|
## Develop
|
||||||
|
|
||||||
|
```sh
|
||||||
|
bun install
|
||||||
|
bun tools/build-sidecars.ts --host # apps/desktop/src-tauri/binaries/storebound-<target triple>
|
||||||
|
cd apps/desktop && bunx tauri dev # Vite on 127.0.0.1:1420 + the Rust host
|
||||||
|
cd apps/desktop/src-tauri && cargo test && cargo clippy --all-targets -- -D warnings
|
||||||
|
```
|
||||||
|
|
||||||
|
Dev-only switches (ignored in release builds): `VITE_START=accounts|app:catalog|...` opens a screen first,
|
||||||
|
`VITE_THEME=light|dark` forces the theme, `VITE_AUTORUN=gallery` starts the confirm flow on the first app.
|
||||||
|
Gotchas kept from earlier Tauri apps: Cmd+Q quits and the Window menu keeps an entry for the hidden window; platform
|
||||||
|
configs (`tauri.<os>.conf.json`) must not set `app.windows` (Tauri replaces the whole array); Linux sets
|
||||||
|
`WEBKIT_DISABLE_DMABUF_RENDERER=1` unless the user set it; a `bun build --compile` binary needs an ad-hoc re-sign on
|
||||||
|
macOS or the kernel kills it on start.
|
||||||
|
|
@ -46,6 +46,9 @@
|
||||||
"CHANGELOG.md",
|
"CHANGELOG.md",
|
||||||
"docs/agents-core.md"
|
"docs/agents-core.md"
|
||||||
],
|
],
|
||||||
|
"workspaces": [
|
||||||
|
"apps/*"
|
||||||
|
],
|
||||||
"engines": {
|
"engines": {
|
||||||
"bun": ">=1.1"
|
"bun": ">=1.1"
|
||||||
},
|
},
|
||||||
|
|
|
||||||
21
tools/ci.ts
21
tools/ci.ts
|
|
@ -1,16 +1,29 @@
|
||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
// Everything CI runs, in order; stops at the first failure. bun run ci
|
// Everything CI runs, in order; stops at the first failure. bun run ci
|
||||||
const steps: [string, string[]][] = [
|
// `bun test` covers the CLI and the desktop webview (apps/desktop/tests). The desktop Rust host (cargo test, clippy
|
||||||
|
// with warnings as errors) runs when cargo is installed; set STOREBOUND_CI_RUST=0 to skip it on a machine without Rust.
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
const root = new URL('..', import.meta.url).pathname;
|
||||||
|
const tauri = join(root, 'apps/desktop/src-tauri');
|
||||||
|
const cargo = process.env.STOREBOUND_CI_RUST === '0' ? null : Bun.which('cargo');
|
||||||
|
const steps: [string, string[], string?][] = [
|
||||||
['adapters', ['bun', 'tools/gen-adapters.ts', '--check']],
|
['adapters', ['bun', 'tools/gen-adapters.ts', '--check']],
|
||||||
['tests', ['bun', 'test']],
|
['tests', ['bun', 'test']],
|
||||||
['typecheck', ['bunx', 'tsc', '--noEmit']],
|
['typecheck', ['bunx', 'tsc', '--noEmit']],
|
||||||
|
['desktop typecheck', ['bunx', 'tsc', '--noEmit', '-p', 'apps/desktop']],
|
||||||
|
['desktop build', ['bun', 'run', '--cwd', 'apps/desktop', 'build']],
|
||||||
|
...(cargo ? [
|
||||||
|
['desktop rust tests', [cargo, 'test', '--quiet'], tauri],
|
||||||
|
['desktop clippy', [cargo, 'clippy', '--all-targets', '--quiet', '--', '-D', 'warnings'], tauri],
|
||||||
|
] as [string, string[], string][] : []),
|
||||||
['scrub', ['bun', 'tools/scrub.ts']],
|
['scrub', ['bun', 'tools/scrub.ts']],
|
||||||
];
|
];
|
||||||
const root = new URL('..', import.meta.url).pathname;
|
if (!cargo) console.log('ci: cargo not found (or STOREBOUND_CI_RUST=0): desktop Rust tests and clippy skipped');
|
||||||
for (const [name, cmd] of steps) {
|
for (const [name, cmd, cwd] of steps) {
|
||||||
const t = Date.now();
|
const t = Date.now();
|
||||||
console.log(`\n== ${name}: ${cmd.join(' ')}`);
|
console.log(`\n== ${name}: ${cmd.join(' ')}`);
|
||||||
const r = Bun.spawnSync(cmd, { cwd: root, stdout: 'inherit', stderr: 'inherit' });
|
const r = Bun.spawnSync(cmd, { cwd: cwd ?? root, stdout: 'inherit', stderr: 'inherit' });
|
||||||
if (r.exitCode !== 0) { console.error(`\nci: ${name} failed (exit ${r.exitCode})`); process.exit(1); }
|
if (r.exitCode !== 0) { console.error(`\nci: ${name} failed (exit ${r.exitCode})`); process.exit(1); }
|
||||||
console.log(`== ${name} ok (${((Date.now() - t) / 1000).toFixed(1)}s)`);
|
console.log(`== ${name} ok (${((Date.now() - t) / 1000).toFixed(1)}s)`);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
// Secrets / personal data scrub over every tracked (and staged-new) text file. Fails on any hit.
|
// Secrets / personal data scrub over every tracked (and staged-new) text file, the desktop app (apps/desktop)
|
||||||
|
// included. Fails on any hit.
|
||||||
// bun tools/scrub.ts
|
// bun tools/scrub.ts
|
||||||
// Patterns are built from parts so this file does not match itself.
|
// Patterns are built from parts so this file does not match itself.
|
||||||
import { readFileSync } from 'node:fs';
|
import { readFileSync } from 'node:fs';
|
||||||
|
|
@ -10,7 +11,7 @@ export interface Rule { id: string; re: RegExp; files?: RegExp; allow?: (m: stri
|
||||||
const at = '@';
|
const at = '@';
|
||||||
export const RULES: Rule[] = [
|
export const RULES: Rule[] = [
|
||||||
{ id: 'email', re: new RegExp(`[A-Za-z0-9._%+-]+${at}[A-Za-z0-9.-]+\\.[A-Za-z]{2,}`, 'g'),
|
{ id: 'email', re: new RegExp(`[A-Za-z0-9._%+-]+${at}[A-Za-z0-9.-]+\\.[A-Za-z]{2,}`, 'g'),
|
||||||
allow: m => /@example\.(com|org|net)$/i.test(m) || /@users\.noreply\./.test(m) },
|
allow: m => /@example\.(com|org|net)$/i.test(m) || /@users\.noreply\./.test(m) || /@[0-9]x\.(png|jpe?g|webp)$/.test(m) },
|
||||||
{ id: 'private-key', re: new RegExp('-----BEGIN [A-Z ]*PRIVATE ' + 'KEY-----\\s*[A-Za-z0-9+/=]{20,}', 'g'), wholeFile: true },
|
{ id: 'private-key', re: new RegExp('-----BEGIN [A-Z ]*PRIVATE ' + 'KEY-----\\s*[A-Za-z0-9+/=]{20,}', 'g'), wholeFile: true },
|
||||||
{ id: 'private_key-json', re: new RegExp('"private' + '_key"\\s*:\\s*"-----BEGIN', 'g') },
|
{ id: 'private_key-json', re: new RegExp('"private' + '_key"\\s*:\\s*"-----BEGIN', 'g') },
|
||||||
{ id: 'asc-key-file', re: new RegExp('AuthKey' + '_[A-Z0-9]{10}\\.p8', 'g') },
|
{ id: 'asc-key-file', re: new RegExp('AuthKey' + '_[A-Z0-9]{10}\\.p8', 'g') },
|
||||||
|
|
@ -21,9 +22,11 @@ export const RULES: Rule[] = [
|
||||||
{ id: 'ip-address', re: /(?<![\w.\-]|[A-Za-z]\/)(?:\d{1,3}\.){3}\d{1,3}(?![\w.\-])/g, allow: m => ['127.0.0.1', '0.0.0.0'].includes(m) },
|
{ id: 'ip-address', re: /(?<![\w.\-]|[A-Za-z]\/)(?:\d{1,3}\.){3}\d{1,3}(?![\w.\-])/g, allow: m => ['127.0.0.1', '0.0.0.0'].includes(m) },
|
||||||
{ id: 'private-name', re: new RegExp(['Yon', 'ga'].join(''), 'gi') },
|
{ id: 'private-name', re: new RegExp(['Yon', 'ga'].join(''), 'gi') },
|
||||||
{ id: 'google-api-key', re: new RegExp('AI' + 'za[0-9A-Za-z_-]{35}', 'g') },
|
{ id: 'google-api-key', re: new RegExp('AI' + 'za[0-9A-Za-z_-]{35}', 'g') },
|
||||||
|
// absolute home folders leak a machine's account name (placeholders like /Users/you are fine)
|
||||||
|
{ id: 'home-path', re: /(?:\/Users\/|\/home\/|[A-Z]:\\Users\\)(?!(?:you|me|user|runner|name|example)\b)[A-Za-z0-9._-]+/g },
|
||||||
];
|
];
|
||||||
|
|
||||||
const SKIP = /(^|\/)(bun\.lock|LICENSE)$|\.(png|jpe?g|webp|gif|ico|woff2?|ttf|otf|p8|p12|aab|ipa|zip)$/i;
|
const SKIP = /(^|\/)(bun\.lock|Cargo\.lock|LICENSE)$|\.(png|jpe?g|webp|gif|ico|icns|woff2?|ttf|otf|p8|p12|aab|ipa|zip)$/i;
|
||||||
|
|
||||||
export function scan(files: { path: string; text: string }[]): { file: string; line: number; rule: string; match: string }[] {
|
export function scan(files: { path: string; text: string }[]): { file: string; line: number; rule: string; match: string }[] {
|
||||||
const hits: { file: string; line: number; rule: string; match: string }[] = [];
|
const hits: { file: string; line: number; rule: string; match: string }[] = [];
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue