Compare commits
4 commits
c48eead0e0
...
94d2f3d6ca
| Author | SHA1 | Date | |
|---|---|---|---|
| 94d2f3d6ca | |||
| 61a1e832a0 | |||
| ab13d95898 | |||
| d74d99bcc9 |
94 changed files with 10799 additions and 51 deletions
7
.gitignore
vendored
7
.gitignore
vendored
|
|
@ -7,3 +7,10 @@ node_modules/
|
||||||
*.p12
|
*.p12
|
||||||
.DS_Store
|
.DS_Store
|
||||||
media/teaser/out/
|
media/teaser/out/
|
||||||
|
|
||||||
|
# desktop app (apps/desktop): build output, compiled sidecars, Tauri generated schemas
|
||||||
|
apps/desktop/dist/
|
||||||
|
apps/desktop/src-tauri/target/
|
||||||
|
apps/desktop/src-tauri/binaries/
|
||||||
|
apps/desktop/src-tauri/gen/
|
||||||
|
.scratch/
|
||||||
|
|
|
||||||
20
CHANGELOG.md
20
CHANGELOG.md
|
|
@ -1,5 +1,25 @@
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## Unreleased
|
||||||
|
|
||||||
|
- **Desktop machine interface** (`serve --stdio`): JSON-RPC session for the coming desktop app, built on the MCP core.
|
||||||
|
Typed methods with argument schemas, structured results, progress notifications, cancellation, `project.inspect`
|
||||||
|
and `portfolio.status`: apps across iOS and Android with identity, config check, release trains (current and next
|
||||||
|
version on both stores) and catalog parity (`live` reads App Store and Play status). `system.tools` reports ffmpeg,
|
||||||
|
Chrome, Xcode tools, simctl, adb and git with versions; `STOREBOUND_TOOL_PATH` / `STOREBOUND_CHROME` point the CLI
|
||||||
|
at app-managed copies. Writes are dry runs unless the host
|
||||||
|
sends a single-use confirm token bound to the method, arguments and a short expiry (HMAC with a per-session secret
|
||||||
|
handed over on stdin). No submit / release / publish method exists. Under `serve`, terminal confirmations always
|
||||||
|
answer no.
|
||||||
|
- `--json` on `check` (and `check --aso`), `apple testflight status`, `apple ppo status`, `apple next-build`,
|
||||||
|
`play next-version-code`, `analytics compare` and `prices import` (read-only diff); new `inspect` command.
|
||||||
|
- **Desktop app shell** (`apps/desktop`, not released yet): Tauri 2 + React 19, app-centric (Portfolio, App with
|
||||||
|
Releases / Catalog / Listings / Health / Reviews / TestFlight, App folders, Accounts, Dependencies, Settings), store
|
||||||
|
keys in the OS keychain, native confirm dialogs with the dry run before any write. See `docs/desktop.md`.
|
||||||
|
- `--json` on `catalog diff` goes through the same machine-readable result line.
|
||||||
|
- `tools/build-sidecars.ts`: single-file executables for macOS (arm64, x64), Linux (x64, arm64) and Windows (x64),
|
||||||
|
re-signed ad hoc on macOS and checked for build-machine paths. The MCP server now also runs from such a binary.
|
||||||
|
|
||||||
## 0.5.0 · 2026-10-11
|
## 0.5.0 · 2026-10-11
|
||||||
|
|
||||||
Apps and games: storebound is for every mobile app, not only games, and the in-app catalog is complete on both stores.
|
Apps and games: storebound is for every mobile app, not only games, and the in-app catalog is complete on both stores.
|
||||||
|
|
|
||||||
15
README.md
15
README.md
|
|
@ -174,6 +174,8 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
||||||
| `init [--profile app\|game\|subscription-app]` | local | copy the templates of a profile (default app), gitignore `.storebound/` |
|
| `init [--profile app\|game\|subscription-app]` | local | copy the templates of a profile (default app), gitignore `.storebound/` |
|
||||||
| `install --agent <tool>` | local | skills + MCP entry for an AI tool |
|
| `install --agent <tool>` | local | skills + MCP entry for an AI tool |
|
||||||
| `mcp` | local | stdio MCP server wrapping the commands |
|
| `mcp` | local | stdio MCP server wrapping the commands |
|
||||||
|
| `serve --stdio` | local | JSON-RPC session for the storebound desktop app (see [Desktop machine interface](#desktop-machine-interface)) |
|
||||||
|
| `inspect [--json]` | local | offline summary of the config: name, store ids, languages, products |
|
||||||
| `check` | local | config, copy limits, data safety, products, subscriptions, profile (delete-account URL, demo account, terms URL), files; warns on untranslated release notes |
|
| `check` | local | config, copy limits, data safety, products, subscriptions, profile (delete-account URL, demo account, terms URL), files; warns on untranslated release notes |
|
||||||
| `catalog diff [--store] [--threshold 10]` | API, read-only | one catalog vs both stores: missing / extra / mismatched products and subscriptions, US and override prices, locales, offers, per-region price differences between the stores; exit 1 on mismatches |
|
| `catalog diff [--store] [--threshold 10]` | API, read-only | one catalog vs both stores: missing / extra / mismatched products and subscriptions, US and override prices, locales, offers, per-region price differences between the stores; exit 1 on mismatches |
|
||||||
| `check --aso` | local | keyword audit: App Store keyword field rules, Play stuffing / claims |
|
| `check --aso` | local | keyword audit: App Store keyword field rules, Play stuffing / claims |
|
||||||
|
|
@ -376,6 +378,19 @@ per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same proc
|
||||||
Manual config for a tool that `install` does not know: command `bunx` with args `["storebound", "mcp"]` (or the
|
Manual config for a tool that `install` does not know: command `bunx` with args `["storebound", "mcp"]` (or the
|
||||||
absolute path of `bin/storebound` plus `mcp`).
|
absolute path of `bin/storebound` plus `mcp`).
|
||||||
|
|
||||||
|
### Desktop machine interface
|
||||||
|
|
||||||
|
`storebound serve --stdio` is what the desktop app (`apps/desktop`, in progress) runs as its sidecar: newline-delimited
|
||||||
|
JSON-RPC on the same core as the MCP server (tool list, validation, forbidden flags, child-process runner), with typed
|
||||||
|
methods (`check`, `validate`, `apple.status`, `play.listing`, ... plus `project.inspect` and `portfolio.status` over
|
||||||
|
many project folders), structured results (the commands' `--json` output), progress notifications and cancellation.
|
||||||
|
The first request is `session.hello` with a per-session secret only the host knows. Write methods are dry runs unless
|
||||||
|
the call carries a single-use confirm token (HMAC over method, arguments and expiry) that the host mints after the
|
||||||
|
owner confirmed a native dialog showing that dry run. There is no method that submits, releases or publishes; Play
|
||||||
|
testing releases and phased release changes stay out of the desktop profile too. Types: `cli/lib/desktop-protocol.ts`.
|
||||||
|
`bun tools/build-sidecars.ts` compiles the CLI for macOS, Linux and Windows (`bun build --compile`). Design, safety
|
||||||
|
model and the Dependencies screen (tool sources and licenses): [docs/desktop.md](docs/desktop.md).
|
||||||
|
|
||||||
## Safety model
|
## Safety model
|
||||||
|
|
||||||
- **Credentials** live in env vars or the gitignored `.storebound/credentials.json`, never in the config or the repo.
|
- **Credentials** live in env vars or the gitignored `.storebound/credentials.json`, never in the config or the repo.
|
||||||
|
|
|
||||||
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', flexWrap: 'nowrap' }}>
|
||||||
|
<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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
85
apps/desktop/src/screens/Portfolio.tsx
Normal file
85
apps/desktop/src/screens/Portfolio.tsx
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
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>Platforms</th><th>Live</th><th>Next</th><th title="In-app products · subscriptions">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>
|
||||||
|
{e && (
|
||||||
|
<div className="plat">
|
||||||
|
<div><span className={`tag ${ios ? 'tag-local' : 'tag-muted'}`}>iOS</span> <span className="selectable">{ios?.bundleId ?? 'not set up'}</span>{e.storeErrors.ios && <span className="tag tag-bad" title={e.storeErrors.ios}>unreadable</span>}</div>
|
||||||
|
<div><span className={`tag ${android ? 'tag-ok' : 'tag-muted'}`}>Android</span> <span className="selectable">{android?.packageName ?? 'not set up'}</span>{e.storeErrors.android && <span className="tag tag-bad" title={e.storeErrors.android}>unreadable</span>}</div>
|
||||||
|
</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.products} in-app products, ${cat.subscriptions} subscriptions; ${cat.checked === 'live' ? 'compared with both stores' : 'from the config, read the stores to compare'}`}>{cat.products} · {cat.subscriptions}</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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
179
apps/desktop/src/styles.css
Normal file
179
apps/desktop/src/styles.css
Normal file
|
|
@ -0,0 +1,179 @@
|
||||||
|
/* 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; max-width: 220px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
td:first-child { min-width: 180px; }
|
||||||
|
.card:has(> table) { overflow-x: auto; }
|
||||||
|
.name { font-weight: 650; }
|
||||||
|
|
||||||
|
.nowrap { white-space: nowrap; }
|
||||||
|
.plat { display: grid; gap: 6px; font-size: 13px; }
|
||||||
|
.plat .tag { min-width: 64px; text-align: center; margin-right: 6px; }
|
||||||
|
.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,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
@ -17,7 +17,7 @@ import {
|
||||||
latestPerDate, mergeSeries, monthsBetween, parseGitLog, parseReport, pickReport, type PlayDay, playDaily, playObjects, playTotals, type Snapshot,
|
latestPerDate, mergeSeries, monthsBetween, parseGitLog, parseReport, pickReport, type PlayDay, playDaily, playObjects, playTotals, type Snapshot,
|
||||||
} from './lib/analytics';
|
} from './lib/analytics';
|
||||||
import { STORAGE_READ_SCOPE } from './lib/google-auth';
|
import { STORAGE_READ_SCOPE } from './lib/google-auth';
|
||||||
import { done, log, warn } from './lib/log';
|
import { done, log, printJson, warn } from './lib/log';
|
||||||
import { pct, textTable } from './lib/table';
|
import { pct, textTable } from './lib/table';
|
||||||
import { googleClient } from './play/google';
|
import { googleClient } from './play/google';
|
||||||
|
|
||||||
|
|
@ -145,6 +145,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const events = parseGitLog(g.stdout.toString()).reverse();
|
const events = parseGitLog(g.stdout.toString()).reverse();
|
||||||
log(TAG, `${snaps.length} snapshot(s), ${series.apple.length} App Store day(s), ${series.play.length} Play day(s), ${events.length} store change(s) since ${first}`);
|
log(TAG, `${snaps.length} snapshot(s), ${series.apple.length} App Store day(s), ${series.play.length} Play day(s), ${events.length} store change(s) since ${first}`);
|
||||||
const fx = compareAroundEvents(series, events, a.num('days', 7));
|
const fx = compareAroundEvents(series, events, a.num('days', 7));
|
||||||
|
if (a.has('json')) { printJson({ snapshots: snaps.length, since: first, series, effects: fx }); return; }
|
||||||
console.log(a.has('md') ? effectMarkdown(fx) : effectTable(fx));
|
console.log(a.has('md') ? effectMarkdown(fx) : effectTable(fx));
|
||||||
log(TAG, 'reading: a change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too');
|
log(TAG, 'reading: a change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too');
|
||||||
return;
|
return;
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@
|
||||||
// Then attach exactly that build: storebound apple listing --version x.y.z --build 42 (never "the latest").
|
// Then attach exactly that build: storebound apple listing --version x.y.z --build 42 (never "the latest").
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { need } from '../lib/ctx';
|
import { need } from '../lib/ctx';
|
||||||
|
import { printJson } from '../lib/log';
|
||||||
import { nextBuildNumber } from '../lib/release';
|
import { nextBuildNumber } from '../lib/release';
|
||||||
import { ascClient } from './asc';
|
import { ascClient } from './asc';
|
||||||
|
|
||||||
|
|
@ -14,6 +15,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const appId = await c.app();
|
const appId = await c.app();
|
||||||
const builds = await c.all(`/v1/builds?filter[app]=${appId}&limit=200&fields[builds]=version`);
|
const builds = await c.all(`/v1/builds?filter[app]=${appId}&limit=200&fields[builds]=version`);
|
||||||
const next = nextBuildNumber(builds.map(b => String(b.attributes.version)));
|
const next = nextBuildNumber(builds.map(b => String(b.attributes.version)));
|
||||||
|
if (ctx.args.has('json')) { printJson({ next, builds: builds.length }); return; }
|
||||||
console.error(`[apple] ${builds.length} builds on App Store Connect; next build number:`);
|
console.error(`[apple] ${builds.length} builds on App Store Connect; next build number:`);
|
||||||
console.log(next);
|
console.log(next);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
// App Store Product Page Optimization through the App Store Connect API, wired to the `shots` variants.
|
// App Store Product Page Optimization through the App Store Connect API, wired to the `shots` variants.
|
||||||
// storebound apple ppo status
|
// storebound apple ppo status [--json]
|
||||||
// storebound apple ppo create --variant b[,c] [--name "..."] [--traffic 30] [--dry]
|
// storebound apple ppo create --variant b[,c] [--name "..."] [--traffic 30] [--dry]
|
||||||
// storebound apple ppo upload --variant b [--experiment "..."] [--only en-US,tr] [--src store/renders] [--dry]
|
// storebound apple ppo upload --variant b [--experiment "..."] [--only en-US,tr] [--src store/renders] [--dry]
|
||||||
// storebound apple ppo start | stop [--experiment "..."] [--dry] [--yes]
|
// storebound apple ppo start | stop [--experiment "..."] [--dry] [--yes]
|
||||||
|
|
@ -13,7 +13,7 @@ import { existsSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { byAppleLocale, confirm, need } from '../lib/ctx';
|
import { byAppleLocale, confirm, need } from '../lib/ctx';
|
||||||
import { done, log, warn } from '../lib/log';
|
import { done, log, printJson, warn } from '../lib/log';
|
||||||
import {
|
import {
|
||||||
checkCreate, createExperimentReq, defaultName, type Experiment, experimentFromApi, pickExperiment, planTreatmentLocales, planTreatments, startStopReq,
|
checkCreate, createExperimentReq, defaultName, type Experiment, experimentFromApi, pickExperiment, planTreatmentLocales, planTreatments, startStopReq,
|
||||||
} from '../lib/ppo';
|
} from '../lib/ppo';
|
||||||
|
|
@ -44,6 +44,16 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const list = await experiments(c, appId);
|
const list = await experiments(c, appId);
|
||||||
const locales = config.languages.map(l => l.apple).filter((x): x is string => !!x);
|
const locales = config.languages.map(l => l.apple).filter((x): x is string => !!x);
|
||||||
|
|
||||||
|
if (sub === 'status' && a.has('json')) {
|
||||||
|
const tests = [];
|
||||||
|
for (const x of list) {
|
||||||
|
const ts = [];
|
||||||
|
if (!['COMPLETED', 'STOPPED'].includes(x.state)) for (const t of await treatments(c, x.id)) ts.push({ id: t.id, name: t.attributes.name, locales: (await treatmentLocs(c, t.id)).length });
|
||||||
|
tests.push({ ...x, treatments: ts });
|
||||||
|
}
|
||||||
|
printJson({ tests });
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (sub === 'status') {
|
if (sub === 'status') {
|
||||||
if (!list.length) { done(TAG, 'no Product Page Optimization tests (storebound apple ppo create --variant b)'); return; }
|
if (!list.length) { done(TAG, 'no Product Page Optimization tests (storebound apple ppo create --variant b)'); return; }
|
||||||
console.log(textTable(['test', 'state', 'traffic', 'start', 'end'], list.map(x => [x.name, x.state, x.trafficProportion !== undefined ? `${x.trafficProportion}%` : '', (x.startDate ?? '').slice(0, 10), (x.endDate ?? '').slice(0, 10)])));
|
console.log(textTable(['test', 'state', 'traffic', 'start', 'end'], list.map(x => [x.name, x.state, x.trafficProportion !== undefined ? `${x.trafficProportion}%` : '', (x.startDate ?? '').slice(0, 10), (x.endDate ?? '').slice(0, 10)])));
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@
|
||||||
// exit codes: 0 approved, 1 rejected, 7 timeout (2 = nothing in review)
|
// exit codes: 0 approved, 1 rejected, 7 timeout (2 = nothing in review)
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { confirm, need } from '../lib/ctx';
|
import { confirm, need } from '../lib/ctx';
|
||||||
import { log } from '../lib/log';
|
import { log, printJson } from '../lib/log';
|
||||||
import { classifyReviewState, nextPollDelay, parseDuration, WAIT_EXIT } from '../lib/release';
|
import { classifyReviewState, nextPollDelay, parseDuration, WAIT_EXIT } from '../lib/release';
|
||||||
import { type Asc, ascClient, type J } from './asc';
|
import { type Asc, ascClient, type J } from './asc';
|
||||||
|
|
||||||
|
|
@ -54,7 +54,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=5&include=preReleaseVersion`));
|
const builds = (await c.asc('GET', `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=5&include=preReleaseVersion`));
|
||||||
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
|
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
|
||||||
const subs = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&limit=20`);
|
const subs = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&limit=20`);
|
||||||
if (ctx.args.has('json')) { console.log(JSON.stringify({ app, versions, builds: builds.data, iaps, subs }, null, 2)); return; }
|
if (ctx.args.has('json')) { printJson({ app, versions, builds: builds.data, iaps, subs }); return; }
|
||||||
|
|
||||||
console.log(`${app.attributes.name} · ${app.attributes.bundleId} · Apple ID ${appId}`);
|
console.log(`${app.attributes.name} · ${app.attributes.bundleId} · Apple ID ${appId}`);
|
||||||
for (const v of versions) console.log(` version ${v.attributes.versionString.padEnd(8)} ${v.attributes.appVersionState ?? v.attributes.appStoreState}${v.relationships?.build?.data ? ' (build attached)' : ''}`);
|
for (const v of versions) console.log(` version ${v.attributes.versionString.padEnd(8)} ${v.attributes.appVersionState ?? v.attributes.appStoreState}${v.relationships?.build?.data ? ' (build attached)' : ''}`);
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
// TestFlight through the App Store Connect API.
|
// TestFlight through the App Store Connect API.
|
||||||
// storebound apple testflight status groups, testers per group, recent builds + beta states
|
// storebound apple testflight status [--json] groups, testers per group, recent builds + beta states
|
||||||
// storebound apple testflight groups [--dry] create the groups of apple.testflight.groups that are missing
|
// storebound apple testflight groups [--dry] create the groups of apple.testflight.groups that are missing
|
||||||
// storebound apple testflight testers [--csv f] [--group a,b] [--remove] [--invite] [--dry] [--yes]
|
// storebound apple testflight testers [--csv f] [--group a,b] [--remove] [--invite] [--dry] [--yes]
|
||||||
// storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry]
|
// storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry]
|
||||||
|
|
@ -14,7 +14,7 @@ import { existsSync, readFileSync } from 'node:fs';
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { confirm, need } from '../lib/ctx';
|
import { confirm, need } from '../lib/ctx';
|
||||||
import { reviewContact } from '../lib/credentials';
|
import { reviewContact } from '../lib/credentials';
|
||||||
import { done, log, warn } from '../lib/log';
|
import { done, log, printJson, warn } from '../lib/log';
|
||||||
import { textTable } from '../lib/table';
|
import { textTable } from '../lib/table';
|
||||||
import {
|
import {
|
||||||
type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail,
|
type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail,
|
||||||
|
|
@ -52,21 +52,30 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
if (sub === 'status') {
|
if (sub === 'status') {
|
||||||
const gs = await groups(c, appId);
|
const gs = await groups(c, appId);
|
||||||
const rows: (string | number)[][] = [];
|
const rows: (string | number)[][] = [];
|
||||||
|
const jsonGroups: Record<string, unknown>[] = [];
|
||||||
for (const g of gs) {
|
for (const g of gs) {
|
||||||
const testers = await c.all(`/v1/betaGroups/${g.id}/betaTesters?limit=200`);
|
const testers = await c.all(`/v1/betaGroups/${g.id}/betaTesters?limit=200`);
|
||||||
const builds = await c.all(`/v1/betaGroups/${g.id}/builds?limit=200`);
|
const builds = await c.all(`/v1/betaGroups/${g.id}/builds?limit=200`);
|
||||||
|
jsonGroups.push({ id: g.id, name: g.name, internal: g.internal, testers: testers.length, builds: g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, publicLink: !!g.publicLinkEnabled });
|
||||||
rows.push([g.name, g.internal ? 'internal' : 'external', testers.length, g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, g.publicLinkEnabled ? 'public link on' : '']);
|
rows.push([g.name, g.internal ? 'internal' : 'external', testers.length, g.internal && g.hasAccessToAllBuilds ? 'all' : builds.length, g.publicLinkEnabled ? 'public link on' : '']);
|
||||||
}
|
}
|
||||||
console.log(textTable(['group', 'kind', 'testers', 'builds', ''], rows));
|
|
||||||
const q = new URLSearchParams({ 'filter[app]': appId, include: 'preReleaseVersion,buildBetaDetail', sort: '-uploadedDate', limit: '8' });
|
const q = new URLSearchParams({ 'filter[app]': appId, include: 'preReleaseVersion,buildBetaDetail', sort: '-uploadedDate', limit: '8' });
|
||||||
const resp = await c.asc('GET', `/v1/builds?${q}`);
|
const resp = await c.asc('GET', `/v1/builds?${q}`);
|
||||||
const details = new Map((resp.included ?? []).filter((x: J) => x.type === 'buildBetaDetails').map((x: J) => [x.id, x.attributes] as const));
|
const details = new Map((resp.included ?? []).filter((x: J) => x.type === 'buildBetaDetails').map((x: J) => [x.id, x.attributes] as const));
|
||||||
|
const missingGroups = (tf?.groups ?? []).filter(w => !gs.some(g => g.name === w.name)).map(w => w.name);
|
||||||
|
if (a.has('json')) {
|
||||||
|
printJson({ groups: jsonGroups, builds: buildsWithVersion(resp).map(b => {
|
||||||
|
const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J;
|
||||||
|
return { version: b.marketing ?? null, build: b.attributes.version ?? null, processing: b.attributes.processingState ?? null, internal: d?.internalBuildState ?? null, external: d?.externalBuildState ?? null, uploaded: b.attributes.uploadedDate ?? null };
|
||||||
|
}), missingGroups });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(textTable(['group', 'kind', 'testers', 'builds', ''], rows));
|
||||||
console.log('\n' + textTable(['version', 'build', 'processing', 'internal', 'external', 'uploaded'], buildsWithVersion(resp).map(b => {
|
console.log('\n' + textTable(['version', 'build', 'processing', 'internal', 'external', 'uploaded'], buildsWithVersion(resp).map(b => {
|
||||||
const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J;
|
const d = details.get((b as J).relationships?.buildBetaDetail?.data?.id) as J;
|
||||||
return [b.marketing ?? '', b.attributes.version ?? '', b.attributes.processingState ?? '', d?.internalBuildState ?? '', d?.externalBuildState ?? '', (b.attributes.uploadedDate ?? '').slice(0, 10)];
|
return [b.marketing ?? '', b.attributes.version ?? '', b.attributes.processingState ?? '', d?.internalBuildState ?? '', d?.externalBuildState ?? '', (b.attributes.uploadedDate ?? '').slice(0, 10)];
|
||||||
})));
|
})));
|
||||||
const missing = (tf?.groups ?? []).filter(w => !gs.some(g => g.name === w.name)).map(w => w.name);
|
if (missingGroups.length) warn(TAG, `configured but not on App Store Connect: ${missingGroups.join(', ')} (storebound apple testflight groups)`);
|
||||||
if (missing.length) warn(TAG, `configured but not on App Store Connect: ${missing.join(', ')} (storebound apple testflight groups)`);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import { appleCurrent, pages, playProduct } from './prices';
|
||||||
import { ascClient, type J } from './apple/asc';
|
import { ascClient, type J } from './apple/asc';
|
||||||
import { type CatalogRow, catalogDiff, fromApplePeriod, fromAppleType, regionOf, type StoreItem, wantedCatalog } from './lib/catalog';
|
import { type CatalogRow, catalogDiff, fromApplePeriod, fromAppleType, regionOf, type StoreItem, wantedCatalog } from './lib/catalog';
|
||||||
import type { Ctx } from './lib/ctx';
|
import type { Ctx } from './lib/ctx';
|
||||||
import { done, log } from './lib/log';
|
import { done, log, printJson } from './lib/log';
|
||||||
import { fromMoney } from './lib/money';
|
import { fromMoney } from './lib/money';
|
||||||
import { listOneTimeProducts } from './play/products';
|
import { listOneTimeProducts } from './play/products';
|
||||||
import { playClient } from './play/client';
|
import { playClient } from './play/client';
|
||||||
|
|
@ -94,7 +94,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const play = (!store || store === 'play') && config.play ? await playItems(ctx) : null;
|
const play = (!store || store === 'play') && config.play ? await playItems(ctx) : null;
|
||||||
const { rows, parity } = catalogDiff(want, { apple, play }, { threshold: a.num('threshold', 10) / 100 });
|
const { rows, parity } = catalogDiff(want, { apple, play }, { threshold: a.num('threshold', 10) / 100 });
|
||||||
const errors = rows.filter(r => r.level === 'error').length;
|
const errors = rows.filter(r => r.level === 'error').length;
|
||||||
if (a.has('json')) console.log(JSON.stringify({ errors, rows, parity }, null, 2));
|
if (a.has('json')) printJson({ errors, rows, parity });
|
||||||
else {
|
else {
|
||||||
console.log(formatRows(rows));
|
console.log(formatRows(rows));
|
||||||
if (parity.length) console.log(`\nprice differences between the stores (same currency, over ${a.num('threshold', 10)} %):\n` +
|
if (parity.length) console.log(`\nprice differences between the stores (same currency, over ${a.num('threshold', 10)} %):\n` +
|
||||||
|
|
|
||||||
18
cli/check.ts
18
cli/check.ts
|
|
@ -3,6 +3,7 @@
|
||||||
// subscriptions + terms URL) and the files the config points at. No network; credentials are only checked for presence.
|
// subscriptions + terms URL) and the files the config points at. No network; credentials are only checked for presence.
|
||||||
// storebound check everything above
|
// storebound check everything above
|
||||||
// storebound check --aso keyword audit of both listing files (App Store keyword field, Play stuffing); exit 1 on errors
|
// storebound check --aso keyword audit of both listing files (App Store keyword field, Play stuffing); exit 1 on errors
|
||||||
|
// --json structured result ({ ok, items, warnings, problems } or { findings, errors }), exit 1 on problems
|
||||||
import { existsSync, readFileSync } from 'node:fs';
|
import { existsSync, readFileSync } from 'node:fs';
|
||||||
import { type AsoFinding, auditAso } from './lib/aso';
|
import { type AsoFinding, auditAso } from './lib/aso';
|
||||||
import { playCodes } from './lib/config';
|
import { playCodes } from './lib/config';
|
||||||
|
|
@ -10,7 +11,7 @@ import { APPLE_IAP_LIMITS, len, parseAppStoreListing, parsePlayListing } from '.
|
||||||
import type { Ctx } from './lib/ctx';
|
import type { Ctx } from './lib/ctx';
|
||||||
import { dataSafetyRows } from './lib/data-safety';
|
import { dataSafetyRows } from './lib/data-safety';
|
||||||
import { reviewDemoAccount } from './lib/credentials';
|
import { reviewDemoAccount } from './lib/credentials';
|
||||||
import { log, warn } from './lib/log';
|
import { log, printJson, warn } from './lib/log';
|
||||||
import { profileIssues } from './lib/profile';
|
import { profileIssues } from './lib/profile';
|
||||||
import { allSubscriptions } from './lib/subscriptions';
|
import { allSubscriptions } from './lib/subscriptions';
|
||||||
import { type CopyFile, validateCopy } from './shots/lib';
|
import { type CopyFile, validateCopy } from './shots/lib';
|
||||||
|
|
@ -20,6 +21,7 @@ function aso(ctx: Ctx): void {
|
||||||
const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined;
|
const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined;
|
||||||
const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined;
|
const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined;
|
||||||
const f: AsoFinding[] = auditAso({ apple, play, appName: config.app.name, storefront: ctx.args.get('storefront') ?? 'US' });
|
const f: AsoFinding[] = auditAso({ apple, play, appName: config.app.name, storefront: ctx.args.get('storefront') ?? 'US' });
|
||||||
|
if (ctx.args.has('json')) { const errors = f.filter(x => x.level === 'error').length; printJson({ findings: f, errors }); if (errors) process.exitCode = 1; return; }
|
||||||
const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const;
|
const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const;
|
||||||
for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`);
|
for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`);
|
||||||
const errors = f.filter(x => x.level === 'error').length;
|
const errors = f.filter(x => x.level === 'error').length;
|
||||||
|
|
@ -32,24 +34,29 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const { config, resolve, path } = ctx.loaded;
|
const { config, resolve, path } = ctx.loaded;
|
||||||
log('check', `config ok: ${path}`);
|
log('check', `config ok: ${path}`);
|
||||||
const problems: string[] = [];
|
const problems: string[] = [];
|
||||||
const tryDo = (what: string, fn: () => string): void => { try { log('check', `${what}: ${fn()}`); } catch (e) { problems.push(`${what}: ${(e as Error).message}`); } };
|
const items: { what: string; detail: string }[] = [];
|
||||||
|
const warnings: string[] = [];
|
||||||
|
const note = (msg: string): void => { warnings.push(msg); warn('check', msg); };
|
||||||
|
const tryDo = (what: string, fn: () => string): void => {
|
||||||
|
try { const detail = fn(); items.push({ what, detail }); log('check', `${what}: ${detail}`); } catch (e) { problems.push(`${what}: ${(e as Error).message}`); }
|
||||||
|
};
|
||||||
|
|
||||||
if (config.play) tryDo('play listing', () => {
|
if (config.play) tryDo('play listing', () => {
|
||||||
const f = resolve(config.play!.listing ?? 'store/listing.md');
|
const f = resolve(config.play!.listing ?? 'store/listing.md');
|
||||||
const copy = parsePlayListing(readFileSync(f, 'utf8'), config.app.name);
|
const copy = parsePlayListing(readFileSync(f, 'utf8'), config.app.name);
|
||||||
const want = config.languages.flatMap(playCodes);
|
const want = config.languages.flatMap(playCodes);
|
||||||
const missing = want.filter(c => !copy.some(x => x.lang === c));
|
const missing = want.filter(c => !copy.some(x => x.lang === c));
|
||||||
if (missing.length) warn('check', `play listing has no section for ${missing.join(', ')}`);
|
if (missing.length) note(`play listing has no section for ${missing.join(', ')}`);
|
||||||
const def = copy.find(x => x.lang === (config.play!.defaultLanguage ?? 'en-US'));
|
const def = copy.find(x => x.lang === (config.play!.defaultLanguage ?? 'en-US'));
|
||||||
const same = copy.filter(x => def && x !== def && x.whatsNew && x.whatsNew === def.whatsNew && x.lang.slice(0, 2) !== def.lang.slice(0, 2));
|
const same = copy.filter(x => def && x !== def && x.whatsNew && x.whatsNew === def.whatsNew && x.lang.slice(0, 2) !== def.lang.slice(0, 2));
|
||||||
if (same.length) warn('check', `what's new of ${same.map(x => x.lang).join(', ')} is the same text as ${def!.lang}: translate it`);
|
if (same.length) note(`what's new of ${same.map(x => x.lang).join(', ')} is the same text as ${def!.lang}: translate it`);
|
||||||
return `${copy.length} languages`;
|
return `${copy.length} languages`;
|
||||||
});
|
});
|
||||||
if (config.apple) tryDo('appstore listing', () => {
|
if (config.apple) tryDo('appstore listing', () => {
|
||||||
const f = resolve(config.apple!.listing ?? 'store/appstore.md');
|
const f = resolve(config.apple!.listing ?? 'store/appstore.md');
|
||||||
const copy = parseAppStoreListing(readFileSync(f, 'utf8'));
|
const copy = parseAppStoreListing(readFileSync(f, 'utf8'));
|
||||||
const missing = config.languages.filter(l => l.apple && !copy[l.apple]).map(l => l.apple);
|
const missing = config.languages.filter(l => l.apple && !copy[l.apple]).map(l => l.apple);
|
||||||
if (missing.length) warn('check', `appstore listing has no section for ${missing.join(', ')}`);
|
if (missing.length) note(`appstore listing has no section for ${missing.join(', ')}`);
|
||||||
return `${Object.keys(copy).length} locales`;
|
return `${Object.keys(copy).length} locales`;
|
||||||
});
|
});
|
||||||
if (config.dataSafety) tryDo('data safety', () => `${dataSafetyRows(config.dataSafety!).length - 1} CSV rows`);
|
if (config.dataSafety) tryDo('data safety', () => `${dataSafetyRows(config.dataSafety!).length - 1} CSV rows`);
|
||||||
|
|
@ -74,6 +81,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
if (existsSync(resolve('.gitignore')) && !/^\/?\.storebound\/?$/m.test(readFileSync(resolve('.gitignore'), 'utf8')))
|
if (existsSync(resolve('.gitignore')) && !/^\/?\.storebound\/?$/m.test(readFileSync(resolve('.gitignore'), 'utf8')))
|
||||||
problems.push('.gitignore does not ignore .storebound/ (credentials live there)');
|
problems.push('.gitignore does not ignore .storebound/ (credentials live there)');
|
||||||
|
|
||||||
|
if (ctx.args.has('json')) { printJson({ config: path, ok: !problems.length, items, warnings, problems }); if (problems.length) process.exitCode = 1; return; }
|
||||||
if (problems.length) { for (const p of problems) console.error(` - ${p}`); throw new Error(`${problems.length} problems`); }
|
if (problems.length) { for (const p of problems) console.error(` - ${p}`); throw new Error(`${problems.length} problems`); }
|
||||||
log('check', 'all good');
|
log('check', 'all good');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ import {
|
||||||
type AppleHealth, ANR_METRICS, betaCrashCounts, CRASH_METRICS, deviceBreakdown, healthFindings, healthMarkdown, type HealthSnapshot, healthTable,
|
type AppleHealth, ANR_METRICS, betaCrashCounts, CRASH_METRICS, deviceBreakdown, healthFindings, healthMarkdown, type HealthSnapshot, healthTable,
|
||||||
issuesQuery, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, type PlayHealth, ymd, ymdString,
|
issuesQuery, latestDailyEnd, metricQuery, parseIssues, parseMetricRows, parsePerfPower, type PlayHealth, ymd, ymdString,
|
||||||
} from './lib/health';
|
} from './lib/health';
|
||||||
import { done, log, warn } from './lib/log';
|
import { done, log, printJson, warn } from './lib/log';
|
||||||
import { formatFindings } from './lib/validate-rules';
|
import { formatFindings } from './lib/validate-rules';
|
||||||
import { googleClient, REPORTING_API } from './play/google';
|
import { googleClient, REPORTING_API } from './play/google';
|
||||||
|
|
||||||
|
|
@ -84,7 +84,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const days = a.num('days', 7);
|
const days = a.num('days', 7);
|
||||||
if (!(days >= 1 && days <= 90)) throw new Error('--days: 1-90');
|
if (!(days >= 1 && days <= 90)) throw new Error('--days: 1-90');
|
||||||
const h = await collectHealth(ctx, { apple: both || a.has('apple'), play: both || a.has('play'), days });
|
const h = await collectHealth(ctx, { apple: both || a.has('apple'), play: both || a.has('play'), days });
|
||||||
if (a.has('json')) { console.log(JSON.stringify(h, null, 2)); return; }
|
if (a.has('json')) { printJson(h); return; }
|
||||||
console.log(healthTable(h));
|
console.log(healthTable(h));
|
||||||
console.log('\n' + formatFindings(healthFindings(h)));
|
console.log('\n' + formatFindings(healthFindings(h)));
|
||||||
if (weekly) {
|
if (weekly) {
|
||||||
|
|
|
||||||
|
|
@ -12,9 +12,11 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
|
||||||
'init': [() => import('./init'), 'copy the templates (config, listing, copy, declarations, privacy policy) into this project; --profile app|game|subscription-app (default app)'],
|
'init': [() => import('./init'), 'copy the templates (config, listing, copy, declarations, privacy policy) into this project; --profile app|game|subscription-app (default app)'],
|
||||||
'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'],
|
'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'],
|
||||||
'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'],
|
'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'],
|
||||||
|
'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'],
|
||||||
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
|
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
|
||||||
};
|
};
|
||||||
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
||||||
|
'inspect': [() => import('./inspect'), 'offline summary of the config (name, store ids, languages, products, subscriptions); --json'],
|
||||||
'check': [() => import('./check'), 'validate config, copy files, data safety answers, products, subscriptions and the app profile (offline); --aso keyword audit'],
|
'check': [() => import('./check'), 'validate config, copy files, data safety answers, products, subscriptions and the app profile (offline); --aso keyword audit'],
|
||||||
'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'],
|
'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'],
|
||||||
'analytics': [() => import('./analytics'), 'setup (App Store report request) | snapshot (impressions, page views, installs, conversion -> .storebound/analytics) | compare (vs listing changes in git)'],
|
'analytics': [() => import('./analytics'), 'setup (App Store report request) | snapshot (impressions, page views, installs, conversion -> .storebound/analytics) | compare (vs listing changes in git)'],
|
||||||
|
|
|
||||||
39
cli/inspect.ts
Normal file
39
cli/inspect.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
// Offline summary of the project config: app name, store ids, languages, products, shots. No network, no credentials.
|
||||||
|
// storebound inspect [--json]
|
||||||
|
import { platformsOf, sellsOn } from './lib/config';
|
||||||
|
import type { Ctx } from './lib/ctx';
|
||||||
|
import type { ProjectSummary } from './lib/desktop-protocol';
|
||||||
|
import { log, printJson } from './lib/log';
|
||||||
|
|
||||||
|
export function summarize(ctx: Ctx): ProjectSummary {
|
||||||
|
const { config, root, path } = ctx.loaded;
|
||||||
|
const subs = (config.subscriptions ?? []).flatMap(g => g.subscriptions);
|
||||||
|
return {
|
||||||
|
dir: root,
|
||||||
|
config: path,
|
||||||
|
name: config.app.name,
|
||||||
|
languages: config.languages.map(l => l.id),
|
||||||
|
play: config.play ? { packageName: config.play.packageName } : null,
|
||||||
|
apple: config.apple ? { bundleId: config.apple.bundleId, appId: config.apple.appId ?? null } : null,
|
||||||
|
platforms: platformsOf(config),
|
||||||
|
products: config.products?.length ?? 0,
|
||||||
|
productIds: (config.products ?? []).map(p => p.id),
|
||||||
|
subscriptions: subs.length,
|
||||||
|
subscriptionIds: subs.map(s => s.id),
|
||||||
|
// the catalog each store should sell (items can be limited to one platform)
|
||||||
|
catalog: {
|
||||||
|
ios: config.apple ? [...(config.products ?? []), ...subs].filter(x => sellsOn(config, x, 'apple')).map(x => x.id) : [],
|
||||||
|
android: config.play ? [...(config.products ?? []), ...subs].filter(x => sellsOn(config, x, 'play')).map(x => x.id) : [],
|
||||||
|
},
|
||||||
|
shots: !!config.shots,
|
||||||
|
testflightGroups: config.apple?.testflight?.groups?.length ?? 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function run(ctx: Ctx): Promise<void> {
|
||||||
|
const s = summarize(ctx);
|
||||||
|
if (ctx.args.has('json')) { printJson(s); return; }
|
||||||
|
log('inspect', `${s.name} · ${s.platforms.join(' + ')} · ${s.languages.length} languages · ${s.products} products · ${s.subscriptions} subscriptions`);
|
||||||
|
log('inspect', `play ${s.play?.packageName ?? '-'} · apple ${s.apple?.bundleId ?? '-'}${s.apple?.appId ? ` (${s.apple.appId})` : ''}`);
|
||||||
|
log('inspect', `config ${s.config}`);
|
||||||
|
}
|
||||||
|
|
@ -617,14 +617,14 @@ export function validateConfig(c: unknown): string[] {
|
||||||
|
|
||||||
export interface Loaded { config: ShipConfig; root: string; path: string; resolve(p: string): string }
|
export interface Loaded { config: ShipConfig; root: string; path: string; resolve(p: string): string }
|
||||||
|
|
||||||
const NAMES = ['storebound.config.ts', 'storebound.config.js', 'storebound.config.json'];
|
export const CONFIG_NAMES = ['storebound.config.ts', 'storebound.config.js', 'storebound.config.json'];
|
||||||
|
|
||||||
/** Finds storebound.config.* from `start` upwards (or uses `explicit`), imports and validates it. */
|
/** Finds storebound.config.* from `start` upwards (or uses `explicit`), imports and validates it. */
|
||||||
export async function loadConfig(explicit?: string, start = process.cwd()): Promise<Loaded> {
|
export async function loadConfig(explicit?: string, start = process.cwd()): Promise<Loaded> {
|
||||||
let path = explicit ? resolve(explicit) : '';
|
let path = explicit ? resolve(explicit) : '';
|
||||||
if (!path) {
|
if (!path) {
|
||||||
for (let d = resolve(start); ; d = dirname(d)) {
|
for (let d = resolve(start); ; d = dirname(d)) {
|
||||||
const hit = NAMES.map(n => join(d, n)).find(existsSync);
|
const hit = CONFIG_NAMES.map(n => join(d, n)).find(existsSync);
|
||||||
if (hit) { path = hit; break; }
|
if (hit) { path = hit; break; }
|
||||||
if (dirname(d) === d) break;
|
if (dirname(d) === d) break;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
95
cli/lib/confirm-token.ts
Normal file
95
cli/lib/confirm-token.ts
Normal file
|
|
@ -0,0 +1,95 @@
|
||||||
|
// Confirm tokens for `storebound serve --stdio` (the desktop app's sidecar protocol).
|
||||||
|
//
|
||||||
|
// A write method only runs for real (dryRun: false) with a token that the desktop host mints after the owner said yes
|
||||||
|
// in a native dialog showing the dry run. The token is an HMAC over the method, the canonical params and an expiry,
|
||||||
|
// keyed with a per-session secret the host generates and hands over in `session.hello` on stdin. Only the process that
|
||||||
|
// owns the sidecar's stdin (the Rust host) knows the secret; the webview never sees it, and child commands never get it
|
||||||
|
// (runner.ts strips STOREBOUND_SESSION* from their env, and the secret never is in the env to begin with).
|
||||||
|
//
|
||||||
|
// token = "sbt1." + expiryMs + "." + nonce + "." + base64url(HMAC-SHA256(secret, payload))
|
||||||
|
// payload = "storebound-confirm-v1\n" + method + "\n" + canonical(params) + "\n" + expiryMs + "\n" + nonce
|
||||||
|
//
|
||||||
|
// Tokens are single use (nonce kept until expiry), live at most MAX_TTL_MS, and are bound to the exact method and
|
||||||
|
// params: another project, other arguments or another method do not verify. The Rust side (apps/desktop/src-tauri/
|
||||||
|
// src/confirm.rs) implements the same scheme; both test the shared vector in tests/serve.test.ts and tests/confirm.rs.
|
||||||
|
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||||
|
|
||||||
|
export const TOKEN_PREFIX = 'sbt1';
|
||||||
|
export const DOMAIN = 'storebound-confirm-v1';
|
||||||
|
/** A token may not be valid for longer than this (the host mints 60 s ones right after the dialog). */
|
||||||
|
export const MAX_TTL_MS = 120_000;
|
||||||
|
export const MIN_SECRET_BYTES = 32;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Canonical JSON: object keys sorted (by UTF-16 code units, like JS sort), no whitespace, strings escaped by
|
||||||
|
* JSON.stringify. Numbers must be safe integers so every language prints them the same way; undefined object
|
||||||
|
* members are dropped, like JSON.stringify does.
|
||||||
|
*/
|
||||||
|
export function canonical(v: unknown): string {
|
||||||
|
if (v === null) return 'null';
|
||||||
|
if (typeof v === 'boolean') return v ? 'true' : 'false';
|
||||||
|
if (typeof v === 'number') {
|
||||||
|
if (!Number.isSafeInteger(v)) throw new Error('canonical: only safe integers are allowed as numbers');
|
||||||
|
return String(v);
|
||||||
|
}
|
||||||
|
if (typeof v === 'string') return JSON.stringify(v);
|
||||||
|
if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`;
|
||||||
|
if (typeof v === 'object') {
|
||||||
|
const o = v as Record<string, unknown>;
|
||||||
|
const keys = Object.keys(o).filter(k => o[k] !== undefined).sort();
|
||||||
|
return `{${keys.map(k => `${JSON.stringify(k)}:${canonical(o[k])}`).join(',')}}`;
|
||||||
|
}
|
||||||
|
throw new Error(`canonical: unsupported ${typeof v}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const b64url = (b: Buffer): string => b.toString('base64url');
|
||||||
|
|
||||||
|
export function payload(method: string, params: unknown, expiry: number, nonce: string): string {
|
||||||
|
return `${DOMAIN}\n${method}\n${canonical(params)}\n${expiry}\n${nonce}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mac(secret: Buffer, method: string, params: unknown, expiry: number, nonce: string): string {
|
||||||
|
return b64url(createHmac('sha256', secret).update(payload(method, params, expiry, nonce), 'utf8').digest());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mints a token (the host does this in Rust; here for tests and tools). */
|
||||||
|
export function mint(secret: Buffer, method: string, params: unknown, o: { now?: number; ttlMs?: number; nonce?: string } = {}): string {
|
||||||
|
const expiry = (o.now ?? Date.now()) + (o.ttlMs ?? 60_000);
|
||||||
|
const nonce = o.nonce ?? b64url(randomBytes(16));
|
||||||
|
return `${TOKEN_PREFIX}.${expiry}.${nonce}.${mac(secret, method, params, expiry, nonce)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseSecret(hex: unknown): Buffer {
|
||||||
|
if (typeof hex !== 'string' || !/^[0-9a-f]+$/i.test(hex) || hex.length % 2) throw new Error('secret: hex string expected');
|
||||||
|
const b = Buffer.from(hex, 'hex');
|
||||||
|
if (b.length < MIN_SECRET_BYTES) throw new Error(`secret: at least ${MIN_SECRET_BYTES} bytes`);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type VerifyError = 'malformed' | 'expired' | 'too-long' | 'replayed' | 'mismatch';
|
||||||
|
|
||||||
|
/** Verifies tokens of one session and remembers used nonces until they expire (replay protection). */
|
||||||
|
export class TokenGuard {
|
||||||
|
private used = new Map<string, number>();
|
||||||
|
constructor(private readonly secret: Buffer, private readonly clock: () => number = Date.now) {}
|
||||||
|
|
||||||
|
verify(token: unknown, method: string, params: unknown): { ok: true } | { ok: false; error: VerifyError } {
|
||||||
|
const now = this.clock();
|
||||||
|
for (const [n, exp] of this.used) if (exp <= now) this.used.delete(n);
|
||||||
|
if (typeof token !== 'string') return { ok: false, error: 'malformed' };
|
||||||
|
const parts = token.split('.');
|
||||||
|
if (parts.length !== 4 || parts[0] !== TOKEN_PREFIX) return { ok: false, error: 'malformed' };
|
||||||
|
const [, exp, nonce, sig] = parts as [string, string, string, string];
|
||||||
|
if (!/^\d{1,16}$/.test(exp) || !/^[A-Za-z0-9_-]{16,64}$/.test(nonce) || !/^[A-Za-z0-9_-]{43}$/.test(sig)) return { ok: false, error: 'malformed' };
|
||||||
|
const expiry = Number(exp);
|
||||||
|
let want: string;
|
||||||
|
try { want = mac(this.secret, method, params, expiry, nonce); } catch { return { ok: false, error: 'malformed' }; }
|
||||||
|
const a = Buffer.from(sig), b = Buffer.from(want);
|
||||||
|
if (a.length !== b.length || !timingSafeEqual(a, b)) return { ok: false, error: 'mismatch' };
|
||||||
|
if (expiry <= now) return { ok: false, error: 'expired' };
|
||||||
|
if (expiry - now > MAX_TTL_MS) return { ok: false, error: 'too-long' };
|
||||||
|
if (this.used.has(nonce)) return { ok: false, error: 'replayed' };
|
||||||
|
this.used.set(nonce, expiry);
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -21,8 +21,13 @@ export function byAppleLocale(langs: Language[]): Map<string, Language> {
|
||||||
return new Map(langs.filter(l => l.apple).map(l => [l.apple!, l] as const));
|
return new Map(langs.filter(l => l.apple).map(l => [l.apple!, l] as const));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Asks on the terminal unless --yes. Store actions that are public or irreversible go through this. */
|
/**
|
||||||
|
* Asks on the terminal unless --yes. Store actions that are public or irreversible go through this.
|
||||||
|
* Under `storebound serve` (the desktop sidecar) nothing can answer and nothing may skip the question, not even --yes:
|
||||||
|
* those actions stay terminal-only, so the answer is always no.
|
||||||
|
*/
|
||||||
export async function confirm(ctx: Ctx, question: string): Promise<boolean> {
|
export async function confirm(ctx: Ctx, question: string): Promise<boolean> {
|
||||||
|
if (process.env.STOREBOUND_SERVE === '1') { console.error(`confirm-required: ${question}\n terminal only: run it in a terminal`); return false; }
|
||||||
if (ctx.args.has('yes')) return true;
|
if (ctx.args.has('yes')) return true;
|
||||||
if (!process.stdin.isTTY) { console.log(`${question}\n not a terminal: re-run with --yes to confirm`); return false; }
|
if (!process.stdin.isTTY) { console.log(`${question}\n not a terminal: re-run with --yes to confirm`); return false; }
|
||||||
process.stdout.write(`${question} [y/N] `);
|
process.stdout.write(`${question} [y/N] `);
|
||||||
|
|
|
||||||
154
cli/lib/desktop-protocol.ts
Normal file
154
cli/lib/desktop-protocol.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
// Types of the `storebound serve --stdio` protocol (desktop profile). Type-only, no runtime code: the desktop app
|
||||||
|
// (apps/desktop) imports this file so both sides agree on shapes. Newline-delimited JSON-RPC 2.0 on stdio.
|
||||||
|
//
|
||||||
|
// Session: the first request must be `session.hello` with the per-session secret (hex, >= 32 bytes) the host
|
||||||
|
// generated. Every other method answers -32002 before that. One hello per process.
|
||||||
|
// Progress: notifications `progress` { requestId, line?, stream?, n?, total?, project? } while a request runs.
|
||||||
|
// Cancel: notification `$/cancelRequest` { id } (or MCP-style `notifications/cancelled` { requestId }); the request
|
||||||
|
// then answers -32800.
|
||||||
|
// Writes: every write method is a dry run unless `dryRun: false` comes with a `confirmToken` minted by the host for
|
||||||
|
// exactly (method, { project, args }) (cli/lib/confirm-token.ts). No method submits, releases or publishes anything.
|
||||||
|
|
||||||
|
export const DESKTOP_PROTOCOL = 'storebound-desktop/1';
|
||||||
|
|
||||||
|
export const ERR = {
|
||||||
|
parse: -32700,
|
||||||
|
invalidRequest: -32600,
|
||||||
|
methodNotFound: -32601,
|
||||||
|
invalidParams: -32602,
|
||||||
|
internal: -32603,
|
||||||
|
notInitialized: -32002,
|
||||||
|
confirmRequired: -32010,
|
||||||
|
confirmInvalid: -32011,
|
||||||
|
cancelled: -32800,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export interface JsonSchemaLite { type: string; description?: string; enum?: (string | number)[]; default?: unknown; minimum?: number; maximum?: number; pattern?: string }
|
||||||
|
|
||||||
|
export interface MethodDescriptor {
|
||||||
|
method: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio';
|
||||||
|
/** Talks to a store API or the internet. */
|
||||||
|
network: boolean;
|
||||||
|
/** Replaces existing data on a store (screenshots, whole forms). */
|
||||||
|
destructive: boolean;
|
||||||
|
/** Result carries structured `data` (the command's --json output). */
|
||||||
|
json: boolean;
|
||||||
|
/** Schema of `params.args` (tool methods), or of `params` (other methods). */
|
||||||
|
args: { type: 'object'; properties: Record<string, JsonSchemaLite>; required?: string[]; additionalProperties: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HelloParams { secret: string; client?: { name: string; version: string } }
|
||||||
|
export interface HelloResult { protocol: typeof DESKTOP_PROTOCOL; server: { name: 'storebound'; version: string; compiled: boolean }; methods: MethodDescriptor[] }
|
||||||
|
|
||||||
|
export interface Credentials { PLAY_SERVICE_ACCOUNT?: string; ASC_KEY_ID?: string; ASC_ISSUER_ID?: string; ASC_P8?: string }
|
||||||
|
|
||||||
|
export interface ToolParams {
|
||||||
|
/** Absolute path of a folder that contains storebound.config.ts. */
|
||||||
|
project: string;
|
||||||
|
args?: Record<string, unknown>;
|
||||||
|
/** Write methods: false runs for real and needs confirmToken. Default true. */
|
||||||
|
dryRun?: boolean;
|
||||||
|
confirmToken?: string;
|
||||||
|
/** Per-call credentials (kept in memory, passed to the command's env only). Not part of the token. */
|
||||||
|
credentials?: Credentials;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ToolResult {
|
||||||
|
method: string;
|
||||||
|
ok: boolean;
|
||||||
|
exitCode: number;
|
||||||
|
dryRun: boolean;
|
||||||
|
/** The CLI line it ran, for logs ("storebound play listing --dry"). */
|
||||||
|
command: string;
|
||||||
|
/** Text output (log lines), trimmed to the last 60 000 characters. */
|
||||||
|
output: string;
|
||||||
|
/** Structured result of a --json capable command. */
|
||||||
|
data?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProgressParams { requestId: string | number; line?: string; stream?: 'stdout' | 'stderr'; n?: number; total?: number; project?: string }
|
||||||
|
|
||||||
|
export interface ProjectSummary {
|
||||||
|
dir: string;
|
||||||
|
config: string;
|
||||||
|
name: string;
|
||||||
|
languages: string[];
|
||||||
|
play: { packageName: string } | null;
|
||||||
|
apple: { bundleId: string; appId: string | null } | null;
|
||||||
|
/** app.platforms (default: from the apple / play sections). */
|
||||||
|
platforms: ('ios' | 'android')[];
|
||||||
|
/** One-time in-app products in the config (one shared catalog). */
|
||||||
|
products: number;
|
||||||
|
productIds: string[];
|
||||||
|
/** Auto-renewable subscriptions in the config (all groups). */
|
||||||
|
subscriptions: number;
|
||||||
|
subscriptionIds: string[];
|
||||||
|
/** Product and subscription ids each store should sell (items may be limited to one platform). */
|
||||||
|
catalog: { ios: string[]; android: string[] };
|
||||||
|
shots: boolean;
|
||||||
|
testflightGroups: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- App-centric model (one app = one product on up to two platforms; a workspace holds many apps) ----
|
||||||
|
|
||||||
|
/** One product across platforms. id = its project folder (one storebound.config.ts per app). */
|
||||||
|
export interface AppIdentity {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
platforms: { ios: { bundleId: string; ascAppId: string | null } | null; android: { packageName: string } | null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a version is on one store. */
|
||||||
|
export type ReleasePhase = 'live' | 'rollout' | 'halted' | 'approved' | 'review' | 'rejected' | 'testing' | 'draft' | 'other';
|
||||||
|
|
||||||
|
export interface StoreRelease {
|
||||||
|
store: 'ios' | 'android';
|
||||||
|
version: string | null;
|
||||||
|
/** iOS build number (CFBundleVersion) / highest Android versionCode. */
|
||||||
|
build: string | null;
|
||||||
|
/** The store's own state word (READY_FOR_SALE, inProgress ...). */
|
||||||
|
state: string;
|
||||||
|
phase: ReleasePhase;
|
||||||
|
/** Android staged rollout user fraction (0-1); iOS phased release percentage comes with D2. */
|
||||||
|
fraction: number | null;
|
||||||
|
/** Android track (production, beta, internal ...). */
|
||||||
|
track: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A release train: one version (e.g. 2.3.0) across both stores. */
|
||||||
|
export interface ReleaseTrain { version: string; ios: StoreRelease | null; android: StoreRelease | null }
|
||||||
|
|
||||||
|
/** In-app catalog parity between the config and both stores. */
|
||||||
|
export interface CatalogParity {
|
||||||
|
checked: 'config' | 'live';
|
||||||
|
products: number;
|
||||||
|
subscriptions: number;
|
||||||
|
/** Live: ids on one store only, and config ids missing on a store the app is on. */
|
||||||
|
onlyIos: string[];
|
||||||
|
onlyAndroid: string[];
|
||||||
|
missingIos: string[];
|
||||||
|
missingAndroid: string[];
|
||||||
|
ok: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PortfolioParams { projects: string[]; live?: boolean; credentials?: Credentials }
|
||||||
|
|
||||||
|
export interface AppStatus {
|
||||||
|
/** Project folder as given. */
|
||||||
|
project: string;
|
||||||
|
ok: boolean;
|
||||||
|
app: AppIdentity | null;
|
||||||
|
summary: ProjectSummary | null;
|
||||||
|
check: { ok: boolean; problems: string[]; warnings: string[] } | null;
|
||||||
|
/** Release trains; `source: none` offline (no store data read). */
|
||||||
|
release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null };
|
||||||
|
catalog: CatalogParity | null;
|
||||||
|
/** live only: per-platform read errors ("unknown, never false"). */
|
||||||
|
storeErrors: { ios?: string; android?: string };
|
||||||
|
errors: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PortfolioResult { apps: AppStatus[]; at: string }
|
||||||
|
|
@ -10,3 +10,15 @@ export const done = (tag: string, msg: string): void => console.log(`${stamp()}
|
||||||
|
|
||||||
/** "3/14 de-DE" style counters. */
|
/** "3/14 de-DE" style counters. */
|
||||||
export const step = (i: number, n: number, what: string): string => `${String(i).padStart(String(n).length)}/${n} ${what}`;
|
export const step = (i: number, n: number, what: string): string => `${String(i).padStart(String(n).length)}/${n} ${what}`;
|
||||||
|
|
||||||
|
/** Prefix of the one machine-readable result line that `storebound serve --stdio` reads from a child command. */
|
||||||
|
export const RESULT_MARK = '\u001estorebound-result ';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Structured result of a `--json` run. In a terminal (or a pipe) it is pretty JSON on stdout as before; under
|
||||||
|
* `storebound serve` (STOREBOUND_MACHINE=1) it is one marked line, so log lines printed before it never break parsing.
|
||||||
|
*/
|
||||||
|
export function printJson(data: unknown): void {
|
||||||
|
if (process.env.STOREBOUND_MACHINE === '1') process.stdout.write(RESULT_MARK + JSON.stringify(data) + '\n');
|
||||||
|
else console.log(JSON.stringify(data, null, 2));
|
||||||
|
}
|
||||||
|
|
|
||||||
101
cli/lib/portfolio.ts
Normal file
101
cli/lib/portfolio.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
||||||
|
// Pure pieces of `portfolio.status` (serve.ts): an app's identity across platforms, its release trains (one version
|
||||||
|
// across the App Store and Google Play) and the in-app catalog parity between the config and both stores.
|
||||||
|
// Inputs are the `apple status --json` / `play status --json` results, read defensively: "unknown, never false".
|
||||||
|
import type { AppIdentity, CatalogParity, ProjectSummary, ReleasePhase, ReleaseTrain, StoreRelease } from './desktop-protocol';
|
||||||
|
|
||||||
|
type J = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||||
|
|
||||||
|
export function appIdentity(s: ProjectSummary): AppIdentity {
|
||||||
|
return {
|
||||||
|
id: s.dir,
|
||||||
|
name: s.name,
|
||||||
|
platforms: {
|
||||||
|
ios: s.apple && s.platforms.includes('ios') ? { bundleId: s.apple.bundleId, ascAppId: s.apple.appId } : null,
|
||||||
|
android: s.play && s.platforms.includes('android') ? { packageName: s.play.packageName } : null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Numeric compare of dotted versions ("2.10.0" > "2.9.1"); non-numeric parts compare as 0. */
|
||||||
|
export function cmpVersion(a: string, b: string): number {
|
||||||
|
const pa = a.split('.').map(x => parseInt(x, 10) || 0), pb = b.split('.').map(x => parseInt(x, 10) || 0);
|
||||||
|
for (let i = 0; i < Math.max(pa.length, pb.length); i++) { const d = (pa[i] ?? 0) - (pb[i] ?? 0); if (d) return d; }
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** App Store version states (appStoreState / appVersionState) -> phase. */
|
||||||
|
export function applePhase(state: string): ReleasePhase {
|
||||||
|
if (/^(READY_FOR_SALE|READY_FOR_DISTRIBUTION)$/.test(state)) return 'live';
|
||||||
|
if (/^(PENDING_DEVELOPER_RELEASE|PENDING_APPLE_RELEASE|ACCEPTED)$/.test(state)) return 'approved';
|
||||||
|
if (/^(WAITING_FOR_REVIEW|IN_REVIEW|WAITING_FOR_EXPORT_COMPLIANCE|PROCESSING_FOR_DISTRIBUTION|PROCESSING_FOR_APP_STORE)$/.test(state)) return 'review';
|
||||||
|
if (/REJECTED$/.test(state)) return 'rejected';
|
||||||
|
if (/^(PREPARE_FOR_SUBMISSION|DEVELOPER_ACTION_NEEDED)$/.test(state)) return 'draft';
|
||||||
|
return 'other';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function appleReleases(data: unknown): StoreRelease[] {
|
||||||
|
const versions = ((data as J)?.versions ?? []) as J[];
|
||||||
|
const builds = new Map((((data as J)?.builds ?? []) as J[]).map(b => [b.id, b.attributes?.version] as const));
|
||||||
|
return versions.filter(v => typeof v?.attributes?.versionString === 'string' && (v.attributes.platform ?? 'IOS') === 'IOS').map(v => {
|
||||||
|
const state = String(v.attributes.appVersionState ?? v.attributes.appStoreState ?? 'UNKNOWN');
|
||||||
|
const buildId = v.relationships?.build?.data?.id;
|
||||||
|
return { store: 'ios', version: v.attributes.versionString as string, build: (buildId && builds.get(buildId)) ? String(builds.get(buildId)) : null, state, phase: applePhase(state), fraction: null, track: null };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Leading dotted version of a Play release name ("2.3.0 (45)" -> "2.3.0"). */
|
||||||
|
export const versionOfName = (name: unknown): string | null => (typeof name === 'string' ? name.match(/\d+(?:\.\d+){0,3}/)?.[0] ?? null : null);
|
||||||
|
|
||||||
|
export function playReleases(data: unknown): StoreRelease[] {
|
||||||
|
const out: StoreRelease[] = [];
|
||||||
|
for (const t of ((data as J)?.tracks ?? []) as J[]) {
|
||||||
|
for (const r of (t?.releases ?? []) as J[]) {
|
||||||
|
const codes = ((r.versionCodes ?? []) as unknown[]).map(Number).filter(Number.isFinite);
|
||||||
|
const production = t.track === 'production';
|
||||||
|
const status = String(r.status ?? 'unknown');
|
||||||
|
const phase: ReleasePhase = !production ? (status === 'draft' ? 'draft' : 'testing')
|
||||||
|
: status === 'completed' ? 'live' : status === 'inProgress' ? 'rollout' : status === 'halted' ? 'halted' : status === 'draft' ? 'draft' : 'other';
|
||||||
|
out.push({ store: 'android', version: versionOfName(r.name), build: codes.length ? String(Math.max(...codes)) : null, state: status, phase, fraction: typeof r.userFraction === 'number' ? r.userFraction : null, track: String(t.track) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PHASE_RANK: Record<ReleasePhase, number> = { live: 0, rollout: 1, halted: 2, approved: 3, review: 4, rejected: 5, testing: 6, draft: 7, other: 8 };
|
||||||
|
const pick = (rs: StoreRelease[]): StoreRelease | null => [...rs].sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase])[0] ?? null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Release trains: one version across both stores. current = the highest version that is live (fully) on a store;
|
||||||
|
* next = the highest version above it on either store (review, testing, rollout, draft ...). A store without that
|
||||||
|
* version has null in the train.
|
||||||
|
*/
|
||||||
|
export function releaseTrains(ios: StoreRelease[], android: StoreRelease[]): { current: ReleaseTrain | null; next: ReleaseTrain | null } {
|
||||||
|
const all = [...ios, ...android].filter((r): r is StoreRelease & { version: string } => !!r.version);
|
||||||
|
const train = (v: string): ReleaseTrain => ({ version: v, ios: pick(all.filter(r => r.store === 'ios' && r.version === v)), android: pick(all.filter(r => r.store === 'android' && r.version === v)) });
|
||||||
|
const live = all.filter(r => r.phase === 'live').map(r => r.version).sort(cmpVersion).at(-1) ?? null;
|
||||||
|
const above = all.filter(r => !live || cmpVersion(r.version, live) > 0).map(r => r.version).sort(cmpVersion).at(-1) ?? null;
|
||||||
|
return { current: live ? train(live) : null, next: above ? train(above) : null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Product ids on App Store Connect (`apple status --json` iaps) and Google Play (`play status --json` products). */
|
||||||
|
export const appleProductIds = (data: unknown): string[] => (((data as J)?.iaps ?? []) as J[]).map(p => p?.attributes?.productId).filter((x): x is string => typeof x === 'string');
|
||||||
|
export const playProductIds = (data: unknown): string[] => (((data as J)?.products ?? []) as J[]).map(p => p?.productId ?? p?.sku).filter((x): x is string => typeof x === 'string');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Catalog parity. Without store data (offline) only the config side is known. With it: ids only on one store,
|
||||||
|
* and config ids missing from a store the app is on.
|
||||||
|
*/
|
||||||
|
export function catalogParity(s: ProjectSummary, apple?: string[], play?: string[]): CatalogParity {
|
||||||
|
const live = apple !== undefined || play !== undefined;
|
||||||
|
const onlyIos = apple && play ? apple.filter(x => !play.includes(x)) : [];
|
||||||
|
const onlyAndroid = apple && play ? play.filter(x => !apple.includes(x)) : [];
|
||||||
|
// the status reads list one-time products; subscriptions are compared by `catalog diff` (catalog.diff method)
|
||||||
|
const sold = (ids: string[]) => ids.filter(x => s.productIds.includes(x));
|
||||||
|
const missingIos = apple ? sold(s.catalog.ios).filter(x => !apple.includes(x)) : [];
|
||||||
|
const missingAndroid = play ? sold(s.catalog.android).filter(x => !play.includes(x)) : [];
|
||||||
|
return {
|
||||||
|
checked: live ? 'live' : 'config', products: s.products, subscriptions: s.subscriptions,
|
||||||
|
onlyIos, onlyAndroid, missingIos, missingAndroid,
|
||||||
|
ok: !onlyIos.length && !onlyAndroid.length && !missingIos.length && !missingAndroid.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
82
cli/lib/runner.ts
Normal file
82
cli/lib/runner.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
// Runs one storebound command as a child process: the shared core of `storebound mcp` and `storebound serve --stdio`.
|
||||||
|
// Works from source (`bun cli/index.ts ...`) and from a `bun build --compile` binary (the desktop sidecar), where the
|
||||||
|
// binary re-executes itself. Output is streamed line by line (progress) and the `--json` result line is picked out.
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { RESULT_MARK } from './log';
|
||||||
|
import { toolPath } from './tools';
|
||||||
|
|
||||||
|
/** True inside a `bun build --compile` executable (the entry module lives in Bun's embedded file system). */
|
||||||
|
export const compiled = (): boolean => /^(\/\$bunfs\/|[A-Z]:[\\/]~BUN[\\/])/.test(Bun.main);
|
||||||
|
|
||||||
|
/** Command prefix that starts this storebound: the compiled binary itself, or bun + cli/index.ts. */
|
||||||
|
export function selfCommand(): string[] {
|
||||||
|
return compiled() ? [process.execPath] : [process.execPath, join(import.meta.dir, '..', 'index.ts')];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RunOptions {
|
||||||
|
cwd: string;
|
||||||
|
/** Extra environment for this call only (credentials from the desktop keychain, never written anywhere). */
|
||||||
|
env?: Record<string, string>;
|
||||||
|
/** Every output line as it arrives (stdout and stderr), without the machine result line. */
|
||||||
|
onLine?: (line: string, stream: 'stdout' | 'stderr') => void;
|
||||||
|
/** Ask for the marked `--json` result line (STOREBOUND_MACHINE=1). */
|
||||||
|
machine?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RunResult { code: number; out: string; data?: unknown; cancelled: boolean }
|
||||||
|
|
||||||
|
export interface Running { result: Promise<RunResult>; cancel(): void }
|
||||||
|
|
||||||
|
/** Env names a caller may pass per call; anything else in `env` is ignored. */
|
||||||
|
export const CALL_ENV = ['PLAY_SERVICE_ACCOUNT', 'ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8'] as const;
|
||||||
|
|
||||||
|
export function pickCallEnv(env: Record<string, unknown> | undefined): Record<string, string> {
|
||||||
|
const out: Record<string, string> = {};
|
||||||
|
for (const k of CALL_ENV) { const v = env?.[k]; if (typeof v === 'string' && v) out[k] = v; }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Environment of a child: the parent's minus anything secret to the session, plus the per-call values. */
|
||||||
|
export function childEnv(extra: Record<string, string> = {}, machine = false): Record<string, string> {
|
||||||
|
const base: Record<string, string> = {};
|
||||||
|
for (const [k, v] of Object.entries(process.env)) if (v !== undefined && !k.startsWith('STOREBOUND_SESSION')) base[k] = v;
|
||||||
|
// app-managed tools (desktop data folder) come first on PATH
|
||||||
|
if (base.STOREBOUND_TOOL_PATH) base.PATH = toolPath(base);
|
||||||
|
return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pump(stream: ReadableStream<Uint8Array>, kind: 'stdout' | 'stderr', each: (line: string, kind: 'stdout' | 'stderr') => void): Promise<void> {
|
||||||
|
const dec = new TextDecoder();
|
||||||
|
let buf = '';
|
||||||
|
const reader = stream.getReader();
|
||||||
|
for (;;) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buf += dec.decode(value, { stream: true });
|
||||||
|
let nl: number;
|
||||||
|
while ((nl = buf.indexOf('\n')) >= 0) { each(buf.slice(0, nl).replace(/\r$/, ''), kind); buf = buf.slice(nl + 1); }
|
||||||
|
}
|
||||||
|
buf += dec.decode();
|
||||||
|
if (buf) each(buf, kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runCommand(argv: string[], o: RunOptions): Running {
|
||||||
|
const p = Bun.spawn([...selfCommand(), ...argv], { cwd: o.cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: childEnv(o.env, o.machine) });
|
||||||
|
let cancelled = false;
|
||||||
|
const lines: string[] = [];
|
||||||
|
let data: unknown;
|
||||||
|
const each = (line: string, kind: 'stdout' | 'stderr'): void => {
|
||||||
|
if (kind === 'stdout' && line.startsWith(RESULT_MARK)) {
|
||||||
|
try { data = JSON.parse(line.slice(RESULT_MARK.length)); } catch { lines.push(line); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lines.push(line);
|
||||||
|
o.onLine?.(line, kind);
|
||||||
|
};
|
||||||
|
const result = (async (): Promise<RunResult> => {
|
||||||
|
await Promise.all([pump(p.stdout, 'stdout', each), pump(p.stderr, 'stderr', each)]);
|
||||||
|
const code = await p.exited;
|
||||||
|
return { code, out: lines.join('\n').trim(), ...(data === undefined ? {} : { data }), cancelled };
|
||||||
|
})();
|
||||||
|
return { result, cancel: () => { cancelled = true; p.kill(); } };
|
||||||
|
}
|
||||||
90
cli/lib/tools.ts
Normal file
90
cli/lib/tools.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
// Optional local tools storebound uses (screenshots, previews, icons, simulator and emulator captures), found on this
|
||||||
|
// machine with their versions. The desktop app can manage its own copies of ffmpeg and Chrome for Testing in its data
|
||||||
|
// folder and points storebound at them:
|
||||||
|
// STOREBOUND_TOOL_PATH folders put in front of PATH for every command (app-managed ffmpeg / ffprobe)
|
||||||
|
// STOREBOUND_CHROME Chrome / Chrome for Testing executable for renders and web captures
|
||||||
|
// Nothing is installed system-wide. Sources and licenses: docs/desktop.md.
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { delimiter, join } from 'node:path';
|
||||||
|
|
||||||
|
export type ToolId = 'ffmpeg' | 'ffprobe' | 'chrome' | 'xcode' | 'simctl' | 'adb' | 'git';
|
||||||
|
|
||||||
|
export interface ToolStatus {
|
||||||
|
id: ToolId;
|
||||||
|
name: string;
|
||||||
|
found: boolean;
|
||||||
|
path: string | null;
|
||||||
|
version: string | null;
|
||||||
|
/** 'app' = the desktop app's own copy (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME), 'system' = installed by the user. */
|
||||||
|
source: 'app' | 'system' | null;
|
||||||
|
/** What needs it. */
|
||||||
|
usedFor: string;
|
||||||
|
/** How to get it: the desktop app downloads ffmpeg and Chrome for Testing; Xcode and the Android SDK are link-out. */
|
||||||
|
install: { kind: 'download' | 'link'; url: string; note: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PATH with the app-managed tool folders first. */
|
||||||
|
export function toolPath(env: Record<string, string | undefined> = process.env): string {
|
||||||
|
const extra = (env.STOREBOUND_TOOL_PATH ?? '').split(delimiter).filter(Boolean);
|
||||||
|
return [...extra, env.PATH ?? ''].filter(Boolean).join(delimiter);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** First line of `<cmd> <args>` (version banners), or null. */
|
||||||
|
function firstLine(cmd: string[], env: Record<string, string>): string | null {
|
||||||
|
try {
|
||||||
|
const r = Bun.spawnSync(cmd, { stdout: 'pipe', stderr: 'pipe', env, timeout: 5_000 });
|
||||||
|
if (r.exitCode !== 0) return null;
|
||||||
|
return (r.stdout.toString() || r.stderr.toString()).trim().split('\n')[0]?.trim() || null;
|
||||||
|
} catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "ffmpeg version 7.1.1 Copyright ..." -> "7.1.1"; "Google Chrome for Testing 131.0.6778.85" -> "131.0.6778.85". */
|
||||||
|
export function parseVersion(line: string | null): string | null {
|
||||||
|
if (!line) return null;
|
||||||
|
return line.match(/version\s+([^\s,]+)/i)?.[1] ?? line.match(/(\d+(?:\.\d+)+)/)?.[1] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function systemChrome(platform = process.platform, env: Record<string, string | undefined> = process.env): string | null {
|
||||||
|
const c = platform === 'darwin' ? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome']
|
||||||
|
: platform === 'win32' ? [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter((d): d is string => !!d).map(d => join(d, 'Google/Chrome/Application/chrome.exe'))
|
||||||
|
: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser'];
|
||||||
|
return c.find(p => existsSync(p)) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const FFMPEG_NOTE = 'Static build into the app data folder (GPL; never bundled with the app). Checksum-verified.';
|
||||||
|
|
||||||
|
export function detectTools(env: Record<string, string | undefined> = process.env): ToolStatus[] {
|
||||||
|
const PATH = toolPath(env);
|
||||||
|
const spawnEnv: Record<string, string> = { ...Object.fromEntries(Object.entries(env).filter((e): e is [string, string] => e[1] !== undefined)), PATH };
|
||||||
|
const appDirs = (env.STOREBOUND_TOOL_PATH ?? '').split(delimiter).filter(Boolean);
|
||||||
|
const which = (n: string): string | null => Bun.which(n, { PATH });
|
||||||
|
const src = (p: string | null): ToolStatus['source'] => (!p ? null : appDirs.some(d => p.startsWith(d)) ? 'app' : 'system');
|
||||||
|
const bin = (id: ToolId, name: string, usedFor: string, install: ToolStatus['install'], versionArgs: string[]): ToolStatus => {
|
||||||
|
const path = which(id);
|
||||||
|
const version = path ? parseVersion(firstLine([path, ...versionArgs], spawnEnv)) : null;
|
||||||
|
return { id, name, found: !!path, path, version, source: src(path), usedFor, install };
|
||||||
|
};
|
||||||
|
const out: ToolStatus[] = [
|
||||||
|
bin('ffmpeg', 'ffmpeg', 'icons, screenshot renders, app preview videos, frame crops', { kind: 'download', url: 'https://ffmpeg.org/download.html', note: FFMPEG_NOTE }, ['-version']),
|
||||||
|
bin('ffprobe', 'ffprobe', 'checks of app preview videos and clips', { kind: 'download', url: 'https://ffmpeg.org/download.html', note: 'Comes with the ffmpeg download.' }, ['-version']),
|
||||||
|
];
|
||||||
|
const appChrome = env.STOREBOUND_CHROME && existsSync(env.STOREBOUND_CHROME) ? env.STOREBOUND_CHROME : null;
|
||||||
|
const chrome = appChrome ?? systemChrome(process.platform, env);
|
||||||
|
out.push({
|
||||||
|
id: 'chrome', name: appChrome ? 'Chrome for Testing' : 'Google Chrome', found: !!chrome, path: chrome,
|
||||||
|
version: chrome ? parseVersion(firstLine([chrome, '--version'], spawnEnv)) : null, source: appChrome ? 'app' : chrome ? 'system' : null,
|
||||||
|
usedFor: 'screenshot renders, captions, web captures and recordings',
|
||||||
|
install: { kind: 'download', url: 'https://googlechromelabs.github.io/chrome-for-testing/', note: 'Chrome for Testing from Google\'s official endpoints into the app data folder.' },
|
||||||
|
});
|
||||||
|
if (process.platform === 'darwin') {
|
||||||
|
const dev = firstLine(['xcode-select', '-p'], spawnEnv);
|
||||||
|
out.push({ id: 'xcode', name: 'Xcode command line tools', found: !!dev, path: dev, version: parseVersion(firstLine(['xcodebuild', '-version'], spawnEnv)), source: dev ? 'system' : null,
|
||||||
|
usedFor: 'iOS builds, the iOS Simulator (simctl)', install: { kind: 'link', url: 'https://developer.apple.com/xcode/', note: 'Install Xcode from the App Store or developer.apple.com.' } });
|
||||||
|
const simctl = firstLine(['xcrun', '--find', 'simctl'], spawnEnv);
|
||||||
|
out.push({ id: 'simctl', name: 'simctl (iOS Simulator)', found: !!simctl, path: simctl, version: null, source: simctl ? 'system' : null,
|
||||||
|
usedFor: 'iOS Simulator screenshots and recordings', install: { kind: 'link', url: 'https://developer.apple.com/xcode/', note: 'Part of Xcode.' } });
|
||||||
|
}
|
||||||
|
out.push(bin('adb', 'adb (Android platform tools)', 'Android emulator / device screenshots and recordings', { kind: 'link', url: 'https://developer.android.com/tools/releases/platform-tools', note: 'Install Android Studio or the SDK platform tools.' }, ['version']));
|
||||||
|
out.push(bin('git', 'git', 'release notes from history, analytics compare', { kind: 'link', url: 'https://git-scm.com/downloads', note: 'Install git from your OS package manager.' }, ['--version']));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
17
cli/mcp.ts
17
cli/mcp.ts
|
|
@ -20,8 +20,8 @@
|
||||||
// Every tool runs the CLI as a child process in the project directory (STOREBOUND_PROJECT or the server's cwd) and
|
// Every tool runs the CLI as a child process in the project directory (STOREBOUND_PROJECT or the server's cwd) and
|
||||||
// returns its output. stdout of this process carries protocol messages only; logs go to stderr.
|
// returns its output. stdout of this process carries protocol messages only; logs go to stderr.
|
||||||
// Tool list and safety rules: mcp-tools.ts (write tools default to dry_run, nothing public or irreversible exposed).
|
// Tool list and safety rules: mcp-tools.ts (write tools default to dry_run, nothing public or irreversible exposed).
|
||||||
import { join } from 'node:path';
|
|
||||||
import pkg from '../package.json' with { type: 'json' };
|
import pkg from '../package.json' with { type: 'json' };
|
||||||
|
import { runCommand, type Running } from './lib/runner';
|
||||||
import { listTools, TOOLS, toArgv, validateInput } from './mcp-tools';
|
import { listTools, TOOLS, toArgv, validateInput } from './mcp-tools';
|
||||||
|
|
||||||
/** Current (modern, stateless) revision. */
|
/** Current (modern, stateless) revision. */
|
||||||
|
|
@ -54,7 +54,6 @@ type Id = string | number;
|
||||||
interface Msg { jsonrpc: '2.0'; id?: Id; method?: string; params?: Record<string, unknown> }
|
interface Msg { jsonrpc: '2.0'; id?: Id; method?: string; params?: Record<string, unknown> }
|
||||||
|
|
||||||
const MAX_OUTPUT = 60_000;
|
const MAX_OUTPUT = 60_000;
|
||||||
const CLI = join(import.meta.dir, 'index.ts');
|
|
||||||
const serverInfo = () => ({ name: 'storebound', title: 'storebound', version: pkg.version });
|
const serverInfo = () => ({ name: 'storebound', title: 'storebound', version: pkg.version });
|
||||||
|
|
||||||
/** Era of one request: modern when its _meta names a modern (or unknown) protocol version, else legacy. */
|
/** Era of one request: modern when its _meta names a modern (or unknown) protocol version, else legacy. */
|
||||||
|
|
@ -117,17 +116,13 @@ export async function handle(m: Msg, run: (argv: string[], id: Id) => Promise<{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const running = new Map<Id, ReturnType<typeof Bun.spawn>>();
|
const running = new Map<Id, Running>();
|
||||||
function cancel(id: Id | undefined): void { if (id !== undefined) running.get(id)?.kill(); }
|
function cancel(id: Id | undefined): void { if (id !== undefined) running.get(id)?.cancel(); }
|
||||||
|
|
||||||
async function runCli(argv: string[], id: Id): Promise<{ code: number; out: string }> {
|
async function runCli(argv: string[], id: Id): Promise<{ code: number; out: string }> {
|
||||||
const cwd = process.env.STOREBOUND_PROJECT || process.cwd();
|
const r = runCommand(argv, { cwd: process.env.STOREBOUND_PROJECT || process.cwd() });
|
||||||
const p = Bun.spawn([process.execPath, CLI, ...argv], { cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NO_COLOR: '1' } });
|
running.set(id, r);
|
||||||
running.set(id, p);
|
try { const { code, out } = await r.result; return { code, out }; } finally { running.delete(id); }
|
||||||
try {
|
|
||||||
const [out, errText, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
|
|
||||||
return { code, out: (out + (errText ? `\n${errText}` : '')).trim() };
|
|
||||||
} finally { running.delete(id); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function serve(): Promise<void> {
|
export async function serve(): Promise<void> {
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
// ./gradlew bundleRelease -PversionCode=$(storebound play next-version-code)
|
// ./gradlew bundleRelease -PversionCode=$(storebound play next-version-code)
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { need } from '../lib/ctx';
|
import { need } from '../lib/ctx';
|
||||||
|
import { printJson } from '../lib/log';
|
||||||
import { nextVersionCode } from '../lib/release';
|
import { nextVersionCode } from '../lib/release';
|
||||||
import { playClient } from './client';
|
import { playClient } from './client';
|
||||||
|
|
||||||
|
|
@ -16,8 +17,11 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const apks = (await play.call<{ apks?: { versionCode: number }[] }>('GET', `${play.API}/edits/${e.id}/apks`).catch(() => ({ apks: [] }))).apks ?? [];
|
const apks = (await play.call<{ apks?: { versionCode: number }[] }>('GET', `${play.API}/edits/${e.id}/apks`).catch(() => ({ apks: [] }))).apks ?? [];
|
||||||
const tracks = (await play.call<{ tracks?: { releases?: { versionCodes?: string[] }[] }[] }>('GET', `${play.API}/edits/${e.id}/tracks`)).tracks ?? [];
|
const tracks = (await play.call<{ tracks?: { releases?: { versionCodes?: string[] }[] }[] }>('GET', `${play.API}/edits/${e.id}/tracks`)).tracks ?? [];
|
||||||
const codes = [...bundles.map(b => b.versionCode), ...apks.map(a => a.versionCode), ...tracks.flatMap(t => (t.releases ?? []).flatMap(r => r.versionCodes ?? []))];
|
const codes = [...bundles.map(b => b.versionCode), ...apks.map(a => a.versionCode), ...tracks.flatMap(t => (t.releases ?? []).flatMap(r => r.versionCodes ?? []))];
|
||||||
|
if (ctx.args.has('json')) printJson({ next: nextVersionCode(codes), seen: codes.length });
|
||||||
|
else {
|
||||||
console.error(`[play] ${codes.length} version codes seen; next versionCode:`);
|
console.error(`[play] ${codes.length} version codes seen; next versionCode:`);
|
||||||
console.log(nextVersionCode(codes));
|
console.log(nextVersionCode(codes));
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
await play.call('DELETE', `${play.API}/edits/${e.id}`).catch(() => {});
|
await play.call('DELETE', `${play.API}/edits/${e.id}`).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
// storebound play status [--json]
|
// storebound play status [--json]
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { need } from '../lib/ctx';
|
import { need } from '../lib/ctx';
|
||||||
|
import { printJson } from '../lib/log';
|
||||||
import { playClient } from './client';
|
import { playClient } from './client';
|
||||||
import { listOneTimeProducts } from './products';
|
import { listOneTimeProducts } from './products';
|
||||||
|
|
||||||
|
|
@ -16,7 +17,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const listings = (await play.call<{ listings?: { language: string }[] }>('GET', `${play.API}/edits/${e.id}/listings`)).listings ?? [];
|
const listings = (await play.call<{ listings?: { language: string }[] }>('GET', `${play.API}/edits/${e.id}/listings`)).listings ?? [];
|
||||||
const details = await play.call<Record<string, string>>('GET', `${play.API}/edits/${e.id}/details`);
|
const details = await play.call<Record<string, string>>('GET', `${play.API}/edits/${e.id}/details`);
|
||||||
const products = await listOneTimeProducts(play);
|
const products = await listOneTimeProducts(play);
|
||||||
if (ctx.args.has('json')) { console.log(JSON.stringify({ details, tracks, listings, products }, null, 2)); return; }
|
if (ctx.args.has('json')) { printJson({ details, tracks, listings, products }); return; }
|
||||||
console.log(`${play.packageName}\n details: ${details.defaultLanguage} · ${details.contactEmail ?? '-'} · ${details.contactWebsite ?? '-'}`);
|
console.log(`${play.packageName}\n details: ${details.defaultLanguage} · ${details.contactEmail ?? '-'} · ${details.contactWebsite ?? '-'}`);
|
||||||
console.log(` listings (${listings.length}): ${listings.map(l => l.language).join(', ') || '-'}`);
|
console.log(` listings (${listings.length}): ${listings.map(l => l.language).join(', ') || '-'}`);
|
||||||
for (const t of tracks) {
|
for (const t of tracks) {
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { ascClient, type Asc, type J } from './apple/asc';
|
import { ascClient, type Asc, type J } from './apple/asc';
|
||||||
import type { Ctx } from './lib/ctx';
|
import type { Ctx } from './lib/ctx';
|
||||||
import { confirm, need } from './lib/ctx';
|
import { confirm, need } from './lib/ctx';
|
||||||
import { done, log, step, warn } from './lib/log';
|
import { done, log, printJson, step, warn } from './lib/log';
|
||||||
import { toMoney } from './lib/money';
|
import { toMoney } from './lib/money';
|
||||||
import {
|
import {
|
||||||
appleSchedule, appleScheduleBody, applePriceRows, diffPrices, diffTable, parsePriceCsv, type PlayProduct, playPatchBody, playPriceRows, playRegions,
|
appleSchedule, appleScheduleBody, applePriceRows, diffPrices, diffTable, parsePriceCsv, type PlayProduct, playPatchBody, playPriceRows, playRegions,
|
||||||
|
|
@ -96,10 +96,12 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const wantedAll = parsePriceCsv(readFileSync(csvPath, 'utf8'), { products: config.products!.map(p => p.id) })
|
const wantedAll = parsePriceCsv(readFileSync(csvPath, 'utf8'), { products: config.products!.map(p => p.id) })
|
||||||
.filter(r => products.some(p => p.id === r.product) && ((r.store === 'apple' && useApple) || (r.store === 'play' && usePlay)));
|
.filter(r => products.some(p => p.id === r.product) && ((r.store === 'apple' && useApple) || (r.store === 'play' && usePlay)));
|
||||||
const diff = diffPrices(current, wantedAll);
|
const diff = diffPrices(current, wantedAll);
|
||||||
console.log(diffTable(diff, { all: a.has('all') }));
|
|
||||||
const changed = new Set(diff.filter(d => d.change !== 'same').map(d => `${d.product}|${d.store}`));
|
const changed = new Set(diff.filter(d => d.change !== 'same').map(d => `${d.product}|${d.store}`));
|
||||||
const reconvert = a.has('reconvert');
|
const reconvert = a.has('reconvert');
|
||||||
if (reconvert && usePlay) for (const p of products) if (playProducts.has(p.id)) changed.add(`${p.id}|play`);
|
if (reconvert && usePlay) for (const p of products) if (playProducts.has(p.id)) changed.add(`${p.id}|play`);
|
||||||
|
// --json is a read-only diff: it never writes, whatever the other flags say.
|
||||||
|
if (a.has('json')) { printJson({ csv: csvPath, diff: a.has('all') ? diff : diff.filter(d => d.change !== 'same'), changed: [...changed] }); return; }
|
||||||
|
console.log(diffTable(diff, { all: a.has('all') }));
|
||||||
if (!changed.size) { done(TAG, 'prices up to date'); return; }
|
if (!changed.size) { done(TAG, 'prices up to date'); return; }
|
||||||
log(TAG, `${changed.size} product / store pair(s) to update`);
|
log(TAG, `${changed.size} product / store pair(s) to update`);
|
||||||
if (dry) { done(TAG, 'dry run: nothing written'); return; }
|
if (dry) { done(TAG, 'dry run: nothing written'); return; }
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ import { join } from 'node:path';
|
||||||
import { ascClient, type J } from './apple/asc';
|
import { ascClient, type J } from './apple/asc';
|
||||||
import type { Ctx } from './lib/ctx';
|
import type { Ctx } from './lib/ctx';
|
||||||
import { confirm } from './lib/ctx';
|
import { confirm } from './lib/ctx';
|
||||||
import { done, log, warn } from './lib/log';
|
import { done, log, printJson, warn } from './lib/log';
|
||||||
import {
|
import {
|
||||||
checkReply, type Draft, draftMarkdown, draftName, filterReviews, markSent, parseAppleReviews, parseDraft, parsePlayReviews, replyRequest,
|
checkReply, type Draft, draftMarkdown, draftName, filterReviews, markSent, parseAppleReviews, parseDraft, parsePlayReviews, replyRequest,
|
||||||
type Review, sendPlan,
|
type Review, sendPlan,
|
||||||
|
|
@ -92,7 +92,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
|
|
||||||
if (sub === 'list') {
|
if (sub === 'list') {
|
||||||
const rs = await collect(ctx, { since, unanswered: a.has('unanswered'), ratings });
|
const rs = await collect(ctx, { since, unanswered: a.has('unanswered'), ratings });
|
||||||
if (a.has('json')) { console.log(JSON.stringify(rs.map(({ author: _a, ...r }) => r), null, 2)); return; }
|
if (a.has('json')) { printJson(rs.map(({ author: _a, ...r }) => r)); return; }
|
||||||
console.log(textTable(['store', 'date', 'stars', 'where', 'replied', 'review'], rs.map(r => [r.store, r.date.slice(0, 10), r.rating, r.where ?? '', r.reply ? 'yes' : '', snippet(r)])));
|
console.log(textTable(['store', 'date', 'stars', 'where', 'replied', 'review'], rs.map(r => [r.store, r.date.slice(0, 10), r.rating, r.where ?? '', r.reply ? 'yes' : '', snippet(r)])));
|
||||||
done(TAG, `${rs.length} review(s) in the last ${days} days, ${rs.filter(r => !r.reply).length} without a reply`);
|
done(TAG, `${rs.length} review(s) in the last ${days} days, ${rs.filter(r => !r.reply).length} without a reply`);
|
||||||
return;
|
return;
|
||||||
|
|
|
||||||
303
cli/serve.ts
Normal file
303
cli/serve.ts
Normal file
|
|
@ -0,0 +1,303 @@
|
||||||
|
// `storebound serve --stdio`: the machine interface the desktop app (apps/desktop) drives as a sidecar.
|
||||||
|
// Newline-delimited JSON-RPC 2.0 on stdin / stdout, logs on stderr. Protocol types: lib/desktop-protocol.ts.
|
||||||
|
//
|
||||||
|
// It reuses the MCP core: the same tool list (mcp-tools.ts: schemas, validation, argv building, the forbidden-flag
|
||||||
|
// rules) and the same child-process runner (lib/runner.ts). On top of that, the desktop profile adds:
|
||||||
|
// - a session handshake (`session.hello`) carrying the per-session secret of the host,
|
||||||
|
// - typed methods (one per tool, e.g. `play.listing`, plus project.inspect, portfolio.status, system.*),
|
||||||
|
// - structured results (`data`, the command's --json output), progress notifications and cancellation,
|
||||||
|
// - writes that are dry runs unless the host sends a confirm token (lib/confirm-token.ts) it minted after the owner
|
||||||
|
// confirmed a native dialog showing that dry run.
|
||||||
|
// Nothing here submits for review, releases or publishes: those methods do not exist (tests/serve.test.ts).
|
||||||
|
import { existsSync, statSync } from 'node:fs';
|
||||||
|
import { isAbsolute, join, resolve } from 'node:path';
|
||||||
|
import pkg from '../package.json' with { type: 'json' };
|
||||||
|
import { parseSecret, TokenGuard } from './lib/confirm-token';
|
||||||
|
import { CONFIG_NAMES } from './lib/config';
|
||||||
|
import {
|
||||||
|
DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult,
|
||||||
|
} from './lib/desktop-protocol';
|
||||||
|
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio';
|
||||||
|
import { detectTools } from './lib/tools';
|
||||||
|
import { compiled, pickCallEnv, runCommand, type RunOptions, type Running } from './lib/runner';
|
||||||
|
import { inputSchema, type ToolDef, TOOLS, toArgv, validateInput } from './mcp-tools';
|
||||||
|
|
||||||
|
type Id = string | number;
|
||||||
|
interface Msg { jsonrpc?: string; id?: Id | null; method?: string; params?: unknown }
|
||||||
|
type Json = Record<string, unknown>;
|
||||||
|
export type Send = (msg: Json) => void;
|
||||||
|
export type Runner = (argv: string[], o: RunOptions) => Running;
|
||||||
|
|
||||||
|
const MAX_OUTPUT = 60_000;
|
||||||
|
|
||||||
|
/** MCP tools the desktop profile leaves out (sending builds to testers on Play, release state changes). */
|
||||||
|
export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_release']);
|
||||||
|
/** Words no desktop method name may contain. */
|
||||||
|
export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i;
|
||||||
|
|
||||||
|
/** Read tools whose command prints a structured result with --json. */
|
||||||
|
export const JSON_TOOLS = new Set(['check', 'check_aso', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
||||||
|
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff']);
|
||||||
|
|
||||||
|
/** `apple_testflight_status` -> `apple.testflight_status`: first underscore becomes the namespace dot. */
|
||||||
|
export const methodName = (tool: string): string => tool.replace('_', '.');
|
||||||
|
|
||||||
|
export const DESKTOP_TOOLS: ToolDef[] = TOOLS.filter(t => !DESKTOP_EXCLUDED.has(t.name));
|
||||||
|
const byMethod = new Map(DESKTOP_TOOLS.map(t => [methodName(t.name), t] as const));
|
||||||
|
|
||||||
|
function argsSchema(t: ToolDef): MethodDescriptor['args'] {
|
||||||
|
const s = inputSchema(t) as MethodDescriptor['args'];
|
||||||
|
const { dry_run: _d, ...properties } = s.properties;
|
||||||
|
return { ...s, properties };
|
||||||
|
}
|
||||||
|
|
||||||
|
const obj = (properties: MethodDescriptor['args']['properties'], required?: string[]): MethodDescriptor['args'] =>
|
||||||
|
({ type: 'object', properties, ...(required ? { required } : {}), additionalProperties: false });
|
||||||
|
|
||||||
|
const SYSTEM: MethodDescriptor[] = [
|
||||||
|
{ method: 'session.hello', title: 'Start the session', description: 'Hand over the per-session secret (hex, >= 32 bytes). Must be the first request.', kind: 'session', network: false, destructive: false, json: true,
|
||||||
|
args: obj({ secret: { type: 'string' }, client: { type: 'object' } }, ['secret']) },
|
||||||
|
{ method: 'system.version', title: 'Version', description: 'storebound version, platform and whether this is the compiled sidecar.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) },
|
||||||
|
{ method: 'system.methods', title: 'Methods', description: 'Every method of this profile with its argument schema.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) },
|
||||||
|
{ method: 'system.tools', title: 'Local tools', description: 'Optional local tools with versions and where they come from (ffmpeg, ffprobe, Chrome, Xcode / simctl, adb, git); screenshot, video and capture features need them.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) },
|
||||||
|
{ method: 'project.inspect', title: 'Inspect a project', description: 'Offline summary of a folder\'s storebound.config.ts (name, store ids, languages, products).', kind: 'read', network: false, destructive: false, json: true,
|
||||||
|
args: obj({ project: { type: 'string', description: 'Absolute folder path' } }, ['project']) },
|
||||||
|
{ method: 'portfolio.status', title: 'Portfolio status', description: 'Apps (one per project folder) across iOS and Android: identity, offline config check, catalog parity; with live, release trains (current / next version on both stores) and live catalog parity from App Store and Google Play status (read-only).', kind: 'portfolio', network: true, destructive: false, json: true,
|
||||||
|
args: obj({ projects: { type: 'array' }, live: { type: 'boolean', default: false } }, ['projects']) },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function describeMethods(): MethodDescriptor[] {
|
||||||
|
return [...SYSTEM, ...DESKTOP_TOOLS.map(t => ({
|
||||||
|
method: methodName(t.name), title: t.title, description: t.description, kind: t.write ? 'write' as const : 'read' as const,
|
||||||
|
network: t.network, destructive: !!t.destructive, json: !t.write && JSON_TOOLS.has(t.name), args: argsSchema(t),
|
||||||
|
}))];
|
||||||
|
}
|
||||||
|
|
||||||
|
class RpcError extends Error {
|
||||||
|
constructor(readonly code: number, message: string, readonly data?: unknown) { super(message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Absolute folder with a storebound config in it, else an error. */
|
||||||
|
export function checkProject(p: unknown): string {
|
||||||
|
if (typeof p !== 'string' || !p) throw new RpcError(ERR.invalidParams, 'project: absolute folder path required');
|
||||||
|
if (!isAbsolute(p)) throw new RpcError(ERR.invalidParams, 'project: must be an absolute path');
|
||||||
|
const dir = resolve(p);
|
||||||
|
let isDir = false;
|
||||||
|
try { isDir = statSync(dir).isDirectory(); } catch { /* missing */ }
|
||||||
|
if (!isDir) throw new RpcError(ERR.invalidParams, `project: not a folder: ${dir}`);
|
||||||
|
if (!CONFIG_NAMES.some(n => existsSync(join(dir, n)))) throw new RpcError(ERR.invalidParams, `project: no storebound.config.ts in ${dir}`);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cut = (s: string): string => (s.length > MAX_OUTPUT ? `[... first ${s.length - MAX_OUTPUT} characters cut ...]\n` + s.slice(-MAX_OUTPUT) : s);
|
||||||
|
|
||||||
|
function credentialsOf(v: unknown): Record<string, string> {
|
||||||
|
if (v === undefined) return {};
|
||||||
|
if (typeof v !== 'object' || v === null || Array.isArray(v)) throw new RpcError(ERR.invalidParams, 'credentials: object expected');
|
||||||
|
return pickCallEnv(v as Record<string, unknown>);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One sidecar session: state is the secret (after hello), the token guard and the running requests. */
|
||||||
|
export class Session {
|
||||||
|
private guard: TokenGuard | null = null;
|
||||||
|
private running = new Map<Id, Set<Running>>();
|
||||||
|
private cancelled = new Set<Id>();
|
||||||
|
|
||||||
|
constructor(private readonly send: Send, private readonly run: Runner = runCommand, private readonly clock: () => number = Date.now) {}
|
||||||
|
|
||||||
|
get ready(): boolean { return this.guard !== null; }
|
||||||
|
|
||||||
|
/** Stops every running child (the host went away). */
|
||||||
|
shutdown(): void { for (const set of this.running.values()) for (const r of set) r.cancel(); }
|
||||||
|
|
||||||
|
/** Handles one incoming message; resolves with the response (or null for notifications). */
|
||||||
|
async handle(m: Msg): Promise<Json | null> {
|
||||||
|
if (typeof m !== 'object' || m === null || Array.isArray(m)) return { jsonrpc: '2.0', id: null, error: { code: ERR.invalidRequest, message: 'Invalid request' } };
|
||||||
|
if (m.id === undefined || m.id === null) { this.notification(m); return null; }
|
||||||
|
const id = m.id;
|
||||||
|
try {
|
||||||
|
const result = await this.dispatch(String(m.method ?? ''), (m.params ?? {}) as Json, id);
|
||||||
|
return { jsonrpc: '2.0', id, result };
|
||||||
|
} catch (e) {
|
||||||
|
if (this.cancelled.has(id)) return { jsonrpc: '2.0', id, error: { code: ERR.cancelled, message: 'Request cancelled' } };
|
||||||
|
const err = e instanceof RpcError ? e : new RpcError(ERR.internal, (e as Error).message);
|
||||||
|
return { jsonrpc: '2.0', id, error: { code: err.code, message: err.message, ...(err.data === undefined ? {} : { data: err.data }) } };
|
||||||
|
} finally {
|
||||||
|
this.running.delete(id);
|
||||||
|
this.cancelled.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private notification(m: Msg): void {
|
||||||
|
const p = (m.params ?? {}) as Json;
|
||||||
|
if (m.method === '$/cancelRequest' || m.method === 'notifications/cancelled') {
|
||||||
|
const id = (p.id ?? p.requestId) as Id | undefined;
|
||||||
|
if (id === undefined) return;
|
||||||
|
this.cancelled.add(id);
|
||||||
|
for (const r of this.running.get(id) ?? []) r.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private track(id: Id, r: Running): Running {
|
||||||
|
if (this.cancelled.has(id)) r.cancel();
|
||||||
|
let set = this.running.get(id);
|
||||||
|
if (!set) this.running.set(id, (set = new Set()));
|
||||||
|
set.add(r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async dispatch(method: string, params: Json, id: Id): Promise<unknown> {
|
||||||
|
if (typeof params !== 'object' || params === null || Array.isArray(params)) throw new RpcError(ERR.invalidParams, 'params must be an object');
|
||||||
|
if (method === 'session.hello') {
|
||||||
|
if (this.guard) throw new RpcError(ERR.invalidRequest, 'session already started');
|
||||||
|
let secret: Buffer;
|
||||||
|
try { secret = parseSecret(params.secret); } catch (e) { throw new RpcError(ERR.invalidParams, (e as Error).message); }
|
||||||
|
this.guard = new TokenGuard(secret, this.clock);
|
||||||
|
return { protocol: DESKTOP_PROTOCOL, server: { name: 'storebound', version: pkg.version, compiled: compiled() }, methods: describeMethods() };
|
||||||
|
}
|
||||||
|
if (!this.guard) throw new RpcError(ERR.notInitialized, 'session.hello first');
|
||||||
|
switch (method) {
|
||||||
|
case 'system.version': return { version: pkg.version, compiled: compiled(), platform: process.platform, arch: process.arch, bun: Bun.version };
|
||||||
|
case 'system.methods': return { methods: describeMethods() };
|
||||||
|
case 'system.tools': return localTools();
|
||||||
|
case 'project.inspect': return this.inspect(checkProject(params.project), {}, id);
|
||||||
|
case 'portfolio.status': return this.portfolio(params, id);
|
||||||
|
}
|
||||||
|
const tool = byMethod.get(method);
|
||||||
|
if (!tool) throw new RpcError(ERR.methodNotFound, `Method not found: ${method}`);
|
||||||
|
return this.tool(method, tool, params, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise<ToolResult> {
|
||||||
|
for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
|
||||||
|
const project = checkProject(params.project);
|
||||||
|
const args = (params.args ?? {}) as Json;
|
||||||
|
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
|
||||||
|
if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun');
|
||||||
|
const problems = validateInput(t, args);
|
||||||
|
if (problems.length) throw new RpcError(ERR.invalidParams, `Invalid arguments: ${problems.join('; ')}`, { problems });
|
||||||
|
const env = credentialsOf(params.credentials);
|
||||||
|
let dryRun = true;
|
||||||
|
if (params.dryRun === false) {
|
||||||
|
if (!t.write) dryRun = false;
|
||||||
|
else {
|
||||||
|
if (params.confirmToken === undefined) throw new RpcError(ERR.confirmRequired, `${method} writes: dryRun false needs a confirmToken from the desktop host`);
|
||||||
|
// Bound to the project string exactly as sent (the host mints over what it sends) and the args object.
|
||||||
|
const v = this.guard!.verify(params.confirmToken, method, { project: params.project, args });
|
||||||
|
if (!v.ok) throw new RpcError(ERR.confirmInvalid, `confirm token rejected: ${v.error}`, { reason: v.error });
|
||||||
|
dryRun = false;
|
||||||
|
}
|
||||||
|
} else if (params.dryRun !== undefined && params.dryRun !== true) throw new RpcError(ERR.invalidParams, 'dryRun must be a boolean');
|
||||||
|
if (!t.write) dryRun = false;
|
||||||
|
const built = toArgv(t, { ...args, ...(t.write ? { dry_run: dryRun } : {}) });
|
||||||
|
const json = !t.write && JSON_TOOLS.has(t.name);
|
||||||
|
const argv = json ? [...built.argv, '--json'] : built.argv;
|
||||||
|
const r = this.track(id, this.run(argv, { cwd: project, env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) }));
|
||||||
|
const res = await r.result;
|
||||||
|
if (res.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled');
|
||||||
|
return {
|
||||||
|
method, ok: res.code === 0, exitCode: res.code, dryRun: t.write ? dryRun : false, command: `storebound ${argv.join(' ')}`, output: cut(res.out),
|
||||||
|
...(res.data === undefined ? {} : { data: res.data }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private progress(id: Id, p: Json): void {
|
||||||
|
this.send({ jsonrpc: '2.0', method: 'progress', params: { requestId: id, ...p } });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async inspect(project: string, env: Record<string, string>, id: Id): Promise<ProjectSummary> {
|
||||||
|
const r = await this.track(id, this.run(['inspect', '--json'], { cwd: project, env, machine: true })).result;
|
||||||
|
if (r.cancelled) throw new RpcError(ERR.cancelled, 'Request cancelled');
|
||||||
|
if (r.code !== 0 || !r.data) throw new RpcError(ERR.invalidParams, `project: ${lastLine(r.out) || 'config could not be loaded'}`);
|
||||||
|
return r.data as ProjectSummary;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async portfolio(params: Json, id: Id): Promise<PortfolioResult> {
|
||||||
|
const list = params.projects;
|
||||||
|
if (!Array.isArray(list) || !list.length || list.length > 200) throw new RpcError(ERR.invalidParams, 'projects: 1-200 absolute folder paths');
|
||||||
|
const live = params.live === true;
|
||||||
|
const env = credentialsOf(params.credentials);
|
||||||
|
const out: AppStatus[] = new Array(list.length);
|
||||||
|
let done = 0;
|
||||||
|
const one = async (i: number): Promise<void> => {
|
||||||
|
const raw = list[i];
|
||||||
|
const e: AppStatus = { project: String(raw), ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] };
|
||||||
|
out[i] = e;
|
||||||
|
try {
|
||||||
|
const dir = checkProject(raw);
|
||||||
|
e.project = dir;
|
||||||
|
const summary = e.summary = await this.inspect(dir, env, id);
|
||||||
|
e.app = appIdentity(summary);
|
||||||
|
e.catalog = catalogParity(summary);
|
||||||
|
const c = await this.track(id, this.run(['check', '--json'], { cwd: dir, env, machine: true })).result;
|
||||||
|
const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined;
|
||||||
|
e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] };
|
||||||
|
if (live) {
|
||||||
|
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => {
|
||||||
|
const r = await this.track(id, this.run(argv, { cwd: dir, env, machine: true })).result;
|
||||||
|
return r.code === 0 && r.data !== undefined ? { data: r.data } : { error: lastLine(r.out) || `exit ${r.code}` };
|
||||||
|
};
|
||||||
|
const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]);
|
||||||
|
if (apple?.error) e.storeErrors.ios = apple.error;
|
||||||
|
if (play?.error) e.storeErrors.android = play.error;
|
||||||
|
e.release = { source: 'live', ...releaseTrains(apple?.data ? appleReleases(apple.data) : [], play?.data ? playReleases(play.data) : []) };
|
||||||
|
e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined);
|
||||||
|
}
|
||||||
|
e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);
|
||||||
|
} catch (err) {
|
||||||
|
if (this.cancelled.has(id)) throw err;
|
||||||
|
e.errors.push((err as Error).message);
|
||||||
|
}
|
||||||
|
this.progress(id, { n: ++done, total: list.length, project: e.project });
|
||||||
|
};
|
||||||
|
// A few projects at a time: each one is a few child processes (and API calls when live).
|
||||||
|
let next = 0;
|
||||||
|
await Promise.all(Array.from({ length: Math.min(3, list.length) }, async () => { while (next < list.length) await one(next++); }));
|
||||||
|
if (this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled');
|
||||||
|
return { apps: out, at: new Date(this.clock()).toISOString() };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
|
||||||
|
|
||||||
|
/** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */
|
||||||
|
export function localTools(): Json {
|
||||||
|
return { tools: detectTools() };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function serveStdio(): Promise<void> {
|
||||||
|
const send: Send = o => { process.stdout.write(JSON.stringify(o) + '\n'); };
|
||||||
|
const session = new Session(send);
|
||||||
|
console.error(`[storebound serve] ${pkg.version} on stdio (${DESKTOP_PROTOCOL}), waiting for session.hello`);
|
||||||
|
let buf = '';
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
const reader = Bun.stdin.stream().getReader();
|
||||||
|
for (;;) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buf += decoder.decode(value, { stream: true });
|
||||||
|
let nl: number;
|
||||||
|
while ((nl = buf.indexOf('\n')) >= 0) {
|
||||||
|
const line = buf.slice(0, nl).trim();
|
||||||
|
buf = buf.slice(nl + 1);
|
||||||
|
if (!line) continue;
|
||||||
|
let msg: Msg;
|
||||||
|
try { msg = JSON.parse(line) as Msg; } catch { send({ jsonrpc: '2.0', id: null, error: { code: ERR.parse, message: 'Parse error' } }); continue; }
|
||||||
|
if (Array.isArray(msg)) { send({ jsonrpc: '2.0', id: null, error: { code: ERR.invalidRequest, message: 'Batches are not supported' } }); continue; }
|
||||||
|
// The handshake must finish before anything else is read, so a request right behind it sees the session.
|
||||||
|
if (!session.ready && msg.method === 'session.hello') { const r = await session.handle(msg); if (r) send(r); continue; }
|
||||||
|
session.handle(msg).then(r => { if (r) send(r); }, e => send({ jsonrpc: '2.0', id: msg.id ?? null, error: { code: ERR.internal, message: String((e as Error).message) } }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// stdin closed: the host is gone; stop what still runs.
|
||||||
|
session.shutdown();
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function run(args: { has(n: string): boolean }): Promise<void> {
|
||||||
|
if (!args.has('stdio')) {
|
||||||
|
console.error('usage: storebound serve --stdio (JSON-RPC for the storebound desktop app; for AI tools use `storebound mcp`)');
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
await serveStdio();
|
||||||
|
}
|
||||||
|
|
@ -17,6 +17,9 @@ async function chromium(root: string): Promise<any> {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
export async function launch(root: string, opts: Record<string, unknown>): Promise<any> {
|
export async function launch(root: string, opts: Record<string, unknown>): Promise<any> {
|
||||||
const c = await chromium(root);
|
const c = await chromium(root);
|
||||||
|
// the desktop app's own Chrome for Testing (or any Chrome the user points at)
|
||||||
|
const exe = process.env.STOREBOUND_CHROME;
|
||||||
|
if (exe) { try { return await c.launch({ ...opts, executablePath: exe }); } catch { /* fall back below */ } }
|
||||||
try { return await c.launch(opts); } catch (e) {
|
try { return await c.launch(opts); } catch (e) {
|
||||||
try { return await c.launch({ ...opts, channel: 'chrome' }); } catch { throw e; }
|
try { return await c.launch({ ...opts, channel: 'chrome' }); } catch { throw e; }
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import type { ShipConfig } from '../lib/config';
|
import type { ShipConfig } from '../lib/config';
|
||||||
import type { Ctx } from '../lib/ctx';
|
import type { Ctx } from '../lib/ctx';
|
||||||
import { log } from '../lib/log';
|
import { log, printJson } from '../lib/log';
|
||||||
import { checkFrames, type FrameIssue } from './devices';
|
import { checkFrames, type FrameIssue } from './devices';
|
||||||
import { defaultSizes, frameDims, SIZES } from './lib';
|
import { defaultSizes, frameDims, SIZES } from './lib';
|
||||||
import type { LocalIssue, RendersCheck } from '../lib/validate-rules';
|
import type { LocalIssue, RendersCheck } from '../lib/validate-rules';
|
||||||
|
|
@ -64,7 +64,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
const cap = config.shots?.capture;
|
const cap = config.shots?.capture;
|
||||||
const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : [];
|
const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : [];
|
||||||
if (ctx.args.has('json')) {
|
if (ctx.args.has('json')) {
|
||||||
console.log(JSON.stringify({ images: scan.images.length, videos: scan.videos.length, issues, frames: frameIssues }, null, 2));
|
printJson({ images: scan.images.length, videos: scan.videos.length, issues, frames: frameIssues });
|
||||||
} else {
|
} else {
|
||||||
for (const { where, issue } of issues) console.log(`${issue.level === 'error' ? 'ERROR' : 'warn '} ${where}: ${issue.msg}`);
|
for (const { where, issue } of issues) console.log(`${issue.level === 'error' ? 'ERROR' : 'warn '} ${where}: ${issue.msg}`);
|
||||||
for (const f of frameIssues) console.log(`ERROR frames/${f.file}: ${f.msg}`);
|
for (const f of frameIssues) console.log(`ERROR frames/${f.file}: ${f.msg}`);
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ import type { Ctx } from './lib/ctx';
|
||||||
import { checkUrl } from './lib/http';
|
import { checkUrl } from './lib/http';
|
||||||
import { collectHealth } from './health';
|
import { collectHealth } from './health';
|
||||||
import { healthFindings } from './lib/health';
|
import { healthFindings } from './lib/health';
|
||||||
import { log, warn } from './lib/log';
|
import { log, printJson, warn } from './lib/log';
|
||||||
import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules, type ProfileFacts, rendersFindings, sortFindings } from './lib/validate-rules';
|
import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules, type ProfileFacts, rendersFindings, sortFindings } from './lib/validate-rules';
|
||||||
import { rendersCheck } from './shots/check';
|
import { rendersCheck } from './shots/check';
|
||||||
import { playClient } from './play/client';
|
import { playClient } from './play/client';
|
||||||
|
|
@ -177,7 +177,7 @@ export async function run(ctx: Ctx): Promise<void> {
|
||||||
findings.push(...sortFindings(healthFindings(h, { unreadable: 'ok' })));
|
findings.push(...sortFindings(healthFindings(h, { unreadable: 'ok' })));
|
||||||
}
|
}
|
||||||
const blockers = findings.filter(f => f.level === 'blocker').length;
|
const blockers = findings.filter(f => f.level === 'blocker').length;
|
||||||
if (a.has('json')) console.log(JSON.stringify({ blockers, findings }, null, 2));
|
if (a.has('json')) printJson({ blockers, findings });
|
||||||
else {
|
else {
|
||||||
console.log(formatFindings(findings));
|
console.log(formatFindings(findings));
|
||||||
log('validate', blockers ? `${blockers} blocker(s)` : 'no blockers (UI-only steps are not visible to the API: App Privacy, Play App content)');
|
log('validate', blockers ? `${blockers} blocker(s)` : 'no blockers (UI-only steps are not visible to the API: App Privacy, Play App content)');
|
||||||
|
|
|
||||||
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"
|
||||||
},
|
},
|
||||||
|
|
|
||||||
72
tests/portfolio.test.ts
Normal file
72
tests/portfolio.test.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import type { ProjectSummary } from '../cli/lib/desktop-protocol';
|
||||||
|
import { appIdentity, applePhase, appleProductIds, appleReleases, catalogParity, cmpVersion, playProductIds, playReleases, releaseTrains, versionOfName } from '../cli/lib/portfolio';
|
||||||
|
|
||||||
|
const summary: ProjectSummary = {
|
||||||
|
dir: '/games/demo', config: '/games/demo/storebound.config.ts', name: 'Demo', languages: ['en'],
|
||||||
|
play: { packageName: 'com.example.demo' }, apple: { bundleId: 'com.example.demo', appId: null },
|
||||||
|
platforms: ['ios', 'android'], products: 2, productIds: ['coins', 'no_ads'], subscriptions: 1, subscriptionIds: ['pro_monthly'],
|
||||||
|
catalog: { ios: ['coins', 'no_ads', 'pro_monthly'], android: ['coins', 'no_ads', 'pro_monthly'] }, shots: false, testflightGroups: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const apple = {
|
||||||
|
versions: [
|
||||||
|
{ attributes: { versionString: '2.3.0', appVersionState: 'WAITING_FOR_REVIEW', platform: 'IOS' }, relationships: { build: { data: { id: 'b2' } } } },
|
||||||
|
{ attributes: { versionString: '2.2.1', appStoreState: 'READY_FOR_SALE', platform: 'IOS' }, relationships: { build: { data: { id: 'b1' } } } },
|
||||||
|
{ attributes: { versionString: '9.9.9', appStoreState: 'READY_FOR_SALE', platform: 'TV_OS' } },
|
||||||
|
],
|
||||||
|
builds: [{ id: 'b1', attributes: { version: '41' } }, { id: 'b2', attributes: { version: '45' } }],
|
||||||
|
iaps: [{ attributes: { productId: 'coins' } }, { attributes: { productId: 'ios_only' } }],
|
||||||
|
};
|
||||||
|
const play = {
|
||||||
|
tracks: [
|
||||||
|
{ track: 'production', releases: [{ name: '2.2.1 (220)', versionCodes: ['220'], status: 'completed' }, { name: '2.3.0', versionCodes: ['230', '231'], status: 'inProgress', userFraction: 0.2 }] },
|
||||||
|
{ track: 'internal', releases: [{ name: '2.4.0', versionCodes: ['240'], status: 'completed' }] },
|
||||||
|
],
|
||||||
|
products: [{ productId: 'coins' }, { productId: 'no_ads' }, { sku: 'android_only' }],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('portfolio (apps, release trains, catalog parity)', () => {
|
||||||
|
test('identity: one app, both platforms', () => {
|
||||||
|
expect(appIdentity(summary)).toEqual({ id: '/games/demo', name: 'Demo', platforms: { ios: { bundleId: 'com.example.demo', ascAppId: null }, android: { packageName: 'com.example.demo' } } });
|
||||||
|
expect(appIdentity({ ...summary, apple: null }).platforms.ios).toBeNull();
|
||||||
|
expect(appIdentity({ ...summary, platforms: ['android'] }).platforms.ios).toBeNull();
|
||||||
|
});
|
||||||
|
test('versions and phases', () => {
|
||||||
|
expect(cmpVersion('2.10.0', '2.9.1')).toBeGreaterThan(0);
|
||||||
|
expect(cmpVersion('2.3', '2.3.0')).toBe(0);
|
||||||
|
expect(versionOfName('2.3.0 (45)')).toBe('2.3.0');
|
||||||
|
expect(versionOfName(undefined)).toBeNull();
|
||||||
|
expect(applePhase('READY_FOR_SALE')).toBe('live');
|
||||||
|
expect(applePhase('PENDING_DEVELOPER_RELEASE')).toBe('approved');
|
||||||
|
expect(applePhase('METADATA_REJECTED')).toBe('rejected');
|
||||||
|
expect(applePhase('PREPARE_FOR_SUBMISSION')).toBe('draft');
|
||||||
|
expect(applePhase('SOMETHING_NEW')).toBe('other');
|
||||||
|
});
|
||||||
|
test('store releases from status data; garbage gives nothing', () => {
|
||||||
|
const ios = appleReleases(apple);
|
||||||
|
expect(ios.map(r => [r.version, r.build, r.phase])).toEqual([['2.3.0', '45', 'review'], ['2.2.1', '41', 'live']]);
|
||||||
|
const android = playReleases(play);
|
||||||
|
expect(android.map(r => [r.version, r.build, r.phase, r.fraction, r.track])).toEqual([['2.2.1', '220', 'live', null, 'production'], ['2.3.0', '231', 'rollout', 0.2, 'production'], ['2.4.0', '240', 'testing', null, 'internal']]);
|
||||||
|
expect(appleReleases(null)).toEqual([]);
|
||||||
|
expect(playReleases({ tracks: 'x' })).toEqual([]);
|
||||||
|
});
|
||||||
|
test('trains: current = highest live version, next = highest above it, per store', () => {
|
||||||
|
const t = releaseTrains(appleReleases(apple), playReleases(play));
|
||||||
|
expect(t.current).toMatchObject({ version: '2.2.1', ios: { phase: 'live', build: '41' }, android: { phase: 'live', build: '220' } });
|
||||||
|
expect(t.next).toMatchObject({ version: '2.4.0', ios: null, android: { phase: 'testing' } });
|
||||||
|
expect(releaseTrains([], [])).toEqual({ current: null, next: null });
|
||||||
|
const onlyNext = releaseTrains(appleReleases({ versions: [apple.versions[0]] }), []);
|
||||||
|
expect(onlyNext.current).toBeNull();
|
||||||
|
expect(onlyNext.next?.version).toBe('2.3.0');
|
||||||
|
});
|
||||||
|
test('catalog parity: config only offline, both stores live', () => {
|
||||||
|
expect(catalogParity(summary)).toEqual({ checked: 'config', products: 2, subscriptions: 1, onlyIos: [], onlyAndroid: [], missingIos: [], missingAndroid: [], ok: true });
|
||||||
|
const live = catalogParity(summary, appleProductIds(apple), playProductIds(play));
|
||||||
|
expect(live).toMatchObject({ checked: 'live', onlyIos: ['ios_only'], onlyAndroid: ['no_ads', 'android_only'], missingIos: ['no_ads'], missingAndroid: [], ok: false });
|
||||||
|
// an item sold on Android only is not missing on iOS
|
||||||
|
expect(catalogParity({ ...summary, catalog: { ios: ['coins'], android: ['coins', 'no_ads'] } }, appleProductIds(apple), playProductIds(play)).missingIos).toEqual([]);
|
||||||
|
// one store unreadable: no cross-store claims
|
||||||
|
expect(catalogParity(summary, undefined, playProductIds(play))).toMatchObject({ onlyIos: [], onlyAndroid: [], missingIos: [], missingAndroid: [] });
|
||||||
|
});
|
||||||
|
});
|
||||||
247
tests/serve.test.ts
Normal file
247
tests/serve.test.ts
Normal file
|
|
@ -0,0 +1,247 @@
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { canonical, mac, MAX_TTL_MS, mint, parseSecret, TokenGuard } from '../cli/lib/confirm-token';
|
||||||
|
import { ERR } from '../cli/lib/desktop-protocol';
|
||||||
|
import { childEnv, pickCallEnv, type RunOptions, type Running } from '../cli/lib/runner';
|
||||||
|
import { FORBIDDEN_ARGS, TOOLS } from '../cli/mcp-tools';
|
||||||
|
import { describeMethods, DESKTOP_TOOLS, FORBIDDEN_METHOD_WORDS, JSON_TOOLS, methodName, Session } from '../cli/serve';
|
||||||
|
import { buildOne, hostTarget, leaks } from '../tools/build-sidecars';
|
||||||
|
|
||||||
|
type J = Record<string, unknown>;
|
||||||
|
const ROOT = join(import.meta.dir, '..');
|
||||||
|
const DEMO = join(ROOT, 'examples/demo-game');
|
||||||
|
const SECRET_HEX = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join('');
|
||||||
|
const SECRET = Buffer.from(SECRET_HEX, 'hex');
|
||||||
|
|
||||||
|
interface Call { argv: string[]; o: RunOptions }
|
||||||
|
function fakeRunner(reply: (argv: string[]) => { code?: number; out?: string; data?: unknown; lines?: string[]; wait?: Promise<void> } = () => ({})) {
|
||||||
|
const calls: Call[] = [];
|
||||||
|
const run = (argv: string[], o: RunOptions): Running => {
|
||||||
|
calls.push({ argv, o });
|
||||||
|
const r = reply(argv);
|
||||||
|
let cancelled = false;
|
||||||
|
let release: () => void = () => {};
|
||||||
|
const gate = new Promise<void>(res => { release = res; });
|
||||||
|
const result = (async () => {
|
||||||
|
for (const l of r.lines ?? []) o.onLine?.(l, 'stdout');
|
||||||
|
if (r.wait) await Promise.race([r.wait, gate]);
|
||||||
|
return { code: cancelled ? 143 : r.code ?? 0, out: r.out ?? '', ...(r.data === undefined ? {} : { data: r.data }), cancelled };
|
||||||
|
})();
|
||||||
|
return { result, cancel: () => { cancelled = true; release(); } };
|
||||||
|
};
|
||||||
|
return { calls, run };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function session(reply?: Parameters<typeof fakeRunner>[0], clock: () => number = Date.now) {
|
||||||
|
const sent: J[] = [];
|
||||||
|
const f = fakeRunner(reply);
|
||||||
|
const s = new Session(m => sent.push(m), f.run, clock);
|
||||||
|
let id = 0;
|
||||||
|
const call = async (method: string, params: unknown = {}) => (await s.handle({ jsonrpc: '2.0', id: ++id, method, params }))!;
|
||||||
|
const hello = await call('session.hello', { secret: SECRET_HEX, client: { name: 'test', version: '1' } });
|
||||||
|
return { s, sent, calls: f.calls, call, hello, nextId: () => id + 1 };
|
||||||
|
}
|
||||||
|
const errOf = (r: J) => r.error as { code: number; message: string; data?: J };
|
||||||
|
const resOf = (r: J) => r.result as J;
|
||||||
|
|
||||||
|
describe('confirm tokens', () => {
|
||||||
|
test('canonical JSON: sorted keys, no whitespace, safe integers only', () => {
|
||||||
|
expect(canonical({ b: 1, a: [true, null, 'x'], c: { z: '', y: undefined } })).toBe('{"a":[true,null,"x"],"b":1,"c":{"z":""}}');
|
||||||
|
expect(() => canonical({ f: 0.5 })).toThrow();
|
||||||
|
expect(() => canonical({ f: 2 ** 60 })).toThrow();
|
||||||
|
});
|
||||||
|
test('shared vector (the Rust host tests the same one in src-tauri/tests/confirm.rs)', () => {
|
||||||
|
const p = { project: '/tmp/game', args: { only: 'en-US,tr', b: [1, true, null, 'ü"\n'] } };
|
||||||
|
expect(canonical(p)).toBe('{"args":{"b":[1,true,null,"ü\\"\\n"],"only":"en-US,tr"},"project":"/tmp/game"}');
|
||||||
|
expect(mac(SECRET, 'play.listing', p, 1700000060000, 'AAAAAAAAAAAAAAAAAAAAAA')).toBe('JhSxUL2ej4cm4yrmlcA23rTCPq3YMKJthbB7n6aixxw');
|
||||||
|
});
|
||||||
|
test('binding, expiry, max lifetime, replay', () => {
|
||||||
|
let now = 1_000_000;
|
||||||
|
const g = new TokenGuard(SECRET, () => now);
|
||||||
|
const p = { project: '/p', args: { only: 'en-US' } };
|
||||||
|
const t = mint(SECRET, 'play.listing', p, { now });
|
||||||
|
expect(g.verify(t, 'play.listing', { project: '/p', args: { only: 'tr' } })).toEqual({ ok: false, error: 'mismatch' });
|
||||||
|
expect(g.verify(t, 'play.listing', { project: '/q', args: { only: 'en-US' } })).toEqual({ ok: false, error: 'mismatch' });
|
||||||
|
expect(g.verify(t, 'play.images', p)).toEqual({ ok: false, error: 'mismatch' });
|
||||||
|
expect(g.verify(mint(Buffer.alloc(32, 7), 'play.listing', p, { now }), 'play.listing', p)).toEqual({ ok: false, error: 'mismatch' });
|
||||||
|
expect(g.verify(t, 'play.listing', p)).toEqual({ ok: true });
|
||||||
|
expect(g.verify(t, 'play.listing', p)).toEqual({ ok: false, error: 'replayed' });
|
||||||
|
const old = mint(SECRET, 'play.listing', p, { now, ttlMs: 1000 });
|
||||||
|
now += 1000;
|
||||||
|
expect(g.verify(old, 'play.listing', p)).toEqual({ ok: false, error: 'expired' });
|
||||||
|
expect(g.verify(mint(SECRET, 'play.listing', p, { now, ttlMs: MAX_TTL_MS + 1 }), 'play.listing', p)).toEqual({ ok: false, error: 'too-long' });
|
||||||
|
for (const bad of [undefined, '', 'sbt1', 'sbt2.1.AAAAAAAAAAAAAAAAAAAAAA.x', `sbt1.${now + 5000}.short.${'A'.repeat(43)}`, t + 'x'])
|
||||||
|
expect(g.verify(bad, 'play.listing', p).ok).toBe(false);
|
||||||
|
});
|
||||||
|
test('secrets: hex, at least 32 bytes', () => {
|
||||||
|
expect(parseSecret(SECRET_HEX).length).toBe(32);
|
||||||
|
expect(() => parseSecret('abcd')).toThrow();
|
||||||
|
expect(() => parseSecret('zz'.repeat(32))).toThrow();
|
||||||
|
expect(() => parseSecret(42)).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('serve --stdio: methods', () => {
|
||||||
|
test('nothing submits, releases or publishes', () => {
|
||||||
|
const names = describeMethods().map(m => m.method);
|
||||||
|
for (const n of names) expect(n).not.toMatch(FORBIDDEN_METHOD_WORDS);
|
||||||
|
for (const n of ['apple.submit', 'apple.release', 'play.release', 'play.release_testing', 'apple.phased_release', 'play.rollout', 'reviews.send', 'apple.ppo_start', 'prices.import'])
|
||||||
|
expect(names).not.toContain(n);
|
||||||
|
// every desktop tool still goes through the MCP rules: no forbidden flag can come out of any of them
|
||||||
|
for (const t of DESKTOP_TOOLS) expect(t.command.some(c => FORBIDDEN_ARGS.includes(c))).toBe(false);
|
||||||
|
expect(new Set(names).size).toBe(names.length);
|
||||||
|
});
|
||||||
|
test('typed descriptors for every tool; json flags only on read tools', () => {
|
||||||
|
const ms = describeMethods();
|
||||||
|
expect(ms.filter(m => m.kind === 'read' || m.kind === 'write').length).toBe(DESKTOP_TOOLS.length + 1); // + project.inspect
|
||||||
|
for (const m of ms) { expect(m.args.type).toBe('object'); expect(m.args.additionalProperties).toBe(false); expect(m.args.properties.dry_run).toBeUndefined(); }
|
||||||
|
for (const t of JSON_TOOLS) expect(TOOLS.find(x => x.name === t)?.write).toBe(false);
|
||||||
|
expect(ms.map(m => m.method)).toEqual(expect.arrayContaining(['portfolio.status', 'project.inspect', 'check', 'validate', 'apple.status', 'play.status', 'reviews.list', 'apple.testflight_status']));
|
||||||
|
expect(methodName('apple_testflight_status')).toBe('apple.testflight_status');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('serve --stdio: session', () => {
|
||||||
|
test('hello first, once, with a real secret', async () => {
|
||||||
|
const s = new Session(() => {}, fakeRunner().run);
|
||||||
|
expect(errOf((await s.handle({ jsonrpc: '2.0', id: 1, method: 'system.version' }))!).code).toBe(ERR.notInitialized);
|
||||||
|
expect(errOf((await s.handle({ jsonrpc: '2.0', id: 2, method: 'session.hello', params: { secret: 'ab' } }))!).code).toBe(ERR.invalidParams);
|
||||||
|
const ok = resOf((await s.handle({ jsonrpc: '2.0', id: 3, method: 'session.hello', params: { secret: SECRET_HEX } }))!);
|
||||||
|
expect(ok.protocol).toBe('storebound-desktop/1');
|
||||||
|
expect((ok.methods as unknown[]).length).toBe(describeMethods().length);
|
||||||
|
expect(errOf((await s.handle({ jsonrpc: '2.0', id: 4, method: 'session.hello', params: { secret: SECRET_HEX } }))!).code).toBe(ERR.invalidRequest);
|
||||||
|
expect(resOf((await s.handle({ jsonrpc: '2.0', id: 5, method: 'system.version' }))!).version).toBeString();
|
||||||
|
expect(errOf((await s.handle({ jsonrpc: '2.0', id: 6, method: 'apple.submit', params: { project: DEMO } }))!).code).toBe(ERR.methodNotFound);
|
||||||
|
});
|
||||||
|
test('read method: --json appended, data and progress passed through, credentials only as per-call env', async () => {
|
||||||
|
const { call, calls, sent } = await session(() => ({ data: { blockers: 0, findings: [] }, out: 'log line', lines: ['12:00:00 [validate] apple'] }));
|
||||||
|
const r = resOf(await call('validate', { project: DEMO, args: { store: 'apple' }, credentials: { ASC_KEY_ID: 'K', HOME: '/evil', ASC_P8: '' } }));
|
||||||
|
expect(calls[0]!.argv).toEqual(['validate', '--apple', '--json']);
|
||||||
|
expect(calls[0]!.o).toMatchObject({ cwd: DEMO, machine: true, env: { ASC_KEY_ID: 'K' } });
|
||||||
|
expect(Object.keys(calls[0]!.o.env!)).toEqual(['ASC_KEY_ID']);
|
||||||
|
expect(r).toMatchObject({ ok: true, exitCode: 0, dryRun: false, data: { blockers: 0 }, command: 'storebound validate --apple --json' });
|
||||||
|
expect(sent).toContainEqual({ jsonrpc: '2.0', method: 'progress', params: { requestId: 2, line: '12:00:00 [validate] apple', stream: 'stdout' } });
|
||||||
|
});
|
||||||
|
test('bad params: relative or config-less project, unknown args, dry_run inside args', async () => {
|
||||||
|
const { call } = await session();
|
||||||
|
expect(errOf(await call('check', { project: 'examples/demo-game' })).code).toBe(ERR.invalidParams);
|
||||||
|
expect(errOf(await call('check', { project: tmpdir() })).message).toContain('no storebound.config.ts');
|
||||||
|
expect(errOf(await call('check', { project: DEMO, args: { nope: 1 } })).code).toBe(ERR.invalidParams);
|
||||||
|
expect(errOf(await call('play.listing', { project: DEMO, args: { dry_run: false } })).code).toBe(ERR.invalidParams);
|
||||||
|
expect(errOf(await call('check', { project: DEMO, extra: true })).code).toBe(ERR.invalidParams);
|
||||||
|
expect(errOf(await call('play.listing', { project: DEMO, args: { only: '--yes' } })).code).toBe(ERR.invalidParams);
|
||||||
|
});
|
||||||
|
test('writes: dry run by default; real run only with a matching, fresh, unused host token', async () => {
|
||||||
|
let now = 5_000_000;
|
||||||
|
const { call, calls } = await session(undefined, () => now);
|
||||||
|
const p = { project: DEMO, args: { only: 'en-US' } };
|
||||||
|
expect(resOf(await call('play.listing', p))).toMatchObject({ dryRun: true });
|
||||||
|
expect(calls[0]!.argv).toEqual(['play', 'listing', '--only', 'en-US', '--dry']);
|
||||||
|
expect(errOf(await call('play.listing', { ...p, dryRun: false })).code).toBe(ERR.confirmRequired);
|
||||||
|
const token = mint(SECRET, 'play.listing', p, { now });
|
||||||
|
expect(errOf(await call('play.listing', { ...p, args: { only: 'tr-TR' }, dryRun: false, confirmToken: token })).code).toBe(ERR.confirmInvalid);
|
||||||
|
expect(errOf(await call('play.images', { ...p, dryRun: false, confirmToken: token })).code).toBe(ERR.confirmInvalid);
|
||||||
|
const real = resOf(await call('play.listing', { ...p, dryRun: false, confirmToken: token, credentials: { PLAY_SERVICE_ACCOUNT: '{}' } }));
|
||||||
|
expect(real).toMatchObject({ dryRun: false });
|
||||||
|
expect(calls.at(-1)!.argv).toEqual(['play', 'listing', '--only', 'en-US']);
|
||||||
|
const replay = errOf(await call('play.listing', { ...p, dryRun: false, confirmToken: token }));
|
||||||
|
expect(replay).toMatchObject({ code: ERR.confirmInvalid, data: { reason: 'replayed' } });
|
||||||
|
const soon = mint(SECRET, 'play.listing', p, { now, ttlMs: 10 });
|
||||||
|
now += 11;
|
||||||
|
expect(errOf(await call('play.listing', { ...p, dryRun: false, confirmToken: soon })).data).toEqual({ reason: 'expired' });
|
||||||
|
// a read method never needs a token, and dryRun false on it is just a normal run
|
||||||
|
expect(resOf(await call('check', { project: DEMO, dryRun: false })).dryRun).toBe(false);
|
||||||
|
});
|
||||||
|
test('cancellation answers -32800 and kills the child', async () => {
|
||||||
|
const { s, call, nextId } = await session(() => ({ wait: new Promise(() => {}) }));
|
||||||
|
const id = nextId();
|
||||||
|
const pending = call('validate', { project: DEMO });
|
||||||
|
await Bun.sleep(5);
|
||||||
|
await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } });
|
||||||
|
expect(errOf(await pending).code).toBe(ERR.cancelled);
|
||||||
|
});
|
||||||
|
test('portfolio.status: apps across platforms, release trains, catalog parity, per-app errors, progress n/total', async () => {
|
||||||
|
const summary = { dir: DEMO, name: 'Demo', apple: { bundleId: 'com.example.demo', appId: null }, play: { packageName: 'com.example.demo' }, platforms: ['ios', 'android'], products: 2, productIds: ['coins', 'no_ads'], subscriptions: 0, subscriptionIds: [], catalog: { ios: ['coins', 'no_ads'], android: ['coins', 'no_ads'] } };
|
||||||
|
const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: summary }
|
||||||
|
: argv[0] === 'check' ? { data: { ok: true, problems: [], warnings: ['w'] } }
|
||||||
|
: argv[0] === 'apple' ? { code: 1, out: 'error: ASC_KEY_ID and ASC_ISSUER_ID are not set' }
|
||||||
|
: argv[0] === 'play' ? { data: { tracks: [{ track: 'production', releases: [{ name: '1.2.0 (12)', versionCodes: ['12'], status: 'completed' }] }, { track: 'beta', releases: [{ name: '1.3.0', versionCodes: ['13'], status: 'completed' }] }], products: [{ productId: 'coins' }] } } : {});
|
||||||
|
const r = resOf(await call('portfolio.status', { projects: [DEMO, '/nope/game'], live: true })) as { apps: J[] };
|
||||||
|
expect(r.apps[0]).toMatchObject({ project: DEMO, app: { id: DEMO, name: 'Demo', platforms: { ios: { bundleId: 'com.example.demo' }, android: { packageName: 'com.example.demo' } } },
|
||||||
|
check: { ok: true, warnings: ['w'] }, storeErrors: { ios: 'ASC_KEY_ID and ASC_ISSUER_ID are not set' }, ok: false });
|
||||||
|
expect(r.apps[0]!.release).toMatchObject({ source: 'live', current: { version: '1.2.0', ios: null, android: { phase: 'live', build: '12' } }, next: { version: '1.3.0', android: { phase: 'testing', track: 'beta' } } });
|
||||||
|
expect(r.apps[0]!.catalog).toMatchObject({ checked: 'live', missingAndroid: ['no_ads'], missingIos: [], ok: false });
|
||||||
|
expect(r.apps[1]).toMatchObject({ ok: false, summary: null, app: null });
|
||||||
|
expect((r.apps[1]!.errors as string[])[0]).toContain('not a folder');
|
||||||
|
const prog = sent.filter(m => m.method === 'progress').map(m => (m.params as J).n);
|
||||||
|
expect(prog.sort()).toEqual([1, 2]);
|
||||||
|
expect(errOf(await call('portfolio.status', { projects: [] })).code).toBe(ERR.invalidParams);
|
||||||
|
});
|
||||||
|
test('children never inherit session secrets; only credential names pass', () => {
|
||||||
|
process.env.STOREBOUND_SESSION_SECRET = 'x';
|
||||||
|
try { expect(childEnv({}, true).STOREBOUND_SESSION_SECRET).toBeUndefined(); } finally { delete process.env.STOREBOUND_SESSION_SECRET; }
|
||||||
|
expect(childEnv({}, true)).toMatchObject({ STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1', NO_COLOR: '1' });
|
||||||
|
expect(pickCallEnv({ PATH: '/x', ASC_ISSUER_ID: 'i', ASC_P8: 3 })).toEqual({ ASC_ISSUER_ID: 'i' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Talks to a real `storebound serve --stdio` process (source or compiled). */
|
||||||
|
async function stdioRoundTrip(cmd: string[]): Promise<J[]> {
|
||||||
|
const p = Bun.spawn([...cmd, 'serve', '--stdio'], { cwd: ROOT, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
const lines = [
|
||||||
|
{ jsonrpc: '2.0', id: 1, method: 'system.version' },
|
||||||
|
{ jsonrpc: '2.0', id: 2, method: 'session.hello', params: { secret: SECRET_HEX } },
|
||||||
|
{ jsonrpc: '2.0', id: 3, method: 'project.inspect', params: { project: DEMO } },
|
||||||
|
{ jsonrpc: '2.0', id: 4, method: 'shots.check', params: { project: DEMO } },
|
||||||
|
{ jsonrpc: '2.0', id: 5, method: 'play.listing', params: { project: DEMO, dryRun: false, confirmToken: 'sbt1.1.AAAAAAAAAAAAAAAAAAAAAA.' + 'A'.repeat(43) } },
|
||||||
|
];
|
||||||
|
// hello must be answered before the next request is read: send the version probe, then the rest
|
||||||
|
p.stdin.write(lines.map(l => JSON.stringify(l)).join('\n') + '\n');
|
||||||
|
await p.stdin.flush();
|
||||||
|
const out: J[] = [];
|
||||||
|
const reader = p.stdout.getReader();
|
||||||
|
const dec = new TextDecoder();
|
||||||
|
let buf = '';
|
||||||
|
const deadline = Date.now() + 25_000;
|
||||||
|
while (out.filter(m => m.id !== undefined).length < lines.length && Date.now() < deadline) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buf += dec.decode(value, { stream: true });
|
||||||
|
let nl: number;
|
||||||
|
while ((nl = buf.indexOf('\n')) >= 0) { out.push(JSON.parse(buf.slice(0, nl)) as J); buf = buf.slice(nl + 1); }
|
||||||
|
}
|
||||||
|
p.stdin.end();
|
||||||
|
await p.exited;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkRoundTrip(out: J[]): void {
|
||||||
|
const byId = (id: number) => out.find(m => m.id === id)!;
|
||||||
|
expect(errOf(byId(1)).code).toBe(ERR.notInitialized);
|
||||||
|
expect(resOf(byId(2)).protocol).toBe('storebound-desktop/1');
|
||||||
|
expect(resOf(byId(3))).toMatchObject({ name: 'Prism Puddle', play: { packageName: 'com.example.prismpuddle' } });
|
||||||
|
const shots = resOf(byId(4));
|
||||||
|
expect(shots.command).toBe('storebound shots check --json');
|
||||||
|
expect((shots.data as J).issues).toBeArray();
|
||||||
|
expect(errOf(byId(5)).code).toBe(ERR.confirmInvalid);
|
||||||
|
expect(out.some(m => m.method === 'progress')).toBe(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('serve --stdio over a real pipe', () => {
|
||||||
|
test('from source', async () => { checkRoundTrip(await stdioRoundTrip([process.execPath, join(ROOT, 'cli/index.ts')])); }, 30_000);
|
||||||
|
|
||||||
|
test('compiled sidecar for this machine: version + handshake, no private paths inside', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'sb-sidecar-'));
|
||||||
|
try {
|
||||||
|
const bin = await buildOne(hostTarget(), dir);
|
||||||
|
expect(existsSync(bin)).toBe(true);
|
||||||
|
const v = Bun.spawnSync([bin, 'version'], { cwd: ROOT, stdout: 'pipe' });
|
||||||
|
expect(v.exitCode).toBe(0);
|
||||||
|
expect(v.stdout.toString().trim()).toMatch(/^\d+\.\d+\.\d+/);
|
||||||
|
expect(leaks(bin)).toEqual([]);
|
||||||
|
checkRoundTrip(await stdioRoundTrip([bin]));
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
}, 60_000);
|
||||||
|
});
|
||||||
40
tests/tools.test.ts
Normal file
40
tests/tools.test.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { delimiter, join } from 'node:path';
|
||||||
|
import { childEnv } from '../cli/lib/runner';
|
||||||
|
import { detectTools, parseVersion, toolPath } from '../cli/lib/tools';
|
||||||
|
|
||||||
|
describe('local tools (desktop Dependencies screen)', () => {
|
||||||
|
test('version banners', () => {
|
||||||
|
expect(parseVersion('ffmpeg version 7.1.1 Copyright (c) 2000-2025')).toBe('7.1.1');
|
||||||
|
expect(parseVersion('ffmpeg version N-118000-g1234abcd-20250101 Copyright')).toBe('N-118000-g1234abcd-20250101');
|
||||||
|
expect(parseVersion('Google Chrome for Testing 131.0.6778.85')).toBe('131.0.6778.85');
|
||||||
|
expect(parseVersion('Android Debug Bridge version 1.0.41')).toBe('1.0.41');
|
||||||
|
expect(parseVersion('git version 2.50.1')).toBe('2.50.1');
|
||||||
|
expect(parseVersion(null)).toBeNull();
|
||||||
|
});
|
||||||
|
test('app-managed folders go first on PATH, also for every child command', () => {
|
||||||
|
expect(toolPath({ PATH: '/usr/bin', STOREBOUND_TOOL_PATH: '/app/tools/bin' })).toBe(['/app/tools/bin', '/usr/bin'].join(delimiter));
|
||||||
|
expect(toolPath({ PATH: '/usr/bin' })).toBe('/usr/bin');
|
||||||
|
const before = process.env.STOREBOUND_TOOL_PATH;
|
||||||
|
process.env.STOREBOUND_TOOL_PATH = '/app/tools/bin';
|
||||||
|
try { expect(childEnv().PATH!.startsWith('/app/tools/bin' + delimiter)).toBe(true); } finally {
|
||||||
|
if (before === undefined) delete process.env.STOREBOUND_TOOL_PATH; else process.env.STOREBOUND_TOOL_PATH = before;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test('an app-managed ffmpeg is found first and marked as the app\'s', () => {
|
||||||
|
if (process.platform === 'win32') return;
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'sb-tools-'));
|
||||||
|
try {
|
||||||
|
const f = join(dir, 'ffmpeg');
|
||||||
|
writeFileSync(f, '#!/bin/sh\necho "ffmpeg version 7.1.1-test Copyright"\n');
|
||||||
|
chmodSync(f, 0o755);
|
||||||
|
const tools = detectTools({ PATH: '/usr/bin:/bin', STOREBOUND_TOOL_PATH: dir });
|
||||||
|
const ff = tools.find(t => t.id === 'ffmpeg')!;
|
||||||
|
expect(ff).toMatchObject({ found: true, path: f, version: '7.1.1-test', source: 'app', install: { kind: 'download' } });
|
||||||
|
expect(tools.map(t => t.id)).toEqual(expect.arrayContaining(['ffmpeg', 'ffprobe', 'chrome', 'adb', 'git']));
|
||||||
|
for (const t of tools) if (t.id === 'xcode' || t.id === 'simctl' || t.id === 'adb') expect(t.install.kind).toBe('link');
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
});
|
||||||
71
tools/build-sidecars.ts
Normal file
71
tools/build-sidecars.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
#!/usr/bin/env bun
|
||||||
|
// Compiles the storebound CLI into single-file executables for the desktop app's sidecar (Tauri `externalBin`).
|
||||||
|
// bun tools/build-sidecars.ts every target
|
||||||
|
// bun tools/build-sidecars.ts --host only this machine's target (what `tauri dev` needs)
|
||||||
|
// bun tools/build-sidecars.ts --target bun-linux-x64[,bun-windows-x64]
|
||||||
|
// Output: apps/desktop/src-tauri/binaries/storebound-<rust target triple>[.exe] (Tauri's sidecar naming; gitignored).
|
||||||
|
// macOS outputs are re-signed ad hoc: the signature `bun build --compile` leaves is invalid once the payload is
|
||||||
|
// appended, and the kernel kills such a binary on start (exit 137). Release builds re-sign with Developer ID (D5).
|
||||||
|
// Every output is scanned for the build machine's home and checkout paths: nothing private may ship.
|
||||||
|
import { mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
export const TARGETS: Record<string, string> = {
|
||||||
|
'bun-darwin-arm64': 'aarch64-apple-darwin',
|
||||||
|
'bun-darwin-x64': 'x86_64-apple-darwin',
|
||||||
|
'bun-linux-x64': 'x86_64-unknown-linux-gnu',
|
||||||
|
'bun-linux-arm64': 'aarch64-unknown-linux-gnu',
|
||||||
|
'bun-windows-x64': 'x86_64-pc-windows-msvc',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ROOT = join(import.meta.dir, '..');
|
||||||
|
export const OUT_DIR = join(ROOT, 'apps/desktop/src-tauri/binaries');
|
||||||
|
|
||||||
|
export function hostTarget(): string {
|
||||||
|
const os = process.platform === 'darwin' ? 'darwin' : process.platform === 'win32' ? 'windows' : 'linux';
|
||||||
|
const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
|
||||||
|
return `bun-${os}-${arch}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const outName = (target: string): string => `storebound-${TARGETS[target]}${target.includes('windows') ? '.exe' : ''}`;
|
||||||
|
|
||||||
|
/** Paths of this machine that must not appear in a shipped binary. */
|
||||||
|
export function privateStrings(): string[] {
|
||||||
|
return [...new Set([homedir(), ROOT].filter(s => s.length > 4))];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function leaks(file: string, needles = privateStrings()): string[] {
|
||||||
|
const buf = readFileSync(file);
|
||||||
|
return needles.filter(n => buf.includes(Buffer.from(n)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function buildOne(target: string, outDir = OUT_DIR): Promise<string> {
|
||||||
|
if (!TARGETS[target]) throw new Error(`unknown target ${target} (${Object.keys(TARGETS).join(', ')})`);
|
||||||
|
mkdirSync(outDir, { recursive: true });
|
||||||
|
const out = join(outDir, outName(target));
|
||||||
|
rmSync(out, { force: true });
|
||||||
|
const t = Date.now();
|
||||||
|
const p = Bun.spawnSync(['bun', 'build', '--compile', `--target=${target}`, '--minify-syntax', '--minify-whitespace', 'cli/index.ts', '--outfile', out],
|
||||||
|
{ cwd: ROOT, stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
if (p.exitCode !== 0) throw new Error(`${target}: bun build failed\n${p.stderr.toString()}${p.stdout.toString()}`);
|
||||||
|
if (target.startsWith('bun-darwin') && process.platform === 'darwin') {
|
||||||
|
const s = Bun.spawnSync(['codesign', '--force', '--sign', '-', out], { stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
if (s.exitCode !== 0) throw new Error(`${target}: ad-hoc codesign failed: ${s.stderr.toString()}`);
|
||||||
|
}
|
||||||
|
const hits = leaks(out);
|
||||||
|
if (hits.length) throw new Error(`${target}: ${out} contains private paths (${hits.length}); refusing to keep it`);
|
||||||
|
console.log(`sidecar ${target} -> ${out} (${(statSync(out).size / 1e6).toFixed(1)} MB, ${((Date.now() - t) / 1000).toFixed(1)}s)`);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (import.meta.main) {
|
||||||
|
const argv = process.argv.slice(2);
|
||||||
|
const i = argv.indexOf('--target');
|
||||||
|
const targets = argv.includes('--host') ? [hostTarget()] : i >= 0 ? (argv[i + 1] ?? '').split(',').filter(Boolean) : Object.keys(TARGETS);
|
||||||
|
let failed = 0;
|
||||||
|
for (const t of targets) {
|
||||||
|
try { await buildOne(t); } catch (e) { failed++; console.error(`sidecar ${t}: ${(e as Error).message}`); }
|
||||||
|
}
|
||||||
|
if (failed) process.exit(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