From d6baa6dc6977090b51b727e9f5b40ec3c951e867 Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:41:43 -0700 Subject: [PATCH 01/58] NEW - Updater: Add compact macOS updates Publish per-architecture zstd app archives for smaller macOS in-app updates, with legacy-feed fallback and end-to-end coverage. --- ARCHITECTURE.md | 23 + CHANGELOG.md | 8 +- e2e/updater-zst.failure-modes.md | 61 ++ package-lock.json | 4 +- package.json | 7 +- run.rosie.rosi.metainfo.xml | 1 + scripts/e2e-updater-zst.mjs | 530 +++++++++++++ scripts/gpg-sign.js | 59 +- scripts/pack-macos-updater-zst.js | 289 +++++++ scripts/updater-signature-verifier.d.ts | 1 + scripts/updater-signature-verifier.js | 11 +- scripts/validate-updater-live.js | 8 + scripts/validate-updater-manifest.js | 5 +- scripts/verify-release-draft.js | 4 + src-tauri/Cargo.lock | 31 +- src-tauri/Cargo.toml | 2 +- src-tauri/Info.plist | 2 +- src-tauri/build.rs | 2 + src-tauri/capabilities/default.json | 1 + src-tauri/gen/schemas/acl-manifests.json | 2 +- src-tauri/gen/schemas/capabilities.json | 2 +- src-tauri/gen/schemas/desktop-schema.json | 12 + src-tauri/gen/schemas/macOS-schema.json | 12 + .../get_compact_updater_target.toml | 11 + src-tauri/src/main.rs | 1 + src-tauri/src/platform.rs | 24 + src-tauri/tauri.conf.json | 4 +- .../vendor/tauri-plugin-updater/Cargo.lock | 41 + .../vendor/tauri-plugin-updater/Cargo.toml | 4 + .../vendor/tauri-plugin-updater/PATCHES.md | 21 +- .../vendor/tauri-plugin-updater/ROSI.patch | 739 +++++++++++------- .../src/appimage_archive.rs | 28 +- .../tauri-plugin-updater/src/updater.rs | 193 ++++- src/commands.ts | 1 + src/updater.ts | 32 +- 35 files changed, 1853 insertions(+), 323 deletions(-) create mode 100644 e2e/updater-zst.failure-modes.md create mode 100644 scripts/e2e-updater-zst.mjs create mode 100644 scripts/pack-macos-updater-zst.js create mode 100644 src-tauri/permissions/autogenerated/get_compact_updater_target.toml diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index dd28bb1c..3806d87a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -111,6 +111,28 @@ builds. The release pipeline (`scripts/run-release.js`, `release-session.js`, The vendored `src-tauri/vendor/tauri-plugin-updater` carries install-safety patches, documented in `src-tauri/vendor/tauri-plugin-updater/PATCHES.md`. +### Compact macOS updates + +Fresh installs use the universal DMG/ZIP. In-app updates on macOS download a +per-arch `ROSI-{aarch64,x86_64}.app.tar.zst` instead of the universal +`ROSI.app.tar.gz` (141.5 MB to about 60 MB): + +- `release:mac:continue` also runs `tauri build --target {aarch64,x86_64}-apple-darwin --bundles app`. + `scripts/pack-macos-updater-zst.js` then repacks each per-arch `.app.tar.gz` with + `zstd --long=27` and signs the result (`tauri signer sign --app-version`). The long + window dedupes `rosi-ffmpeg` against `rosi-ffprobe`. The tar bytes are unchanged, so + the bundle signature and staple survive. +- `scripts/gpg-sign.js` publishes them under `latest-darwin[-beta]-{arch}-app-zst.json` + and never collects the per-arch builds' arch-less `.app.tar.gz`. +- Packaged macOS apps ask for that target (`get_compact_updater_target`). If the + compact feed is missing they fall back to the universal feed, which stays published + for clients older than 5.1.0. +- `rosi-yt-dlp` is upstream's universal2 binary and already compressed, so about + 36 MB of every update is yt-dlp. + +Failure modes: `e2e/updater-zst.failure-modes.md`. Check: `npm run test:e2e:updater-zst` +(report in `e2e/artifacts/updater-zst-report.json`). + ### macOS entitlements for sidecars (planned, not implemented) Today `src-tauri/entitlements.plist` grants `disable-library-validation` and @@ -150,6 +172,7 @@ Ordered plan (confirm each Tauri step with a dry run before changing the pipelin insert steps 2 to 5 into `scripts/release-session.js` or `run-release.js` between `tauri build` and checksum/GPG signing in `scripts/gpg-sign.js`. 7. Regenerated artifacts to re-check before publish: the `.app`, `.app.tar.gz`, + the per-arch bundles and their `.app.tar.zst` (repack after re-signing), `.sig`, the `latest-*.json` manifests, the DMG, the ZIP, checksums, and GPG signatures. `verify-release-draft.js` must pass on the final set. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ec647cf..d45e6d60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,8 @@ | Windows | macOS | Linux | | :-- | :-- | :-- | -| **EXE: [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.0.2/ROSI-Windows-x64.exe) / [arm64](https://github.com/BurntToasters/ROSI/releases/download/v5.0.2/ROSI-Windows-arm64.exe)** | **[Universal DMG](https://github.com/BurntToasters/ROSI/releases/download/v5.0.2/ROSI-MacOS-universal.dmg)** | **AppImage:** [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.0.2/ROSI-Linux-x64.AppImage) | -|
| **[Universal ZIP](https://github.com/BurntToasters/ROSI/releases/download/v5.0.2/ROSI-MacOS-universal.zip)** | **Flatpak:** [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.0.2/ROSI-Linux-x64.flatpak) | +| **EXE: [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Windows-x64.exe) / [arm64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Windows-arm64.exe)** | **[Universal DMG](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-universal.dmg)** | **AppImage:** [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Linux-x64.AppImage) | +|
| **[Universal ZIP](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-universal.zip)** | **Flatpak:** [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Linux-x64.flatpak) | > macOS downloads require macOS 15 or later. @@ -16,6 +16,10 @@ ROSI! A cross platform yt-dlp GUI built on Tauri V2! +## Changes in `v5.1.0-beta.1:` + +- **Fix:** (add release notes) + ## Changes in `v5.0.2:` - **YT-DLP:** Updated `yt-dlp` to `2026.10.21`. diff --git a/e2e/updater-zst.failure-modes.md b/e2e/updater-zst.failure-modes.md new file mode 100644 index 00000000..bdbc4fe2 --- /dev/null +++ b/e2e/updater-zst.failure-modes.md @@ -0,0 +1,61 @@ +# Compact macOS updater (per-arch `.app.tar.zst`) failure modes + +Enumerated before implementation. Each case names the layer that must catch it. +`scripts/e2e-updater-zst.mjs` exercises the pipeline end to end and writes +`e2e/artifacts/updater-zst-report.json`. + +## Z01: archive decoding (vendored updater plugin) + +1. A truncated `.tar.zst` download must fail extraction. The live app must + stay untouched and the update must stay retryable. +2. A frame whose window exceeds 2^27 bytes (for example, compressed with + `--long=31`) must be rejected rather than allocating an unbounded window. +3. A decompression bomb (small archive, huge tar payload) must stop at the + decompressed-byte cap. +4. Garbage after the last zstd frame, or a tar stream without both end + blocks, must be rejected the same way the AppImage reader rejects it. +5. A gzip `.app.tar.gz` must still extract. Old and new feeds can both reach + a new client. +6. Unknown leading bytes (neither gzip nor zstd magic) must fail with an + invalid-format error, never be fed to a decoder. +7. Every existing tar member rule (confinement, hard links, symlink targets, + directory collisions) must apply to zstd archives unchanged. + +## Z02: staged bundle contents + +1. A zstd archive whose app lacks a sidecar, or whose identity differs, must + be refused by the existing completeness and identity checks. +2. A per-arch bundle for the wrong architecture must never be offered: the + feed key carries the arch, and the client asks for its own compile-time + arch (Rosetta processes ask for x86_64). +3. An arm64-only app later moved to an Intel Mac will not launch. This is + accepted and documented; recovery is the universal DMG. + +## Z03: client target selection and fallback + +1. A packaged macOS app asks for `darwin-{arch}-app-zst` (stable) or + `darwin-beta-{arch}-app-zst` (beta). +2. If the compact feed is missing or lacks the key (a release published + without zst artifacts), the check must fall back to the legacy target and + still find the update. +3. A compact feed that exists and reports no newer version must not trigger + the fallback. +4. Clients on 5.0.x never request the compact key and keep receiving the + universal `.app.tar.gz`. +5. Windows, Linux, and Flatpak targets must not change. + +## Z04: release pipeline + +1. Per-arch builds also produce an arch-less `ROSI.app.tar.gz`. It must never + be collected as the universal updater archive, because then an Intel Mac + could receive an arm64 bundle. +2. The packer must refuse a missing or stale per-arch `.app.tar.gz`, a tar + whose top-level entry is not `ROSI.app`, and a bundle whose main executable + is not thin for the expected arch. +3. The repacked `.tar.zst` must hold the exact tar bytes from Tauri's archive + (round-trip check), so the code signature and staple inside survive. +4. A missing or mismatched `.sig` must stop manifest generation. +5. Stable and beta compact manifests must be generated, validated, listed in + the required beta-manifest set, and pass the live validator. +6. Compact entries must never become the generic `darwin-{arch}` fallback for + old clients. diff --git a/package-lock.json b/package-lock.json index f2ca2697..83d56735 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "rosi", - "version": "5.0.2", + "version": "5.1.0-beta.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "rosi", - "version": "5.0.2", + "version": "5.1.0-beta.1", "license": "MPL-2.0", "dependencies": { "@tauri-apps/api": "^2.12.0", diff --git a/package.json b/package.json index 013a6945..bfbf745c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rosi", - "version": "5.0.2", + "version": "5.1.0-beta.1", "license": "MPL-2.0", "private": true, "packageManager": "npm@12.0.2", @@ -37,6 +37,7 @@ "test:rust": "npm run prepare:rust-tests && cargo test --locked --manifest-path src-tauri/Cargo.toml --all-targets", "test:e2e": "node scripts/test-e2e.js", "test:e2e:stability": "node scripts/test-e2e.js --repeat 5", + "test:e2e:updater-zst": "node scripts/e2e-updater-zst.mjs", "test:all": "node scripts/test-all.js", "test:cargo-safe-update": "node --test scripts/cargo-safe-update.test.mjs scripts/check-cargo-update-policy.test.mjs scripts/test-all.test.js scripts/run-release.test.js scripts/github-cli.test.cjs scripts/release-branch-protection.test.cjs scripts/release-licenses.test.mjs scripts/npm-dev-audit.test.cjs scripts/generate-cargo-licenses.test.mjs scripts/check-rustsec-ignore-policy.test.mjs scripts/legacy-v4-feed.test.mjs scripts/security-release-repairs.test.mjs scripts/round2-release-updater.test.mjs scripts/test-e2e-round2.test.mjs scripts/git-reset.test.mjs scripts/fetch-ytdlp-gpg-path.test.mjs scripts/release-preflight.test.mjs scripts/msstore-pack.test.mjs scripts/test-e2e-only.test.mjs scripts/test-e2e-background.test.mjs", "check:cargo-update-policy": "node scripts/check-cargo-update-policy.mjs", @@ -106,6 +107,8 @@ "build:mac:universal:prepared": "dotenv -e .env -- tauri build --target universal-apple-darwin --bundles dmg,app -- --locked", "build:mac:universal": "npm run sync-version && npm run licenses && npm run prepare:sidecars && npm run build:mac:universal:prepared", "build:mac:zip": "node scripts/zip-macos.js", + "build:mac:updater-arches:prepared": "dotenv -e .env -- tauri build --target aarch64-apple-darwin --bundles app -- --locked && dotenv -e .env -- tauri build --target x86_64-apple-darwin --bundles app -- --locked", + "build:mac:updater-zst": "dotenv -e .env -- node scripts/pack-macos-updater-zst.js", "mac:ssh:keychain": "bash scripts/mac-keychain-ssh.sh", "build:linux:x64:prepared": "dotenv -e .env -- tauri build --target x86_64-unknown-linux-gnu --bundles appimage -- --locked", "build:linux:arm64:prepared": "dotenv -e .env -- tauri build --target aarch64-unknown-linux-gnu --bundles appimage -- --locked", @@ -138,7 +141,7 @@ "release:win:continue": "npm run release:session:verify && npm run release:licenses && npm run release:draft && npm run release:legacy-v4-feed && npm run rust:targets:win && npm run build:win:prepared && npm run prepare:sidecars && npm run release:sign:gpg && npm run release:finalize", "release:win:resume": "npm run prerelease:prepare && npm run release:win:continue", "release:win": "node scripts/run-release.js win", - "release:mac:continue": "npm run release:session:verify && npm run release:licenses && npm run release:wait-draft && npm run rust:targets:mac && npm run build:mac:universal:prepared && npm run build:mac:zip && npm run release:sign:gpg && npm run release:finalize", + "release:mac:continue": "npm run release:session:verify && npm run release:licenses && npm run release:wait-draft && npm run rust:targets:mac && npm run build:mac:universal:prepared && npm run build:mac:zip && npm run build:mac:updater-arches:prepared && npm run build:mac:updater-zst && npm run release:sign:gpg && npm run release:finalize", "release:mac:resume": "npm run prerelease:prepare && npm run release:mac:continue", "release:mac": "node scripts/run-release.js mac", "release:mac:ssh": "npm run mac:ssh:keychain && node scripts/run-release.js mac", diff --git a/run.rosie.rosi.metainfo.xml b/run.rosie.rosi.metainfo.xml index 544e1d6f..f5eb72d8 100644 --- a/run.rosie.rosi.metainfo.xml +++ b/run.rosie.rosi.metainfo.xml @@ -41,6 +41,7 @@ + diff --git a/scripts/e2e-updater-zst.mjs b/scripts/e2e-updater-zst.mjs new file mode 100644 index 00000000..fba994c9 --- /dev/null +++ b/scripts/e2e-updater-zst.mjs @@ -0,0 +1,530 @@ +#!/usr/bin/env node +// End-to-end check of the compact macOS updater path, failure modes in +// e2e/updater-zst.failure-modes.md. It runs the real packer, Tauri signer, +// manifest generator and validator, the vendored plugin's extractor, and the +// renderer's updater.ts against real release archives, then writes +// e2e/artifacts/updater-zst-report.json. +// +// Inputs: per-arch `ROSI.app.tar.gz` from `tauri build --target +// {aarch64,x86_64}-apple-darwin --bundles app` when present. Otherwise they are +// derived from the universal archive and the prepared per-arch sidecars (the +// bundle signature is then invalid, which this check does not depend on). +// Requires macOS and zstd. + +import assert from "assert/strict"; +import fs from "fs"; +import os from "os"; +import path from "path"; +import vm from "vm"; +import { spawnSync } from "child_process"; +import { createRequire } from "module"; +import { fileURLToPath } from "url"; +import { + ARCHES, + assertPerArchBundle, + bundleArchivePath, + packMacosUpdaterArchive, +} from "./pack-macos-updater-zst.js"; +import { + generateUpdaterManifests, + isPerArchTauriAppArchive, +} from "./gpg-sign.js"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const require = createRequire(import.meta.url); +const reportPath = path.join( + root, + "e2e", + "artifacts", + "updater-zst-report.json", +); +const universalArchive = path.join( + root, + "src-tauri/target/universal-apple-darwin/release/bundle/macos/ROSI.app.tar.gz", +); +const version = JSON.parse( + fs.readFileSync(path.join(root, "package.json"), "utf8"), +).version; +const scenarios = []; + +function run(command, args, options = {}) { + const result = spawnSync(command, args, { + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + ...options, + }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error( + `${command} ${args.join(" ")} exited ${result.status}\n${result.stderr}${result.stdout}`, + ); + } + return result.stdout; +} + +async function scenario(id, title, body) { + const started = Date.now(); + try { + const details = (await body()) ?? {}; + scenarios.push({ + id, + title, + ok: true, + ms: Date.now() - started, + ...details, + }); + console.log(`ok ${id} ${title}`); + } catch (error) { + scenarios.push({ + id, + title, + ok: false, + ms: Date.now() - started, + error: error instanceof Error ? error.message : String(error), + }); + console.log( + `FAIL ${id} ${title}\n ${error instanceof Error ? error.message : error}`, + ); + } +} + +/** + * Per-arch input archive: the real Tauri build when present. Otherwise the + * universal bundle with `rosi` thinned and the per-arch sidecars Tauri would + * bundle (src-tauri/binaries) swapped in. + */ +function perArchInput(arch, scratch) { + const built = bundleArchivePath(arch); + if (fs.existsSync(built)) + return { path: built, source: "tauri-per-arch-build" }; + const extractRoot = path.join(scratch, `per-arch-${arch}`); + fs.mkdirSync(extractRoot, { recursive: true }); + run("tar", ["-xzf", universalArchive, "-C", extractRoot]); + const macos = path.join(extractRoot, "ROSI.app/Contents/MacOS"); + const main = path.join(macos, "rosi"); + run("lipo", [ + main, + "-thin", + ARCHES[arch].lipoArch, + "-output", + `${main}.thin`, + ]); + fs.renameSync(`${main}.thin`, main); + for (const sidecar of ["rosi-yt-dlp", "rosi-ffmpeg", "rosi-ffprobe"]) { + fs.copyFileSync( + path.join( + root, + "src-tauri/binaries", + `${sidecar}-${ARCHES[arch].rustTarget}`, + ), + path.join(macos, sidecar), + ); + } + const output = path.join(scratch, `ROSI-${arch}-input.app.tar.gz`); + run( + "tar", + [ + "--no-xattrs", + "--no-mac-metadata", + "-czf", + output, + "-C", + extractRoot, + "ROSI.app", + ], + { + env: { ...process.env, COPYFILE_DISABLE: "1" }, + }, + ); + return { path: output, source: "universal-bundle-with-per-arch-sidecars" }; +} + +function tauriCli(args) { + // Never let a release key from the environment override the throwaway key. + const env = Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => !name.startsWith("TAURI_SIGNING_"), + ), + ); + return run(path.join(root, "node_modules/.bin/tauri"), args, { + cwd: root, + env, + }); +} + +/** Runs src/updater.ts against a scripted feed; returns the targets it checked. */ +async function runRendererCheck({ channel, compactTarget, feed }) { + const ts = require(path.join(root, "node_modules/typescript")); + const source = fs + .readFileSync(path.join(root, "src/updater.ts"), "utf8") + .replaceAll("import.meta.env.VITE_ROSI_E2E", "'1'"); + const js = ts.transpileModule(source, { + compilerOptions: { + target: ts.ScriptTarget.ES2020, + module: ts.ModuleKind.CommonJS, + }, + }).outputText; + const checks = []; + const statuses = []; + const window = { + __ROSI_E2E__: { + updaterAdapter: { + invoke: async (command) => + ({ + is_packaged: true, + is_flatpak: false, + get_settings: { updateChannel: channel }, + get_beta_updater_target: "darwin-beta-aarch64-app", + get_compact_updater_target: compactTarget, + })[command], + check: async (target) => { + checks.push(target ?? null); + const result = feed(target ?? null); + if (result instanceof Error) throw result; + if (!result) return null; + return { + version: result, + body: "", + rawJson: {}, + download: async () => {}, + install: async () => {}, + close: async () => {}, + }; + }, + }, + }, + }; + const exports = {}; + vm.runInNewContext(js, { + exports, + require: (id) => + id.includes("/app") + ? { getVersion: async () => "5.1.0" } + : { invoke: () => {}, check: () => {} }, + window, + console, + Date, + Set, + Object, + Error, + Promise, + setTimeout, + clearTimeout, + }); + exports.onUpdaterStatus((event) => statuses.push(event)); + const error = await exports.checkForUpdates(); + return { + checks, + error, + available: + statuses.find((event) => event.status === "available")?.version ?? null, + }; +} + +async function main() { + if (process.platform !== "darwin") + throw new Error("e2e-updater-zst runs on macOS only."); + if (!fs.existsSync(universalArchive)) { + throw new Error( + `missing ${universalArchive}; build the universal app first.`, + ); + } + const scratch = fs.mkdtempSync( + path.join(os.tmpdir(), "rosi-e2e-updater-zst-"), + ); + const releaseDir = path.join(scratch, "release"); + fs.mkdirSync(releaseDir); + const packed = {}; + const inputs = {}; + try { + for (const arch of Object.keys(ARCHES)) + inputs[arch] = perArchInput(arch, scratch); + + await scenario( + "Z04.2", + "packer refuses a universal bundle as a per-arch input", + () => { + assert.throws( + () => assertPerArchBundle(universalArchive, "aarch64"), + /expected "arm64"/, + ); + }, + ); + + for (const arch of Object.keys(ARCHES)) { + await scenario( + `Z04.3-${arch}`, + `repack ${arch} with a byte-identical tar stream`, + async () => { + packed[arch] = await packMacosUpdaterArchive({ + input: inputs[arch].path, + arch, + version, + outputDir: releaseDir, + sign: false, + }); + const { gzipBytes, zstdBytes, tarSha256 } = packed[arch]; + return { + input: inputs[arch].source, + gzipBytes, + zstdBytes, + savedPercent: Number( + (100 - (zstdBytes / gzipBytes) * 100).toFixed(1), + ), + tarSha256, + }; + }, + ); + } + + const keyPath = path.join(scratch, "updater.key"); + await scenario( + "Z04.4", + "throwaway minisign key signs every updater archive", + () => { + tauriCli(["signer", "generate", "--ci", "-p", "", "-w", keyPath]); + fs.copyFileSync( + universalArchive, + path.join(releaseDir, "ROSI.app.tar.gz"), + ); + for (const name of [ + "ROSI.app.tar.gz", + ...Object.keys(ARCHES).map((arch) => + path.basename(packed[arch].output), + ), + ]) { + tauriCli([ + "signer", + "sign", + "-f", + keyPath, + "-p", + "", + "--app-version", + version, + path.join(releaseDir, name), + ]); + } + }, + ); + + let manifests = {}; + await scenario( + "Z04.5", + "generator writes and validates stable and beta compact feeds", + () => { + const files = fs + .readdirSync(releaseDir) + .map((name) => path.join(releaseDir, name)); + const publicKey = fs.readFileSync(`${keyPath}.pub`, "utf8").trim(); + const written = generateUpdaterManifests(files, { + outputDir: releaseDir, + publicKey, + }); + manifests = Object.fromEntries( + written.map((file) => [ + path.basename(file), + JSON.parse(fs.readFileSync(file, "utf8")), + ]), + ); + for (const arch of Object.keys(ARCHES)) { + for (const channel of ["", "-beta"]) { + const key = `darwin${channel}-${arch}-app-zst`; + const manifest = manifests[`latest-${key}.json`]; + assert.ok(manifest, `latest-${key}.json was not generated`); + assert.deepEqual(Object.keys(manifest.platforms), [key]); + assert.match( + manifest.platforms[key].url, + new RegExp(`/ROSI-${arch}\\.app\\.tar\\.zst$`), + ); + } + } + return { manifests: Object.keys(manifests).sort() }; + }, + ); + + await scenario( + "Z04.6", + "compact archives never become the legacy darwin fallback", + () => { + for (const arch of Object.keys(ARCHES)) { + const generic = manifests[`latest-darwin-${arch}.json`].platforms; + for (const key of [`darwin-${arch}`, `darwin-${arch}-app`]) { + assert.match(generic[key].url, /\/ROSI\.app\.tar\.gz$/, key); + } + } + }, + ); + + await scenario( + "Z04.1", + "per-arch arch-less ROSI.app.tar.gz is never collected", + () => { + const target = path.join(root, "src-tauri/target"); + for (const arch of Object.keys(ARCHES)) { + const dir = path.join( + target, + `${ARCHES[arch].rustTarget}/release/bundle/macos`, + ); + assert.equal( + isPerArchTauriAppArchive(path.join(dir, "ROSI.app.tar.gz")), + true, + ); + assert.equal( + isPerArchTauriAppArchive(path.join(dir, "ROSI.app.tar.gz.sig")), + true, + ); + assert.equal( + isPerArchTauriAppArchive( + path.join(dir, `ROSI-${arch}.app.tar.zst`), + ), + false, + ); + } + assert.equal(isPerArchTauriAppArchive(universalArchive), false); + }, + ); + + await scenario( + "Z01/Z02", + "vendored plugin extracts real archives into complete bundles", + () => { + const archives = [ + universalArchive, + ...Object.keys(ARCHES).map((arch) => packed[arch].output), + ]; + const output = run( + "cargo", + [ + "test", + "--manifest-path", + "src-tauri/vendor/tauri-plugin-updater/Cargo.toml", + "--lib", + "macos_archive_tests", + "--", + "--include-ignored", + "--nocapture", + ], + { + cwd: root, + env: { + ...process.env, + ROSI_UPDATER_ZST_E2E_ARCHIVES: archives.join(":"), + }, + }, + ); + const extractMs = Object.fromEntries( + [ + ...output.matchAll(/ROSI_UPDATER_ZST_E2E (\S+) extract_ms=(\d+)/g), + ].map((m) => [path.basename(m[1]), Number(m[2])]), + ); + assert.equal(Object.keys(extractMs).length, archives.length); + const passed = output.match(/test result: ok\. (\d+) passed/); + assert.ok(passed, "plugin archive tests did not pass"); + return { pluginTestsPassed: Number(passed[1]), extractMs }; + }, + ); + + await scenario( + "Z03.1", + "stable macOS check uses the compact feed", + async () => { + const result = await runRendererCheck({ + channel: "stable", + compactTarget: "darwin-aarch64-app-zst", + feed: () => "9.0.0", + }); + assert.deepEqual(result.checks, ["darwin-aarch64-app-zst"]); + assert.equal(result.available, "9.0.0"); + return result; + }, + ); + + await scenario( + "Z03.2", + "missing compact feed falls back to the legacy target", + async () => { + const missing = new Error( + "Could not fetch a valid release JSON from the remote", + ); + const stable = await runRendererCheck({ + channel: "stable", + compactTarget: "darwin-aarch64-app-zst", + feed: (target) => (target ? missing : "9.0.0"), + }); + assert.equal(stable.checks.at(-1), null); + assert.equal(stable.available, "9.0.0"); + const beta = await runRendererCheck({ + channel: "beta", + compactTarget: "darwin-beta-aarch64-app-zst", + feed: (target) => + target.endsWith("-zst") ? missing : "9.0.0-beta.1", + }); + assert.equal(beta.checks.at(-1), "darwin-beta-aarch64-app"); + assert.equal(beta.available, "9.0.0-beta.1"); + return { stable, beta }; + }, + ); + + await scenario( + "Z03.3", + "compact feed reporting no update does not fall back", + async () => { + const result = await runRendererCheck({ + channel: "stable", + compactTarget: "darwin-aarch64-app-zst", + feed: () => null, + }); + assert.ok( + result.checks.every((target) => target === "darwin-aarch64-app-zst"), + ); + assert.equal(result.available, null); + return result; + }, + ); + + await scenario( + "Z03.5", + "non-macOS builds keep their existing targets", + async () => { + const stable = await runRendererCheck({ + channel: "stable", + compactTarget: null, + feed: () => null, + }); + const beta = await runRendererCheck({ + channel: "beta", + compactTarget: null, + feed: () => null, + }); + assert.ok(stable.checks.every((target) => target === null)); + assert.ok( + beta.checks.every((target) => target === "darwin-beta-aarch64-app"), + ); + return { stable: stable.checks, beta: beta.checks }; + }, + ); + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } + + const report = { + generatedAt: new Date().toISOString(), + version, + host: `${os.platform()}-${os.arch()}`, + universalGzipBytes: fs.statSync(universalArchive).size, + ok: scenarios.every((s) => s.ok), + scenarios, + }; + fs.mkdirSync(path.dirname(reportPath), { recursive: true }); + fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`); + console.log(`report: ${path.relative(root, reportPath)}`); + if (!report.ok) process.exitCode = 1; +} + +main().catch((error) => { + console.error( + `e2e-updater-zst: FAILED: ${error instanceof Error ? error.stack : error}`, + ); + process.exit(1); +}); diff --git a/scripts/gpg-sign.js b/scripts/gpg-sign.js index 1f989a88..d7195a09 100644 --- a/scripts/gpg-sign.js +++ b/scripts/gpg-sign.js @@ -125,12 +125,13 @@ const ARTIFACT_RULES = [ rx(/\.nsis\.zip$/i), rx(/\.app\.tar\.gz$/i), + rx(/\.app\.tar\.zst$/i), rx(/\.appimage\.tar\.gz$/i), rx(/\.(?:exe|msi|dmg|flatpak|appimage)\.sig$/i), rx(/^ROSI(?:-MacOS-universal)?\.zip\.sig$/i), rx(/\.nsis\.zip\.sig$/i), - rx(/\.tar\.gz\.sig$/i), + rx(/\.tar\.(?:gz|zst)\.sig$/i), exact("latest.json"), isPerTargetManifest, @@ -145,6 +146,7 @@ const SIGN_RULES = [ rx(/^ROSI(?:-MacOS-universal)?\.zip$/i), rx(/\.nsis\.zip$/i), rx(/\.app\.tar\.gz$/i), + rx(/\.app\.tar\.zst$/i), rx(/\.appimage\.tar\.gz$/i), ]; @@ -289,6 +291,19 @@ function pickNewestByBasename(paths) { return Array.from(latest.values()).map((entry) => entry.filePath); } +// `tauri build --target {aarch64,x86_64}-apple-darwin` (the per-arch updater +// builds) also writes an arch-less ROSI.app.tar.gz. Only the universal build's +// archive may serve the arch-less `darwin-*-app` targets. +function isPerArchTauriAppArchive(filePath) { + const name = path.basename(filePath); + if (!/\.app\.tar\.gz(?:\.sig)?$/i.test(name) || inferArchFromName(name)) { + return false; + } + return filePath + .split(/[\\/]+/) + .some((part) => /^(?:aarch64|x86_64)-apple-darwin$/i.test(part)); +} + function walk(dir, results = []) { if (!fs.existsSync(dir)) return results; for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { @@ -303,7 +318,7 @@ function walk(dir, results = []) { } function cleanArtifactBaseName(name) { - if (/\.tar\.gz$/i.test(name)) return name; + if (/\.tar\.(?:gz|zst)$/i.test(name)) return name; if (/\.nsis\.zip$/i.test(name)) return name; if (/\.dmg$/i.test(name)) return "ROSI-MacOS-universal.dmg"; @@ -331,6 +346,10 @@ function cleanArtifactName(name) { return cleanArtifactBaseName(name); } +// Installers that only custom-target clients request, on every channel. They +// never become the generic `{os}-{arch}` fallback that older clients read. +const CUSTOM_TARGET_INSTALLERS = new Set(["app-zst"]); + const FALLBACK_INSTALLER_PRIORITY = { windows: { nsis: 3, msi: 2 }, linux: { appimage: 3 }, @@ -399,6 +418,14 @@ function canPopulateFallbackTarget(_target) { function resolveUpdaterTargets(name) { const targets = []; + if (/\.app\.tar\.zst$/i.test(name)) { + // Per-arch only (scripts/pack-macos-updater-zst.js). Packaged macOS apps + // request these through the custom `darwin[-beta]-{arch}-app-zst` target. + const arch = inferArchFromName(name); + if (arch) targets.push({ os: "darwin", arch, installer: "app-zst" }); + return targets; + } + if (/\.app\.tar\.gz$/i.test(name)) { const arch = inferArchFromName(name); const arches = arch ? [arch] : ["x86_64", "aarch64"]; @@ -449,7 +476,10 @@ function updaterChannelVariants( ]; } -function generateUpdaterManifests(files) { +function generateUpdaterManifests( + files, + { outputDir = releaseDir, publicKey } = {}, +) { const byName = new Map(); for (const filePath of files) { byName.set(path.basename(filePath), filePath); @@ -463,10 +493,11 @@ function generateUpdaterManifests(files) { } verifyUpdaterSignatures({ root, - releaseDir, + releaseDir: outputDir, byName, signatureByBaseName, resolveUpdaterTargets, + publicKey, }); const manifests = new Map(); @@ -517,10 +548,13 @@ function generateUpdaterManifests(files) { const installerKey = `${targetName}-${target.arch}-${target.installer}`; const fallbackKey = `${targetName}-${target.arch}`; manifest.platforms[installerKey] = { url, signature }; - if (channel.targetSuffix) { - // A beta check uses the full installer-aware key as its custom Tauri - // target. Give that key its own endpoint manifest so installers do - // not fall through to the generic fallback. + if ( + channel.targetSuffix || + CUSTOM_TARGET_INSTALLERS.has(target.installer) + ) { + // A beta or compact check uses the full installer-aware key as its + // custom Tauri target. Give that key its own endpoint manifest so + // installers do not fall through to the generic fallback. const installerManifestName = `latest-${installerKey}.json`; manifests.set(installerManifestName, { version: VERSION, @@ -582,7 +616,7 @@ function generateUpdaterManifests(files) { if (manifest.notes) { output.notes = manifest.notes; } - const dest = path.join(releaseDir, manifestName); + const dest = path.join(outputDir, manifestName); fs.writeFileSync(dest, JSON.stringify(output, null, 2) + "\n"); console.log( ` + ${manifestName} (${Object.keys(output.platforms).length} platform entries)`, @@ -693,7 +727,9 @@ function collectArtifacts() { fs.mkdirSync(releaseDir, { recursive: true }); const buildSession = readBuildSession(); - const discovered = SEARCH_DIRS.flatMap((d) => walk(d)); + const discovered = SEARCH_DIRS.flatMap((d) => walk(d)).filter( + (filePath) => !isPerArchTauriAppArchive(filePath), + ); const found = discovered.filter( (filePath) => artifactMatchesVersion(path.basename(filePath)) && @@ -1332,6 +1368,8 @@ function requiredPublishedBetaManifestNames() { "darwin-beta-x86_64-app", "darwin-beta-aarch64", "darwin-beta-aarch64-app", + "darwin-beta-x86_64-app-zst", + "darwin-beta-aarch64-app-zst", "linux-beta-x86_64", "linux-beta-x86_64-appimage", ]); @@ -1704,6 +1742,7 @@ export { cleanArtifactName, generateUpdaterManifests, isArtifact, + isPerArchTauriAppArchive, assertReleaseTargetsCommit, buildUploadList, checksumTargetKeysForArtifactName, diff --git a/scripts/pack-macos-updater-zst.js b/scripts/pack-macos-updater-zst.js new file mode 100644 index 00000000..30c4a219 --- /dev/null +++ b/scripts/pack-macos-updater-zst.js @@ -0,0 +1,289 @@ +#!/usr/bin/env node +// Repack the per-arch Tauri updater archives (`ROSI.app.tar.gz` from +// `tauri build --target {aarch64,x86_64}-apple-darwin`) as zstd with a long +// window, then sign them for the updater. A long window dedupes rosi-ffmpeg +// against rosi-ffprobe, which gzip's 32 KB window cannot. +// +// The tar bytes stay identical, so the code signature and notarization staple +// inside the bundle survive. Failure modes: e2e/updater-zst.failure-modes.md (Z04). + +import crypto from "crypto"; +import fs from "fs"; +import os from "os"; +import path from "path"; +import { spawn, spawnSync } from "child_process"; +import { Transform, Writable } from "stream"; +import { pipeline } from "stream/promises"; +import { fileURLToPath } from "url"; +import zlib from "zlib"; +import { isDirectExecutionOf } from "./direct-execution.mjs"; +import { verifyReleaseSession } from "./release-session.js"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +const ARCHES = { + aarch64: { rustTarget: "aarch64-apple-darwin", lipoArch: "arm64" }, + x86_64: { rustTarget: "x86_64-apple-darwin", lipoArch: "x86_64" }, +}; +// Must match MACOS_ZSTD_WINDOW_LOG_MAX in the vendored updater plugin. +const ZSTD_WINDOW_LOG = 27; +const ZSTD_LEVEL = 19; +const BUNDLE_PREFIX = "ROSI.app/"; +// Executables that must be thin for the target arch. The size win comes from +// these; a universal one means the input is not a per-arch build. +const THIN_MEMBERS = [ + "ROSI.app/Contents/MacOS/rosi", + "ROSI.app/Contents/MacOS/rosi-ffmpeg", + "ROSI.app/Contents/MacOS/rosi-ffprobe", +]; +// Upstream ships yt-dlp_macos only as universal2, so every bundle carries +// the same file. It must still run on the target arch. +const MULTI_ARCH_MEMBERS = ["ROSI.app/Contents/MacOS/rosi-yt-dlp"]; + +function run(command, args, options = {}) { + const result = spawnSync(command, args, { encoding: "utf8", ...options }); + if (result.error) { + if (result.error.code === "ENOENT") { + throw new Error( + `${command} was not found.${command === "zstd" ? " Install it with: brew install zstd" : ""}`, + ); + } + throw result.error; + } + if (result.status !== 0) { + throw new Error( + `${command} ${args.join(" ")} failed (${result.status}): ${result.stderr || result.stdout}`, + ); + } + return result.stdout; +} + +function bundleArchivePath( + arch, + targetRoot = path.join(root, "src-tauri", "target"), +) { + return path.join( + targetRoot, + ARCHES[arch].rustTarget, + "release", + "bundle", + "macos", + "ROSI.app.tar.gz", + ); +} + +function compactArchiveName(arch) { + return `ROSI-${arch}.app.tar.zst`; +} + +/** Z04.2: one top-level ROSI.app, and executables built for `arch`. */ +function assertPerArchBundle(input, arch) { + const members = run("tar", ["-tzf", input], { maxBuffer: 64 * 1024 * 1024 }) + .split("\n") + .filter(Boolean); + const outside = members.filter((name) => !name.startsWith(BUNDLE_PREFIX)); + if (members.length === 0 || outside.length > 0) { + throw new Error( + `${input}: archive must contain only ${BUNDLE_PREFIX}; found ${outside.slice(0, 3).join(", ") || "nothing"}`, + ); + } + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "rosi-updater-zst-")); + try { + run("tar", [ + "-xzf", + input, + "-C", + scratch, + ...THIN_MEMBERS, + ...MULTI_ARCH_MEMBERS, + ]); + const expected = ARCHES[arch].lipoArch; + for (const member of [...THIN_MEMBERS, ...MULTI_ARCH_MEMBERS]) { + const archs = run("lipo", ["-archs", path.join(scratch, member)]).trim(); + const thin = THIN_MEMBERS.includes(member); + if (thin ? archs !== expected : !archs.split(/\s+/).includes(expected)) { + throw new Error( + `${input}: ${member} has architectures "${archs}", expected ${thin ? "" : "to include "}"${expected}"`, + ); + } + } + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } +} + +function hashingPassThrough(hash) { + return new Transform({ + transform(chunk, _encoding, callback) { + hash.update(chunk); + callback(null, chunk); + }, + }); +} + +function childExit(child, label) { + return new Promise((resolve, reject) => { + child.on("error", (error) => + reject( + error.code === "ENOENT" + ? new Error("zstd was not found. Install it with: brew install zstd") + : error, + ), + ); + child.on("close", (code) => + code === 0 + ? resolve() + : reject(new Error(`${label} exited with ${code}`)), + ); + }); +} + +/** Gunzip `input` into zstd at `output`. Returns the tar stream's SHA-256. */ +async function repackGzipAsZstd(input, output) { + const hash = crypto.createHash("sha256"); + const child = spawn( + "zstd", + [ + `-${ZSTD_LEVEL}`, + `--long=${ZSTD_WINDOW_LOG}`, + "-T0", + "-q", + "-f", + "-o", + output, + ], + { stdio: ["pipe", "inherit", "inherit"] }, + ); + const exited = childExit(child, "zstd"); + await Promise.all([ + pipeline( + fs.createReadStream(input), + zlib.createGunzip(), + hashingPassThrough(hash), + child.stdin, + ), + exited, + ]); + return hash.digest("hex"); +} + +/** Decode `file` the way the updater will (window capped at 2^27). */ +async function zstdContentSha256(file) { + const hash = crypto.createHash("sha256"); + const child = spawn( + "zstd", + ["-dc", `--long=${ZSTD_WINDOW_LOG}`, "-q", file], + { + stdio: ["ignore", "pipe", "inherit"], + }, + ); + const exited = childExit(child, "zstd -d"); + await Promise.all([ + pipeline( + child.stdout, + hashingPassThrough(hash), + new Writable({ write: (_c, _e, cb) => cb() }), + ), + exited, + ]); + return hash.digest("hex"); +} + +function signUpdaterArtifact(file, version) { + const tauri = path.join(root, "node_modules", ".bin", "tauri"); + run(tauri, ["signer", "sign", "--app-version", version, file], { + cwd: root, + stdio: ["ignore", "pipe", "pipe"], + }); + const signature = `${file}.sig`; + if (!fs.existsSync(signature) || fs.statSync(signature).size === 0) { + throw new Error(`tauri signer did not write ${signature}`); + } + return signature; +} + +/** + * Pack one per-arch archive. `sign: false` skips the minisign step (callers + * that sign with their own key, such as the E2E harness, do it afterwards). + */ +async function packMacosUpdaterArchive({ + input, + arch, + version, + outputDir, + sign = true, +}) { + if (!ARCHES[arch]) throw new Error(`unsupported macOS arch: ${arch}`); + if (!fs.existsSync(input)) + throw new Error(`missing per-arch updater archive: ${input}`); + assertPerArchBundle(input, arch); + + const output = path.join( + outputDir ?? path.dirname(input), + compactArchiveName(arch), + ); + fs.rmSync(output, { force: true }); + fs.rmSync(`${output}.sig`, { force: true }); + const tarSha256 = await repackGzipAsZstd(input, output); + // Z04.3: the zstd archive must decode to the exact tar Tauri produced. + const roundTripSha256 = await zstdContentSha256(output); + if (roundTripSha256 !== tarSha256) { + fs.rmSync(output, { force: true }); + throw new Error(`${output}: zstd round trip changed the tar stream`); + } + const signature = sign ? signUpdaterArtifact(output, version) : null; + return { + arch, + input, + output, + signature, + tarSha256, + gzipBytes: fs.statSync(input).size, + zstdBytes: fs.statSync(output).size, + }; +} + +async function main() { + if (process.platform !== "darwin") { + throw new Error("pack-macos-updater-zst can only run on macOS."); + } + const session = verifyReleaseSession(root); + const version = JSON.parse( + fs.readFileSync(path.join(root, "package.json"), "utf8"), + ).version; + for (const arch of Object.keys(ARCHES)) { + const input = bundleArchivePath(arch); + if (!fs.existsSync(input)) { + throw new Error( + `missing ${input}. Run tauri build --target ${ARCHES[arch].rustTarget} --bundles app first.`, + ); + } + // Permit coarse filesystem timestamp resolution, as gpg-sign does. + if (fs.statSync(input).mtimeMs < session.startedAt - 2000) { + throw new Error(`${input} predates this release session; rebuild it.`); + } + const result = await packMacosUpdaterArchive({ input, arch, version }); + const saved = 100 - (result.zstdBytes / result.gzipBytes) * 100; + console.log( + ` + ${path.basename(result.output)} (${(result.zstdBytes / 1e6).toFixed(1)} MB; gzip ${(result.gzipBytes / 1e6).toFixed(1)} MB; ${saved.toFixed(0)}% smaller)`, + ); + } +} + +if (isDirectExecutionOf(import.meta.url)) { + main().catch((error) => { + console.error( + `pack-macos-updater-zst: FAILED: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + }); +} + +export { + ARCHES, + ZSTD_WINDOW_LOG, + assertPerArchBundle, + bundleArchivePath, + compactArchiveName, + packMacosUpdaterArchive, +}; diff --git a/scripts/updater-signature-verifier.d.ts b/scripts/updater-signature-verifier.d.ts index 052d0e17..692d4783 100644 --- a/scripts/updater-signature-verifier.d.ts +++ b/scripts/updater-signature-verifier.d.ts @@ -6,4 +6,5 @@ export function verifyUpdaterSignatures(options: { byName: Map; signatureByBaseName: Map; resolveUpdaterTargets(name: string): unknown[]; + publicKey?: string; }): void; diff --git a/scripts/updater-signature-verifier.js b/scripts/updater-signature-verifier.js index 00265c2c..de93a6e6 100644 --- a/scripts/updater-signature-verifier.js +++ b/scripts/updater-signature-verifier.js @@ -20,6 +20,8 @@ export function verifyUpdaterSignatures({ byName, signatureByBaseName, resolveUpdaterTargets, + // Base64 minisign public key; defaults to tauri.conf.json's updater pubkey. + publicKey, }) { const pairs = []; const eligibleArtifacts = []; @@ -52,10 +54,11 @@ export function verifyUpdaterSignatures({ ); } - const tauriConfig = JSON.parse( - fs.readFileSync(path.join(root, "src-tauri", "tauri.conf.json"), "utf8"), - ); - const encodedPublicKey = tauriConfig.plugins?.updater?.pubkey; + const encodedPublicKey = + publicKey ?? + JSON.parse( + fs.readFileSync(path.join(root, "src-tauri", "tauri.conf.json"), "utf8"), + ).plugins?.updater?.pubkey; if (!encodedPublicKey) { throw new Error("tauri.conf.json is missing plugins.updater.pubkey."); } diff --git a/scripts/validate-updater-live.js b/scripts/validate-updater-live.js index 49e85989..385171dd 100644 --- a/scripts/validate-updater-live.js +++ b/scripts/validate-updater-live.js @@ -64,6 +64,8 @@ const TARGETS = [ "windows-aarch64", "darwin-aarch64", "darwin-x86_64", + "darwin-aarch64-app-zst", + "darwin-x86_64-app-zst", "linux-x86_64", "linux-aarch64", "windows-beta-x86_64", @@ -74,6 +76,8 @@ const TARGETS = [ "darwin-beta-aarch64-app", "darwin-beta-x86_64", "darwin-beta-x86_64-app", + "darwin-beta-aarch64-app-zst", + "darwin-beta-x86_64-app-zst", "linux-beta-x86_64", "linux-beta-x86_64-appimage", "linux-beta-aarch64", @@ -85,6 +89,8 @@ const STANDARD_STABLE_TARGETS = [ "windows-aarch64", "darwin-aarch64", "darwin-x86_64", + "darwin-aarch64-app-zst", + "darwin-x86_64-app-zst", "linux-x86_64", ]; @@ -97,6 +103,8 @@ const STANDARD_BETA_TARGETS = [ "darwin-beta-aarch64-app", "darwin-beta-x86_64", "darwin-beta-x86_64-app", + "darwin-beta-aarch64-app-zst", + "darwin-beta-x86_64-app-zst", "linux-beta-x86_64", "linux-beta-x86_64-appimage", ]; diff --git a/scripts/validate-updater-manifest.js b/scripts/validate-updater-manifest.js index 1bc7c78e..7050fd9f 100644 --- a/scripts/validate-updater-manifest.js +++ b/scripts/validate-updater-manifest.js @@ -105,7 +105,7 @@ export function validateManifestData(data, filePath) { ? expectedTarget.replace(/-(?:aarch64|x86_64)$/i, "") : null; const target = expectedTarget.match( - /^(darwin|windows|linux)(-beta)?-(x86_64|aarch64)(?:-(app|nsis|msi|appimage))?$/, + /^(darwin|windows|linux)(-beta)?-(x86_64|aarch64)(?:-(app-zst|app|nsis|msi|appimage))?$/, ); if (!target) { fail(`${filePath}: unsupported manifest target ${expectedTarget}`); @@ -121,7 +121,8 @@ export function validateManifestData(data, filePath) { if ( installer && installer !== defaultInstaller && - !(os === "windows" && installer === "msi") + !(os === "windows" && installer === "msi") && + !(os === "darwin" && installer === "app-zst") ) { fail(`${filePath}: unsupported installer ${installer}`); } diff --git a/scripts/verify-release-draft.js b/scripts/verify-release-draft.js index 84f3ed52..412c9557 100644 --- a/scripts/verify-release-draft.js +++ b/scripts/verify-release-draft.js @@ -95,6 +95,8 @@ export function requiredDraftStableManifestNames({ "windows-aarch64", "darwin-x86_64", "darwin-aarch64", + "darwin-x86_64-app-zst", + "darwin-aarch64-app-zst", "linux-x86_64", ]; if (requireLinuxAarch64) { @@ -115,6 +117,8 @@ export function requiredDraftBetaManifestNames({ "darwin-beta-x86_64-app", "darwin-beta-aarch64", "darwin-beta-aarch64-app", + "darwin-beta-x86_64-app-zst", + "darwin-beta-aarch64-app-zst", "linux-beta-x86_64", "linux-beta-x86_64-appimage", ]; diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 047715fd..194f9360 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3412,7 +3412,7 @@ dependencies = [ [[package]] name = "rosi" -version = "5.0.2" +version = "5.1.0-beta.1" dependencies = [ "getrandom 0.3.4", "libc", @@ -4513,6 +4513,7 @@ dependencies = [ "url", "windows-sys 0.61.2", "zip", + "zstd", ] [[package]] @@ -6115,6 +6116,34 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "zvariant" version = "5.15.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index cf3075f3..b3e2099f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rosi" -version = "5.0.2" +version = "5.1.0-beta.1" description = "Cross-platform yt-dlp GUI built with Tauri." license = "MPL-2.0" authors = ["BurntToasters "] diff --git a/src-tauri/Info.plist b/src-tauri/Info.plist index 9e7ca1e8..8f3054e5 100644 --- a/src-tauri/Info.plist +++ b/src-tauri/Info.plist @@ -3,6 +3,6 @@ CFBundleShortVersionString - 5.0.2 + 5.1.0 diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 6ff67727..cbd8c735 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -41,6 +41,7 @@ const COMMANDS: &[&str] = &[ "get_app_platform", "get_distribution_channel", "get_beta_updater_target", + "get_compact_updater_target", "restart_app", "log_error", "notify_settings_flushed", @@ -87,6 +88,7 @@ const COMMANDS_WITH_E2E: &[&str] = &[ "get_app_platform", "get_distribution_channel", "get_beta_updater_target", + "get_compact_updater_target", "restart_app", "log_error", "notify_settings_flushed", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 111a3754..a8c9517b 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -48,6 +48,7 @@ "allow-get-app-platform", "allow-get-distribution-channel", "allow-get-beta-updater-target", + "allow-get-compact-updater-target", "allow-restart-app", "allow-log-error", "allow-notify-settings-flushed", diff --git a/src-tauri/gen/schemas/acl-manifests.json b/src-tauri/gen/schemas/acl-manifests.json index ad1c8e12..dbd84013 100644 --- a/src-tauri/gen/schemas/acl-manifests.json +++ b/src-tauri/gen/schemas/acl-manifests.json @@ -1 +1 @@ -{"__app-acl__":{"default_permission":null,"permissions":{"allow-add-to-queue":{"identifier":"allow-add-to-queue","description":"Enables the add_to_queue command without any pre-configured scope.","commands":{"allow":["add_to_queue"],"deny":[]}},"allow-cancel-download":{"identifier":"allow-cancel-download","description":"Enables the cancel_download command without any pre-configured scope.","commands":{"allow":["cancel_download"],"deny":[]}},"allow-cancel-formats":{"identifier":"allow-cancel-formats","description":"Enables the cancel_formats command without any pre-configured scope.","commands":{"allow":["cancel_formats"],"deny":[]}},"allow-cancel-queue":{"identifier":"allow-cancel-queue","description":"Enables the cancel_queue command without any pre-configured scope.","commands":{"allow":["cancel_queue"],"deny":[]}},"allow-cancel-video-info":{"identifier":"allow-cancel-video-info","description":"Enables the cancel_video_info command without any pre-configured scope.","commands":{"allow":["cancel_video_info"],"deny":[]}},"allow-check-deno-installed":{"identifier":"allow-check-deno-installed","description":"Enables the check_deno_installed command without any pre-configured scope.","commands":{"allow":["check_deno_installed"],"deny":[]}},"allow-clear-download-activity":{"identifier":"allow-clear-download-activity","description":"Enables the clear_download_activity command without any pre-configured scope.","commands":{"allow":["clear_download_activity"],"deny":[]}},"allow-clear-finished-queue":{"identifier":"allow-clear-finished-queue","description":"Enables the clear_finished_queue command without any pre-configured scope.","commands":{"allow":["clear_finished_queue"],"deny":[]}},"allow-clear-queue":{"identifier":"allow-clear-queue","description":"Enables the clear_queue command without any pre-configured scope.","commands":{"allow":["clear_queue"],"deny":[]}},"allow-detect-gpu":{"identifier":"allow-detect-gpu","description":"Enables the detect_gpu command without any pre-configured scope.","commands":{"allow":["detect_gpu"],"deny":[]}},"allow-download-video":{"identifier":"allow-download-video","description":"Enables the download_video command without any pre-configured scope.","commands":{"allow":["download_video"],"deny":[]}},"allow-e2e-cancel-close-request":{"identifier":"allow-e2e-cancel-close-request","description":"Enables the e2e_cancel_close_request command without any pre-configured scope.","commands":{"allow":["e2e_cancel_close_request"],"deny":[]}},"allow-e2e-emit-stale-download-events":{"identifier":"allow-e2e-emit-stale-download-events","description":"Enables the e2e_emit_stale_download_events command without any pre-configured scope.","commands":{"allow":["e2e_emit_stale_download_events"],"deny":[]}},"allow-e2e-network-pipelining-probe":{"identifier":"allow-e2e-network-pipelining-probe","description":"Enables the e2e_network_pipelining_probe command without any pre-configured scope.","commands":{"allow":["e2e_network_pipelining_probe"],"deny":[]}},"allow-e2e-updater-install-probe":{"identifier":"allow-e2e-updater-install-probe","description":"Enables the e2e_updater_install_probe command without any pre-configured scope.","commands":{"allow":["e2e_updater_install_probe"],"deny":[]}},"allow-export-settings":{"identifier":"allow-export-settings","description":"Enables the export_settings command without any pre-configured scope.","commands":{"allow":["export_settings"],"deny":[]}},"allow-get-app-platform":{"identifier":"allow-get-app-platform","description":"Enables the get_app_platform command without any pre-configured scope.","commands":{"allow":["get_app_platform"],"deny":[]}},"allow-get-beta-updater-target":{"identifier":"allow-get-beta-updater-target","description":"Enables the get_beta_updater_target command without any pre-configured scope.","commands":{"allow":["get_beta_updater_target"],"deny":[]}},"allow-get-default-settings":{"identifier":"allow-get-default-settings","description":"Enables the get_default_settings command without any pre-configured scope.","commands":{"allow":["get_default_settings"],"deny":[]}},"allow-get-distribution-channel":{"identifier":"allow-get-distribution-channel","description":"Enables the get_distribution_channel command without any pre-configured scope.","commands":{"allow":["get_distribution_channel"],"deny":[]}},"allow-get-download-activity":{"identifier":"allow-get-download-activity","description":"Enables the get_download_activity command without any pre-configured scope.","commands":{"allow":["get_download_activity"],"deny":[]}},"allow-get-formats":{"identifier":"allow-get-formats","description":"Enables the get_formats command without any pre-configured scope.","commands":{"allow":["get_formats"],"deny":[]}},"allow-get-queue":{"identifier":"allow-get-queue","description":"Enables the get_queue command without any pre-configured scope.","commands":{"allow":["get_queue"],"deny":[]}},"allow-get-settings":{"identifier":"allow-get-settings","description":"Enables the get_settings command without any pre-configured scope.","commands":{"allow":["get_settings"],"deny":[]}},"allow-get-stats":{"identifier":"allow-get-stats","description":"Enables the get_stats command without any pre-configured scope.","commands":{"allow":["get_stats"],"deny":[]}},"allow-get-video-info":{"identifier":"allow-get-video-info","description":"Enables the get_video_info command without any pre-configured scope.","commands":{"allow":["get_video_info"],"deny":[]}},"allow-import-settings":{"identifier":"allow-import-settings","description":"Enables the import_settings command without any pre-configured scope.","commands":{"allow":["import_settings"],"deny":[]}},"allow-install-deno":{"identifier":"allow-install-deno","description":"Enables the install_deno command without any pre-configured scope.","commands":{"allow":["install_deno"],"deny":[]}},"allow-is-flatpak":{"identifier":"allow-is-flatpak","description":"Enables the is_flatpak command without any pre-configured scope.","commands":{"allow":["is_flatpak"],"deny":[]}},"allow-is-packaged":{"identifier":"allow-is-packaged","description":"Enables the is_packaged command without any pre-configured scope.","commands":{"allow":["is_packaged"],"deny":[]}},"allow-log-error":{"identifier":"allow-log-error","description":"Enables the log_error command without any pre-configured scope.","commands":{"allow":["log_error"],"deny":[]}},"allow-mark-main-window-ready":{"identifier":"allow-mark-main-window-ready","description":"Enables the mark_main_window_ready command without any pre-configured scope.","commands":{"allow":["mark_main_window_ready"],"deny":[]}},"allow-notify-settings-flushed":{"identifier":"allow-notify-settings-flushed","description":"Enables the notify_settings_flushed command without any pre-configured scope.","commands":{"allow":["notify_settings_flushed"],"deny":[]}},"allow-open-external":{"identifier":"allow-open-external","description":"Enables the open_external command without any pre-configured scope.","commands":{"allow":["open_external"],"deny":[]}},"allow-open-file-location":{"identifier":"allow-open-file-location","description":"Enables the open_file_location command without any pre-configured scope.","commands":{"allow":["open_file_location"],"deny":[]}},"allow-remove-from-queue":{"identifier":"allow-remove-from-queue","description":"Enables the remove_from_queue command without any pre-configured scope.","commands":{"allow":["remove_from_queue"],"deny":[]}},"allow-reorder-queue-item":{"identifier":"allow-reorder-queue-item","description":"Enables the reorder_queue_item command without any pre-configured scope.","commands":{"allow":["reorder_queue_item"],"deny":[]}},"allow-reset-settings":{"identifier":"allow-reset-settings","description":"Enables the reset_settings command without any pre-configured scope.","commands":{"allow":["reset_settings"],"deny":[]}},"allow-reset-stats":{"identifier":"allow-reset-stats","description":"Enables the reset_stats command without any pre-configured scope.","commands":{"allow":["reset_stats"],"deny":[]}},"allow-restart-app":{"identifier":"allow-restart-app","description":"Enables the restart_app command without any pre-configured scope.","commands":{"allow":["restart_app"],"deny":[]}},"allow-retry-queue-item":{"identifier":"allow-retry-queue-item","description":"Enables the retry_queue_item command without any pre-configured scope.","commands":{"allow":["retry_queue_item"],"deny":[]}},"allow-save-settings":{"identifier":"allow-save-settings","description":"Enables the save_settings command without any pre-configured scope.","commands":{"allow":["save_settings"],"deny":[]}},"allow-select-download-location":{"identifier":"allow-select-download-location","description":"Enables the select_download_location command without any pre-configured scope.","commands":{"allow":["select_download_location"],"deny":[]}},"allow-show-notification":{"identifier":"allow-show-notification","description":"Enables the show_notification command without any pre-configured scope.","commands":{"allow":["show_notification"],"deny":[]}},"allow-start-queue":{"identifier":"allow-start-queue","description":"Enables the start_queue command without any pre-configured scope.","commands":{"allow":["start_queue"],"deny":[]}},"deny-add-to-queue":{"identifier":"deny-add-to-queue","description":"Denies the add_to_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["add_to_queue"]}},"deny-cancel-download":{"identifier":"deny-cancel-download","description":"Denies the cancel_download command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_download"]}},"deny-cancel-formats":{"identifier":"deny-cancel-formats","description":"Denies the cancel_formats command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_formats"]}},"deny-cancel-queue":{"identifier":"deny-cancel-queue","description":"Denies the cancel_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_queue"]}},"deny-cancel-video-info":{"identifier":"deny-cancel-video-info","description":"Denies the cancel_video_info command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_video_info"]}},"deny-check-deno-installed":{"identifier":"deny-check-deno-installed","description":"Denies the check_deno_installed command without any pre-configured scope.","commands":{"allow":[],"deny":["check_deno_installed"]}},"deny-clear-download-activity":{"identifier":"deny-clear-download-activity","description":"Denies the clear_download_activity command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_download_activity"]}},"deny-clear-finished-queue":{"identifier":"deny-clear-finished-queue","description":"Denies the clear_finished_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_finished_queue"]}},"deny-clear-queue":{"identifier":"deny-clear-queue","description":"Denies the clear_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_queue"]}},"deny-detect-gpu":{"identifier":"deny-detect-gpu","description":"Denies the detect_gpu command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_gpu"]}},"deny-download-video":{"identifier":"deny-download-video","description":"Denies the download_video command without any pre-configured scope.","commands":{"allow":[],"deny":["download_video"]}},"deny-e2e-cancel-close-request":{"identifier":"deny-e2e-cancel-close-request","description":"Denies the e2e_cancel_close_request command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_cancel_close_request"]}},"deny-e2e-emit-stale-download-events":{"identifier":"deny-e2e-emit-stale-download-events","description":"Denies the e2e_emit_stale_download_events command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_emit_stale_download_events"]}},"deny-e2e-network-pipelining-probe":{"identifier":"deny-e2e-network-pipelining-probe","description":"Denies the e2e_network_pipelining_probe command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_network_pipelining_probe"]}},"deny-e2e-updater-install-probe":{"identifier":"deny-e2e-updater-install-probe","description":"Denies the e2e_updater_install_probe command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_updater_install_probe"]}},"deny-export-settings":{"identifier":"deny-export-settings","description":"Denies the export_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["export_settings"]}},"deny-get-app-platform":{"identifier":"deny-get-app-platform","description":"Denies the get_app_platform command without any pre-configured scope.","commands":{"allow":[],"deny":["get_app_platform"]}},"deny-get-beta-updater-target":{"identifier":"deny-get-beta-updater-target","description":"Denies the get_beta_updater_target command without any pre-configured scope.","commands":{"allow":[],"deny":["get_beta_updater_target"]}},"deny-get-default-settings":{"identifier":"deny-get-default-settings","description":"Denies the get_default_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_default_settings"]}},"deny-get-distribution-channel":{"identifier":"deny-get-distribution-channel","description":"Denies the get_distribution_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["get_distribution_channel"]}},"deny-get-download-activity":{"identifier":"deny-get-download-activity","description":"Denies the get_download_activity command without any pre-configured scope.","commands":{"allow":[],"deny":["get_download_activity"]}},"deny-get-formats":{"identifier":"deny-get-formats","description":"Denies the get_formats command without any pre-configured scope.","commands":{"allow":[],"deny":["get_formats"]}},"deny-get-queue":{"identifier":"deny-get-queue","description":"Denies the get_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["get_queue"]}},"deny-get-settings":{"identifier":"deny-get-settings","description":"Denies the get_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_settings"]}},"deny-get-stats":{"identifier":"deny-get-stats","description":"Denies the get_stats command without any pre-configured scope.","commands":{"allow":[],"deny":["get_stats"]}},"deny-get-video-info":{"identifier":"deny-get-video-info","description":"Denies the get_video_info command without any pre-configured scope.","commands":{"allow":[],"deny":["get_video_info"]}},"deny-import-settings":{"identifier":"deny-import-settings","description":"Denies the import_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["import_settings"]}},"deny-install-deno":{"identifier":"deny-install-deno","description":"Denies the install_deno command without any pre-configured scope.","commands":{"allow":[],"deny":["install_deno"]}},"deny-is-flatpak":{"identifier":"deny-is-flatpak","description":"Denies the is_flatpak command without any pre-configured scope.","commands":{"allow":[],"deny":["is_flatpak"]}},"deny-is-packaged":{"identifier":"deny-is-packaged","description":"Denies the is_packaged command without any pre-configured scope.","commands":{"allow":[],"deny":["is_packaged"]}},"deny-log-error":{"identifier":"deny-log-error","description":"Denies the log_error command without any pre-configured scope.","commands":{"allow":[],"deny":["log_error"]}},"deny-mark-main-window-ready":{"identifier":"deny-mark-main-window-ready","description":"Denies the mark_main_window_ready command without any pre-configured scope.","commands":{"allow":[],"deny":["mark_main_window_ready"]}},"deny-notify-settings-flushed":{"identifier":"deny-notify-settings-flushed","description":"Denies the notify_settings_flushed command without any pre-configured scope.","commands":{"allow":[],"deny":["notify_settings_flushed"]}},"deny-open-external":{"identifier":"deny-open-external","description":"Denies the open_external command without any pre-configured scope.","commands":{"allow":[],"deny":["open_external"]}},"deny-open-file-location":{"identifier":"deny-open-file-location","description":"Denies the open_file_location command without any pre-configured scope.","commands":{"allow":[],"deny":["open_file_location"]}},"deny-remove-from-queue":{"identifier":"deny-remove-from-queue","description":"Denies the remove_from_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_from_queue"]}},"deny-reorder-queue-item":{"identifier":"deny-reorder-queue-item","description":"Denies the reorder_queue_item command without any pre-configured scope.","commands":{"allow":[],"deny":["reorder_queue_item"]}},"deny-reset-settings":{"identifier":"deny-reset-settings","description":"Denies the reset_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["reset_settings"]}},"deny-reset-stats":{"identifier":"deny-reset-stats","description":"Denies the reset_stats command without any pre-configured scope.","commands":{"allow":[],"deny":["reset_stats"]}},"deny-restart-app":{"identifier":"deny-restart-app","description":"Denies the restart_app command without any pre-configured scope.","commands":{"allow":[],"deny":["restart_app"]}},"deny-retry-queue-item":{"identifier":"deny-retry-queue-item","description":"Denies the retry_queue_item command without any pre-configured scope.","commands":{"allow":[],"deny":["retry_queue_item"]}},"deny-save-settings":{"identifier":"deny-save-settings","description":"Denies the save_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["save_settings"]}},"deny-select-download-location":{"identifier":"deny-select-download-location","description":"Denies the select_download_location command without any pre-configured scope.","commands":{"allow":[],"deny":["select_download_location"]}},"deny-show-notification":{"identifier":"deny-show-notification","description":"Denies the show_notification command without any pre-configured scope.","commands":{"allow":[],"deny":["show_notification"]}},"deny-start-queue":{"identifier":"deny-start-queue","description":"Denies the start_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["start_queue"]}}},"permission_sets":{},"global_scope_schema":null},"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null},"notification":{"default_permission":{"identifier":"default","description":"This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n","permissions":["allow-is-permission-granted","allow-request-permission","allow-notify","allow-register-action-types","allow-register-listener","allow-remove-listener","allow-cancel","allow-get-pending","allow-remove-active","allow-get-active","allow-check-permissions","allow-show","allow-batch","allow-list-channels","allow-delete-channel","allow-create-channel","allow-permission-state"]},"permissions":{"allow-batch":{"identifier":"allow-batch","description":"Enables the batch command without any pre-configured scope.","commands":{"allow":["batch"],"deny":[]}},"allow-cancel":{"identifier":"allow-cancel","description":"Enables the cancel command without any pre-configured scope.","commands":{"allow":["cancel"],"deny":[]}},"allow-check-permissions":{"identifier":"allow-check-permissions","description":"Enables the check_permissions command without any pre-configured scope.","commands":{"allow":["check_permissions"],"deny":[]}},"allow-create-channel":{"identifier":"allow-create-channel","description":"Enables the create_channel command without any pre-configured scope.","commands":{"allow":["create_channel"],"deny":[]}},"allow-delete-channel":{"identifier":"allow-delete-channel","description":"Enables the delete_channel command without any pre-configured scope.","commands":{"allow":["delete_channel"],"deny":[]}},"allow-get-active":{"identifier":"allow-get-active","description":"Enables the get_active command without any pre-configured scope.","commands":{"allow":["get_active"],"deny":[]}},"allow-get-pending":{"identifier":"allow-get-pending","description":"Enables the get_pending command without any pre-configured scope.","commands":{"allow":["get_pending"],"deny":[]}},"allow-is-permission-granted":{"identifier":"allow-is-permission-granted","description":"Enables the is_permission_granted command without any pre-configured scope.","commands":{"allow":["is_permission_granted"],"deny":[]}},"allow-list-channels":{"identifier":"allow-list-channels","description":"Enables the list_channels command without any pre-configured scope.","commands":{"allow":["list_channels"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-permission-state":{"identifier":"allow-permission-state","description":"Enables the permission_state command without any pre-configured scope.","commands":{"allow":["permission_state"],"deny":[]}},"allow-register-action-types":{"identifier":"allow-register-action-types","description":"Enables the register_action_types command without any pre-configured scope.","commands":{"allow":["register_action_types"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-active":{"identifier":"allow-remove-active","description":"Enables the remove_active command without any pre-configured scope.","commands":{"allow":["remove_active"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-request-permission":{"identifier":"allow-request-permission","description":"Enables the request_permission command without any pre-configured scope.","commands":{"allow":["request_permission"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"deny-batch":{"identifier":"deny-batch","description":"Denies the batch command without any pre-configured scope.","commands":{"allow":[],"deny":["batch"]}},"deny-cancel":{"identifier":"deny-cancel","description":"Denies the cancel command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel"]}},"deny-check-permissions":{"identifier":"deny-check-permissions","description":"Denies the check_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_permissions"]}},"deny-create-channel":{"identifier":"deny-create-channel","description":"Denies the create_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["create_channel"]}},"deny-delete-channel":{"identifier":"deny-delete-channel","description":"Denies the delete_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_channel"]}},"deny-get-active":{"identifier":"deny-get-active","description":"Denies the get_active command without any pre-configured scope.","commands":{"allow":[],"deny":["get_active"]}},"deny-get-pending":{"identifier":"deny-get-pending","description":"Denies the get_pending command without any pre-configured scope.","commands":{"allow":[],"deny":["get_pending"]}},"deny-is-permission-granted":{"identifier":"deny-is-permission-granted","description":"Denies the is_permission_granted command without any pre-configured scope.","commands":{"allow":[],"deny":["is_permission_granted"]}},"deny-list-channels":{"identifier":"deny-list-channels","description":"Denies the list_channels command without any pre-configured scope.","commands":{"allow":[],"deny":["list_channels"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-permission-state":{"identifier":"deny-permission-state","description":"Denies the permission_state command without any pre-configured scope.","commands":{"allow":[],"deny":["permission_state"]}},"deny-register-action-types":{"identifier":"deny-register-action-types","description":"Denies the register_action_types command without any pre-configured scope.","commands":{"allow":[],"deny":["register_action_types"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-active":{"identifier":"deny-remove-active","description":"Denies the remove_active command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_active"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-request-permission":{"identifier":"deny-request-permission","description":"Denies the request_permission command without any pre-configured scope.","commands":{"allow":[],"deny":["request_permission"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}}},"permission_sets":{},"global_scope_schema":null},"opener":{"default_permission":{"identifier":"default","description":"This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer","permissions":["allow-open-url","allow-reveal-item-in-dir","allow-default-urls"]},"permissions":{"allow-default-urls":{"identifier":"allow-default-urls","description":"This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.","commands":{"allow":[],"deny":[]},"scope":{"allow":[{"url":"mailto:*"},{"url":"tel:*"},{"url":"http://*"},{"url":"https://*"}]}},"allow-open-path":{"identifier":"allow-open-path","description":"Enables the open_path command without any pre-configured scope.","commands":{"allow":["open_path"],"deny":[]}},"allow-open-url":{"identifier":"allow-open-url","description":"Enables the open_url command without any pre-configured scope.","commands":{"allow":["open_url"],"deny":[]}},"allow-reveal-item-in-dir":{"identifier":"allow-reveal-item-in-dir","description":"Enables the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":["reveal_item_in_dir"],"deny":[]}},"deny-open-path":{"identifier":"deny-open-path","description":"Denies the open_path command without any pre-configured scope.","commands":{"allow":[],"deny":["open_path"]}},"deny-open-url":{"identifier":"deny-open-url","description":"Denies the open_url command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url"]}},"deny-reveal-item-in-dir":{"identifier":"deny-reveal-item-in-dir","description":"Denies the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":[],"deny":["reveal_item_in_dir"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this url with, for example: firefox."},"url":{"description":"A URL that can be opened by the webview when using the Opener APIs.\n\nWildcards can be used following the UNIX glob pattern.\n\nExamples:\n\n- \"https://*\" : allows all HTTPS origin\n\n- \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path\n\n- \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"","type":"string"}},"required":["url"],"type":"object"},{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this path with, for example: xdg-open."},"path":{"description":"A path that can be opened by the webview when using the Opener APIs.\n\nThe pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"}},"required":["path"],"type":"object"}],"definitions":{"Application":{"anyOf":[{"description":"Open in default application.","type":"null"},{"description":"If true, allow open with any application.","type":"boolean"},{"description":"Allow specific application to open with.","type":"string"}],"description":"Opener scope application."}},"description":"Opener scope entry.","title":"OpenerScopeEntry"}},"process":{"default_permission":{"identifier":"default","description":"This permission set configures which\nprocess features are by default exposed.\n\n#### Granted Permissions\n\nThis enables to quit via `allow-exit` and restart via `allow-restart`\nthe application.\n","permissions":["allow-exit","allow-restart"]},"permissions":{"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-restart":{"identifier":"allow-restart","description":"Enables the restart command without any pre-configured scope.","commands":{"allow":["restart"],"deny":[]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-restart":{"identifier":"deny-restart","description":"Denies the restart command without any pre-configured scope.","commands":{"allow":[],"deny":["restart"]}}},"permission_sets":{},"global_scope_schema":null},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file +{"__app-acl__":{"default_permission":null,"permissions":{"allow-add-to-queue":{"identifier":"allow-add-to-queue","description":"Enables the add_to_queue command without any pre-configured scope.","commands":{"allow":["add_to_queue"],"deny":[]}},"allow-cancel-download":{"identifier":"allow-cancel-download","description":"Enables the cancel_download command without any pre-configured scope.","commands":{"allow":["cancel_download"],"deny":[]}},"allow-cancel-formats":{"identifier":"allow-cancel-formats","description":"Enables the cancel_formats command without any pre-configured scope.","commands":{"allow":["cancel_formats"],"deny":[]}},"allow-cancel-queue":{"identifier":"allow-cancel-queue","description":"Enables the cancel_queue command without any pre-configured scope.","commands":{"allow":["cancel_queue"],"deny":[]}},"allow-cancel-video-info":{"identifier":"allow-cancel-video-info","description":"Enables the cancel_video_info command without any pre-configured scope.","commands":{"allow":["cancel_video_info"],"deny":[]}},"allow-check-deno-installed":{"identifier":"allow-check-deno-installed","description":"Enables the check_deno_installed command without any pre-configured scope.","commands":{"allow":["check_deno_installed"],"deny":[]}},"allow-clear-download-activity":{"identifier":"allow-clear-download-activity","description":"Enables the clear_download_activity command without any pre-configured scope.","commands":{"allow":["clear_download_activity"],"deny":[]}},"allow-clear-finished-queue":{"identifier":"allow-clear-finished-queue","description":"Enables the clear_finished_queue command without any pre-configured scope.","commands":{"allow":["clear_finished_queue"],"deny":[]}},"allow-clear-queue":{"identifier":"allow-clear-queue","description":"Enables the clear_queue command without any pre-configured scope.","commands":{"allow":["clear_queue"],"deny":[]}},"allow-detect-gpu":{"identifier":"allow-detect-gpu","description":"Enables the detect_gpu command without any pre-configured scope.","commands":{"allow":["detect_gpu"],"deny":[]}},"allow-download-video":{"identifier":"allow-download-video","description":"Enables the download_video command without any pre-configured scope.","commands":{"allow":["download_video"],"deny":[]}},"allow-e2e-cancel-close-request":{"identifier":"allow-e2e-cancel-close-request","description":"Enables the e2e_cancel_close_request command without any pre-configured scope.","commands":{"allow":["e2e_cancel_close_request"],"deny":[]}},"allow-e2e-emit-stale-download-events":{"identifier":"allow-e2e-emit-stale-download-events","description":"Enables the e2e_emit_stale_download_events command without any pre-configured scope.","commands":{"allow":["e2e_emit_stale_download_events"],"deny":[]}},"allow-e2e-network-pipelining-probe":{"identifier":"allow-e2e-network-pipelining-probe","description":"Enables the e2e_network_pipelining_probe command without any pre-configured scope.","commands":{"allow":["e2e_network_pipelining_probe"],"deny":[]}},"allow-e2e-updater-install-probe":{"identifier":"allow-e2e-updater-install-probe","description":"Enables the e2e_updater_install_probe command without any pre-configured scope.","commands":{"allow":["e2e_updater_install_probe"],"deny":[]}},"allow-export-settings":{"identifier":"allow-export-settings","description":"Enables the export_settings command without any pre-configured scope.","commands":{"allow":["export_settings"],"deny":[]}},"allow-get-app-platform":{"identifier":"allow-get-app-platform","description":"Enables the get_app_platform command without any pre-configured scope.","commands":{"allow":["get_app_platform"],"deny":[]}},"allow-get-beta-updater-target":{"identifier":"allow-get-beta-updater-target","description":"Enables the get_beta_updater_target command without any pre-configured scope.","commands":{"allow":["get_beta_updater_target"],"deny":[]}},"allow-get-compact-updater-target":{"identifier":"allow-get-compact-updater-target","description":"Enables the get_compact_updater_target command without any pre-configured scope.","commands":{"allow":["get_compact_updater_target"],"deny":[]}},"allow-get-default-settings":{"identifier":"allow-get-default-settings","description":"Enables the get_default_settings command without any pre-configured scope.","commands":{"allow":["get_default_settings"],"deny":[]}},"allow-get-distribution-channel":{"identifier":"allow-get-distribution-channel","description":"Enables the get_distribution_channel command without any pre-configured scope.","commands":{"allow":["get_distribution_channel"],"deny":[]}},"allow-get-download-activity":{"identifier":"allow-get-download-activity","description":"Enables the get_download_activity command without any pre-configured scope.","commands":{"allow":["get_download_activity"],"deny":[]}},"allow-get-formats":{"identifier":"allow-get-formats","description":"Enables the get_formats command without any pre-configured scope.","commands":{"allow":["get_formats"],"deny":[]}},"allow-get-queue":{"identifier":"allow-get-queue","description":"Enables the get_queue command without any pre-configured scope.","commands":{"allow":["get_queue"],"deny":[]}},"allow-get-settings":{"identifier":"allow-get-settings","description":"Enables the get_settings command without any pre-configured scope.","commands":{"allow":["get_settings"],"deny":[]}},"allow-get-stats":{"identifier":"allow-get-stats","description":"Enables the get_stats command without any pre-configured scope.","commands":{"allow":["get_stats"],"deny":[]}},"allow-get-video-info":{"identifier":"allow-get-video-info","description":"Enables the get_video_info command without any pre-configured scope.","commands":{"allow":["get_video_info"],"deny":[]}},"allow-import-settings":{"identifier":"allow-import-settings","description":"Enables the import_settings command without any pre-configured scope.","commands":{"allow":["import_settings"],"deny":[]}},"allow-install-deno":{"identifier":"allow-install-deno","description":"Enables the install_deno command without any pre-configured scope.","commands":{"allow":["install_deno"],"deny":[]}},"allow-is-flatpak":{"identifier":"allow-is-flatpak","description":"Enables the is_flatpak command without any pre-configured scope.","commands":{"allow":["is_flatpak"],"deny":[]}},"allow-is-packaged":{"identifier":"allow-is-packaged","description":"Enables the is_packaged command without any pre-configured scope.","commands":{"allow":["is_packaged"],"deny":[]}},"allow-log-error":{"identifier":"allow-log-error","description":"Enables the log_error command without any pre-configured scope.","commands":{"allow":["log_error"],"deny":[]}},"allow-mark-main-window-ready":{"identifier":"allow-mark-main-window-ready","description":"Enables the mark_main_window_ready command without any pre-configured scope.","commands":{"allow":["mark_main_window_ready"],"deny":[]}},"allow-notify-settings-flushed":{"identifier":"allow-notify-settings-flushed","description":"Enables the notify_settings_flushed command without any pre-configured scope.","commands":{"allow":["notify_settings_flushed"],"deny":[]}},"allow-open-external":{"identifier":"allow-open-external","description":"Enables the open_external command without any pre-configured scope.","commands":{"allow":["open_external"],"deny":[]}},"allow-open-file-location":{"identifier":"allow-open-file-location","description":"Enables the open_file_location command without any pre-configured scope.","commands":{"allow":["open_file_location"],"deny":[]}},"allow-remove-from-queue":{"identifier":"allow-remove-from-queue","description":"Enables the remove_from_queue command without any pre-configured scope.","commands":{"allow":["remove_from_queue"],"deny":[]}},"allow-reorder-queue-item":{"identifier":"allow-reorder-queue-item","description":"Enables the reorder_queue_item command without any pre-configured scope.","commands":{"allow":["reorder_queue_item"],"deny":[]}},"allow-reset-settings":{"identifier":"allow-reset-settings","description":"Enables the reset_settings command without any pre-configured scope.","commands":{"allow":["reset_settings"],"deny":[]}},"allow-reset-stats":{"identifier":"allow-reset-stats","description":"Enables the reset_stats command without any pre-configured scope.","commands":{"allow":["reset_stats"],"deny":[]}},"allow-restart-app":{"identifier":"allow-restart-app","description":"Enables the restart_app command without any pre-configured scope.","commands":{"allow":["restart_app"],"deny":[]}},"allow-retry-queue-item":{"identifier":"allow-retry-queue-item","description":"Enables the retry_queue_item command without any pre-configured scope.","commands":{"allow":["retry_queue_item"],"deny":[]}},"allow-save-settings":{"identifier":"allow-save-settings","description":"Enables the save_settings command without any pre-configured scope.","commands":{"allow":["save_settings"],"deny":[]}},"allow-select-download-location":{"identifier":"allow-select-download-location","description":"Enables the select_download_location command without any pre-configured scope.","commands":{"allow":["select_download_location"],"deny":[]}},"allow-show-notification":{"identifier":"allow-show-notification","description":"Enables the show_notification command without any pre-configured scope.","commands":{"allow":["show_notification"],"deny":[]}},"allow-start-queue":{"identifier":"allow-start-queue","description":"Enables the start_queue command without any pre-configured scope.","commands":{"allow":["start_queue"],"deny":[]}},"deny-add-to-queue":{"identifier":"deny-add-to-queue","description":"Denies the add_to_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["add_to_queue"]}},"deny-cancel-download":{"identifier":"deny-cancel-download","description":"Denies the cancel_download command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_download"]}},"deny-cancel-formats":{"identifier":"deny-cancel-formats","description":"Denies the cancel_formats command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_formats"]}},"deny-cancel-queue":{"identifier":"deny-cancel-queue","description":"Denies the cancel_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_queue"]}},"deny-cancel-video-info":{"identifier":"deny-cancel-video-info","description":"Denies the cancel_video_info command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_video_info"]}},"deny-check-deno-installed":{"identifier":"deny-check-deno-installed","description":"Denies the check_deno_installed command without any pre-configured scope.","commands":{"allow":[],"deny":["check_deno_installed"]}},"deny-clear-download-activity":{"identifier":"deny-clear-download-activity","description":"Denies the clear_download_activity command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_download_activity"]}},"deny-clear-finished-queue":{"identifier":"deny-clear-finished-queue","description":"Denies the clear_finished_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_finished_queue"]}},"deny-clear-queue":{"identifier":"deny-clear-queue","description":"Denies the clear_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_queue"]}},"deny-detect-gpu":{"identifier":"deny-detect-gpu","description":"Denies the detect_gpu command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_gpu"]}},"deny-download-video":{"identifier":"deny-download-video","description":"Denies the download_video command without any pre-configured scope.","commands":{"allow":[],"deny":["download_video"]}},"deny-e2e-cancel-close-request":{"identifier":"deny-e2e-cancel-close-request","description":"Denies the e2e_cancel_close_request command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_cancel_close_request"]}},"deny-e2e-emit-stale-download-events":{"identifier":"deny-e2e-emit-stale-download-events","description":"Denies the e2e_emit_stale_download_events command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_emit_stale_download_events"]}},"deny-e2e-network-pipelining-probe":{"identifier":"deny-e2e-network-pipelining-probe","description":"Denies the e2e_network_pipelining_probe command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_network_pipelining_probe"]}},"deny-e2e-updater-install-probe":{"identifier":"deny-e2e-updater-install-probe","description":"Denies the e2e_updater_install_probe command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_updater_install_probe"]}},"deny-export-settings":{"identifier":"deny-export-settings","description":"Denies the export_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["export_settings"]}},"deny-get-app-platform":{"identifier":"deny-get-app-platform","description":"Denies the get_app_platform command without any pre-configured scope.","commands":{"allow":[],"deny":["get_app_platform"]}},"deny-get-beta-updater-target":{"identifier":"deny-get-beta-updater-target","description":"Denies the get_beta_updater_target command without any pre-configured scope.","commands":{"allow":[],"deny":["get_beta_updater_target"]}},"deny-get-compact-updater-target":{"identifier":"deny-get-compact-updater-target","description":"Denies the get_compact_updater_target command without any pre-configured scope.","commands":{"allow":[],"deny":["get_compact_updater_target"]}},"deny-get-default-settings":{"identifier":"deny-get-default-settings","description":"Denies the get_default_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_default_settings"]}},"deny-get-distribution-channel":{"identifier":"deny-get-distribution-channel","description":"Denies the get_distribution_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["get_distribution_channel"]}},"deny-get-download-activity":{"identifier":"deny-get-download-activity","description":"Denies the get_download_activity command without any pre-configured scope.","commands":{"allow":[],"deny":["get_download_activity"]}},"deny-get-formats":{"identifier":"deny-get-formats","description":"Denies the get_formats command without any pre-configured scope.","commands":{"allow":[],"deny":["get_formats"]}},"deny-get-queue":{"identifier":"deny-get-queue","description":"Denies the get_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["get_queue"]}},"deny-get-settings":{"identifier":"deny-get-settings","description":"Denies the get_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_settings"]}},"deny-get-stats":{"identifier":"deny-get-stats","description":"Denies the get_stats command without any pre-configured scope.","commands":{"allow":[],"deny":["get_stats"]}},"deny-get-video-info":{"identifier":"deny-get-video-info","description":"Denies the get_video_info command without any pre-configured scope.","commands":{"allow":[],"deny":["get_video_info"]}},"deny-import-settings":{"identifier":"deny-import-settings","description":"Denies the import_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["import_settings"]}},"deny-install-deno":{"identifier":"deny-install-deno","description":"Denies the install_deno command without any pre-configured scope.","commands":{"allow":[],"deny":["install_deno"]}},"deny-is-flatpak":{"identifier":"deny-is-flatpak","description":"Denies the is_flatpak command without any pre-configured scope.","commands":{"allow":[],"deny":["is_flatpak"]}},"deny-is-packaged":{"identifier":"deny-is-packaged","description":"Denies the is_packaged command without any pre-configured scope.","commands":{"allow":[],"deny":["is_packaged"]}},"deny-log-error":{"identifier":"deny-log-error","description":"Denies the log_error command without any pre-configured scope.","commands":{"allow":[],"deny":["log_error"]}},"deny-mark-main-window-ready":{"identifier":"deny-mark-main-window-ready","description":"Denies the mark_main_window_ready command without any pre-configured scope.","commands":{"allow":[],"deny":["mark_main_window_ready"]}},"deny-notify-settings-flushed":{"identifier":"deny-notify-settings-flushed","description":"Denies the notify_settings_flushed command without any pre-configured scope.","commands":{"allow":[],"deny":["notify_settings_flushed"]}},"deny-open-external":{"identifier":"deny-open-external","description":"Denies the open_external command without any pre-configured scope.","commands":{"allow":[],"deny":["open_external"]}},"deny-open-file-location":{"identifier":"deny-open-file-location","description":"Denies the open_file_location command without any pre-configured scope.","commands":{"allow":[],"deny":["open_file_location"]}},"deny-remove-from-queue":{"identifier":"deny-remove-from-queue","description":"Denies the remove_from_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_from_queue"]}},"deny-reorder-queue-item":{"identifier":"deny-reorder-queue-item","description":"Denies the reorder_queue_item command without any pre-configured scope.","commands":{"allow":[],"deny":["reorder_queue_item"]}},"deny-reset-settings":{"identifier":"deny-reset-settings","description":"Denies the reset_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["reset_settings"]}},"deny-reset-stats":{"identifier":"deny-reset-stats","description":"Denies the reset_stats command without any pre-configured scope.","commands":{"allow":[],"deny":["reset_stats"]}},"deny-restart-app":{"identifier":"deny-restart-app","description":"Denies the restart_app command without any pre-configured scope.","commands":{"allow":[],"deny":["restart_app"]}},"deny-retry-queue-item":{"identifier":"deny-retry-queue-item","description":"Denies the retry_queue_item command without any pre-configured scope.","commands":{"allow":[],"deny":["retry_queue_item"]}},"deny-save-settings":{"identifier":"deny-save-settings","description":"Denies the save_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["save_settings"]}},"deny-select-download-location":{"identifier":"deny-select-download-location","description":"Denies the select_download_location command without any pre-configured scope.","commands":{"allow":[],"deny":["select_download_location"]}},"deny-show-notification":{"identifier":"deny-show-notification","description":"Denies the show_notification command without any pre-configured scope.","commands":{"allow":[],"deny":["show_notification"]}},"deny-start-queue":{"identifier":"deny-start-queue","description":"Denies the start_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["start_queue"]}}},"permission_sets":{},"global_scope_schema":null},"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null},"notification":{"default_permission":{"identifier":"default","description":"This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n","permissions":["allow-is-permission-granted","allow-request-permission","allow-notify","allow-register-action-types","allow-register-listener","allow-remove-listener","allow-cancel","allow-get-pending","allow-remove-active","allow-get-active","allow-check-permissions","allow-show","allow-batch","allow-list-channels","allow-delete-channel","allow-create-channel","allow-permission-state"]},"permissions":{"allow-batch":{"identifier":"allow-batch","description":"Enables the batch command without any pre-configured scope.","commands":{"allow":["batch"],"deny":[]}},"allow-cancel":{"identifier":"allow-cancel","description":"Enables the cancel command without any pre-configured scope.","commands":{"allow":["cancel"],"deny":[]}},"allow-check-permissions":{"identifier":"allow-check-permissions","description":"Enables the check_permissions command without any pre-configured scope.","commands":{"allow":["check_permissions"],"deny":[]}},"allow-create-channel":{"identifier":"allow-create-channel","description":"Enables the create_channel command without any pre-configured scope.","commands":{"allow":["create_channel"],"deny":[]}},"allow-delete-channel":{"identifier":"allow-delete-channel","description":"Enables the delete_channel command without any pre-configured scope.","commands":{"allow":["delete_channel"],"deny":[]}},"allow-get-active":{"identifier":"allow-get-active","description":"Enables the get_active command without any pre-configured scope.","commands":{"allow":["get_active"],"deny":[]}},"allow-get-pending":{"identifier":"allow-get-pending","description":"Enables the get_pending command without any pre-configured scope.","commands":{"allow":["get_pending"],"deny":[]}},"allow-is-permission-granted":{"identifier":"allow-is-permission-granted","description":"Enables the is_permission_granted command without any pre-configured scope.","commands":{"allow":["is_permission_granted"],"deny":[]}},"allow-list-channels":{"identifier":"allow-list-channels","description":"Enables the list_channels command without any pre-configured scope.","commands":{"allow":["list_channels"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-permission-state":{"identifier":"allow-permission-state","description":"Enables the permission_state command without any pre-configured scope.","commands":{"allow":["permission_state"],"deny":[]}},"allow-register-action-types":{"identifier":"allow-register-action-types","description":"Enables the register_action_types command without any pre-configured scope.","commands":{"allow":["register_action_types"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-active":{"identifier":"allow-remove-active","description":"Enables the remove_active command without any pre-configured scope.","commands":{"allow":["remove_active"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-request-permission":{"identifier":"allow-request-permission","description":"Enables the request_permission command without any pre-configured scope.","commands":{"allow":["request_permission"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"deny-batch":{"identifier":"deny-batch","description":"Denies the batch command without any pre-configured scope.","commands":{"allow":[],"deny":["batch"]}},"deny-cancel":{"identifier":"deny-cancel","description":"Denies the cancel command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel"]}},"deny-check-permissions":{"identifier":"deny-check-permissions","description":"Denies the check_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_permissions"]}},"deny-create-channel":{"identifier":"deny-create-channel","description":"Denies the create_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["create_channel"]}},"deny-delete-channel":{"identifier":"deny-delete-channel","description":"Denies the delete_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_channel"]}},"deny-get-active":{"identifier":"deny-get-active","description":"Denies the get_active command without any pre-configured scope.","commands":{"allow":[],"deny":["get_active"]}},"deny-get-pending":{"identifier":"deny-get-pending","description":"Denies the get_pending command without any pre-configured scope.","commands":{"allow":[],"deny":["get_pending"]}},"deny-is-permission-granted":{"identifier":"deny-is-permission-granted","description":"Denies the is_permission_granted command without any pre-configured scope.","commands":{"allow":[],"deny":["is_permission_granted"]}},"deny-list-channels":{"identifier":"deny-list-channels","description":"Denies the list_channels command without any pre-configured scope.","commands":{"allow":[],"deny":["list_channels"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-permission-state":{"identifier":"deny-permission-state","description":"Denies the permission_state command without any pre-configured scope.","commands":{"allow":[],"deny":["permission_state"]}},"deny-register-action-types":{"identifier":"deny-register-action-types","description":"Denies the register_action_types command without any pre-configured scope.","commands":{"allow":[],"deny":["register_action_types"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-active":{"identifier":"deny-remove-active","description":"Denies the remove_active command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_active"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-request-permission":{"identifier":"deny-request-permission","description":"Denies the request_permission command without any pre-configured scope.","commands":{"allow":[],"deny":["request_permission"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}}},"permission_sets":{},"global_scope_schema":null},"opener":{"default_permission":{"identifier":"default","description":"This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer","permissions":["allow-open-url","allow-reveal-item-in-dir","allow-default-urls"]},"permissions":{"allow-default-urls":{"identifier":"allow-default-urls","description":"This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.","commands":{"allow":[],"deny":[]},"scope":{"allow":[{"url":"mailto:*"},{"url":"tel:*"},{"url":"http://*"},{"url":"https://*"}]}},"allow-open-path":{"identifier":"allow-open-path","description":"Enables the open_path command without any pre-configured scope.","commands":{"allow":["open_path"],"deny":[]}},"allow-open-url":{"identifier":"allow-open-url","description":"Enables the open_url command without any pre-configured scope.","commands":{"allow":["open_url"],"deny":[]}},"allow-reveal-item-in-dir":{"identifier":"allow-reveal-item-in-dir","description":"Enables the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":["reveal_item_in_dir"],"deny":[]}},"deny-open-path":{"identifier":"deny-open-path","description":"Denies the open_path command without any pre-configured scope.","commands":{"allow":[],"deny":["open_path"]}},"deny-open-url":{"identifier":"deny-open-url","description":"Denies the open_url command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url"]}},"deny-reveal-item-in-dir":{"identifier":"deny-reveal-item-in-dir","description":"Denies the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":[],"deny":["reveal_item_in_dir"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this url with, for example: firefox."},"url":{"description":"A URL that can be opened by the webview when using the Opener APIs.\n\nWildcards can be used following the UNIX glob pattern.\n\nExamples:\n\n- \"https://*\" : allows all HTTPS origin\n\n- \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path\n\n- \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"","type":"string"}},"required":["url"],"type":"object"},{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this path with, for example: xdg-open."},"path":{"description":"A path that can be opened by the webview when using the Opener APIs.\n\nThe pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"}},"required":["path"],"type":"object"}],"definitions":{"Application":{"anyOf":[{"description":"Open in default application.","type":"null"},{"description":"If true, allow open with any application.","type":"boolean"},{"description":"Allow specific application to open with.","type":"string"}],"description":"Opener scope application."}},"description":"Opener scope entry.","title":"OpenerScopeEntry"}},"process":{"default_permission":{"identifier":"default","description":"This permission set configures which\nprocess features are by default exposed.\n\n#### Granted Permissions\n\nThis enables to quit via `allow-exit` and restart via `allow-restart`\nthe application.\n","permissions":["allow-exit","allow-restart"]},"permissions":{"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-restart":{"identifier":"allow-restart","description":"Enables the restart command without any pre-configured scope.","commands":{"allow":["restart"],"deny":[]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-restart":{"identifier":"deny-restart","description":"Denies the restart command without any pre-configured scope.","commands":{"allow":[],"deny":["restart"]}}},"permission_sets":{},"global_scope_schema":null},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file diff --git a/src-tauri/gen/schemas/capabilities.json b/src-tauri/gen/schemas/capabilities.json index 3aa0e4be..03a64d53 100644 --- a/src-tauri/gen/schemas/capabilities.json +++ b/src-tauri/gen/schemas/capabilities.json @@ -1 +1 @@ -{"default":{"identifier":"default","description":"Permissions for the ROSI main window","local":true,"windows":["main"],"permissions":["core:app:allow-version","core:event:allow-listen","core:event:allow-unlisten","core:window:allow-set-theme","updater:allow-check","updater:allow-download","updater:allow-install","allow-get-settings","allow-get-default-settings","allow-save-settings","allow-reset-settings","allow-export-settings","allow-import-settings","allow-get-stats","allow-reset-stats","allow-get-download-activity","allow-clear-download-activity","allow-get-formats","allow-cancel-formats","allow-get-video-info","allow-cancel-video-info","allow-download-video","allow-cancel-download","allow-add-to-queue","allow-remove-from-queue","allow-retry-queue-item","allow-reorder-queue-item","allow-clear-queue","allow-clear-finished-queue","allow-get-queue","allow-start-queue","allow-cancel-queue","allow-select-download-location","allow-open-external","allow-open-file-location","allow-show-notification","allow-check-deno-installed","allow-install-deno","allow-detect-gpu","allow-is-packaged","allow-is-flatpak","allow-get-app-platform","allow-get-distribution-channel","allow-get-beta-updater-target","allow-restart-app","allow-log-error","allow-notify-settings-flushed","allow-mark-main-window-ready"]},"splash":{"identifier":"splash","description":"Minimal permissions for the packaged startup splash window","local":true,"windows":["splash"],"permissions":["core:app:allow-version"]}} \ No newline at end of file +{"default":{"identifier":"default","description":"Permissions for the ROSI main window","local":true,"windows":["main"],"permissions":["core:app:allow-version","core:event:allow-listen","core:event:allow-unlisten","core:window:allow-set-theme","updater:allow-check","updater:allow-download","updater:allow-install","allow-get-settings","allow-get-default-settings","allow-save-settings","allow-reset-settings","allow-export-settings","allow-import-settings","allow-get-stats","allow-reset-stats","allow-get-download-activity","allow-clear-download-activity","allow-get-formats","allow-cancel-formats","allow-get-video-info","allow-cancel-video-info","allow-download-video","allow-cancel-download","allow-add-to-queue","allow-remove-from-queue","allow-retry-queue-item","allow-reorder-queue-item","allow-clear-queue","allow-clear-finished-queue","allow-get-queue","allow-start-queue","allow-cancel-queue","allow-select-download-location","allow-open-external","allow-open-file-location","allow-show-notification","allow-check-deno-installed","allow-install-deno","allow-detect-gpu","allow-is-packaged","allow-is-flatpak","allow-get-app-platform","allow-get-distribution-channel","allow-get-beta-updater-target","allow-get-compact-updater-target","allow-restart-app","allow-log-error","allow-notify-settings-flushed","allow-mark-main-window-ready"]},"splash":{"identifier":"splash","description":"Minimal permissions for the packaged startup splash window","local":true,"windows":["splash"],"permissions":["core:app:allow-version"]}} \ No newline at end of file diff --git a/src-tauri/gen/schemas/desktop-schema.json b/src-tauri/gen/schemas/desktop-schema.json index 7a0a3b48..c8e4edfd 100644 --- a/src-tauri/gen/schemas/desktop-schema.json +++ b/src-tauri/gen/schemas/desktop-schema.json @@ -452,6 +452,12 @@ "const": "allow-get-beta-updater-target", "markdownDescription": "Enables the get_beta_updater_target command without any pre-configured scope." }, + { + "description": "Enables the get_compact_updater_target command without any pre-configured scope.", + "type": "string", + "const": "allow-get-compact-updater-target", + "markdownDescription": "Enables the get_compact_updater_target command without any pre-configured scope." + }, { "description": "Enables the get_default_settings command without any pre-configured scope.", "type": "string", @@ -722,6 +728,12 @@ "const": "deny-get-beta-updater-target", "markdownDescription": "Denies the get_beta_updater_target command without any pre-configured scope." }, + { + "description": "Denies the get_compact_updater_target command without any pre-configured scope.", + "type": "string", + "const": "deny-get-compact-updater-target", + "markdownDescription": "Denies the get_compact_updater_target command without any pre-configured scope." + }, { "description": "Denies the get_default_settings command without any pre-configured scope.", "type": "string", diff --git a/src-tauri/gen/schemas/macOS-schema.json b/src-tauri/gen/schemas/macOS-schema.json index 7a0a3b48..c8e4edfd 100644 --- a/src-tauri/gen/schemas/macOS-schema.json +++ b/src-tauri/gen/schemas/macOS-schema.json @@ -452,6 +452,12 @@ "const": "allow-get-beta-updater-target", "markdownDescription": "Enables the get_beta_updater_target command without any pre-configured scope." }, + { + "description": "Enables the get_compact_updater_target command without any pre-configured scope.", + "type": "string", + "const": "allow-get-compact-updater-target", + "markdownDescription": "Enables the get_compact_updater_target command without any pre-configured scope." + }, { "description": "Enables the get_default_settings command without any pre-configured scope.", "type": "string", @@ -722,6 +728,12 @@ "const": "deny-get-beta-updater-target", "markdownDescription": "Denies the get_beta_updater_target command without any pre-configured scope." }, + { + "description": "Denies the get_compact_updater_target command without any pre-configured scope.", + "type": "string", + "const": "deny-get-compact-updater-target", + "markdownDescription": "Denies the get_compact_updater_target command without any pre-configured scope." + }, { "description": "Denies the get_default_settings command without any pre-configured scope.", "type": "string", diff --git a/src-tauri/permissions/autogenerated/get_compact_updater_target.toml b/src-tauri/permissions/autogenerated/get_compact_updater_target.toml new file mode 100644 index 00000000..62cafab1 --- /dev/null +++ b/src-tauri/permissions/autogenerated/get_compact_updater_target.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-get-compact-updater-target" +description = "Enables the get_compact_updater_target command without any pre-configured scope." +commands.allow = ["get_compact_updater_target"] + +[[permission]] +identifier = "deny-get-compact-updater-target" +description = "Denies the get_compact_updater_target command without any pre-configured scope." +commands.deny = ["get_compact_updater_target"] diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index f429f342..09ef254d 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -160,6 +160,7 @@ macro_rules! generate_app_handler { platform::get_app_platform, platform::get_distribution_channel, platform::get_beta_updater_target, + platform::get_compact_updater_target, window::restart_app, logging::log_error, window::notify_settings_flushed, diff --git a/src-tauri/src/platform.rs b/src-tauri/src/platform.rs index 1256cc2a..bc0bbfe8 100644 --- a/src-tauri/src/platform.rs +++ b/src-tauri/src/platform.rs @@ -61,6 +61,30 @@ pub fn get_beta_updater_target() -> String { } } +/// Packaged macOS apps update from per-arch `.app.tar.zst` archives +/// (`scripts/pack-macos-updater-zst.js`). `None` everywhere else, so those +/// builds keep the default or beta target. +#[tauri::command] +pub fn get_compact_updater_target(beta: bool) -> Option { + use tauri::utils::config::BundleType; + + if !cfg!(target_os = "macos") + || !matches!( + tauri::utils::platform::bundle_type(), + Some(BundleType::App | BundleType::Dmg) + ) + { + return None; + } + // Compile-time arch: a Rosetta process asks for the x86_64 bundle. + let arch = match std::env::consts::ARCH { + arch @ ("aarch64" | "x86_64") => arch, + _ => return None, + }; + let channel = if beta { "-beta" } else { "" }; + Some(format!("darwin{channel}-{arch}-app-zst")) +} + /// The AppImage GTK hook (linuxdeploy-plugin-gtk, Tauri CLI < 2.12) exports /// `GDK_BACKEND=x11` unconditionally. On a Wayland session without XWayland /// there is no X display, so GTK init panics before any window appears. Fall diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index e7226f20..75eb5f90 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "ROSI", - "version": "5.0.2", + "version": "5.1.0-beta.1", "identifier": "run.rosie.rosi", "build": { "beforeDevCommand": "npm run dev", @@ -81,7 +81,7 @@ "entitlements": "entitlements.plist", "hardenedRuntime": true, "minimumSystemVersion": "15.0", - "bundleVersion": "5.0.29999", + "bundleVersion": "5.1.3001", "dmg": { "background": "dmg/background.png", "windowSize": { diff --git a/src-tauri/vendor/tauri-plugin-updater/Cargo.lock b/src-tauri/vendor/tauri-plugin-updater/Cargo.lock index c9858be9..a5d50129 100644 --- a/src-tauri/vendor/tauri-plugin-updater/Cargo.lock +++ b/src-tauri/vendor/tauri-plugin-updater/Cargo.lock @@ -253,6 +253,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -1668,6 +1670,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.106" @@ -3506,6 +3518,7 @@ dependencies = [ "url", "windows-sys 0.61.2", "zip", + "zstd", ] [[package]] @@ -4784,3 +4797,31 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/src-tauri/vendor/tauri-plugin-updater/Cargo.toml b/src-tauri/vendor/tauri-plugin-updater/Cargo.toml index d01b419c..066016be 100644 --- a/src-tauri/vendor/tauri-plugin-updater/Cargo.toml +++ b/src-tauri/vendor/tauri-plugin-updater/Cargo.toml @@ -187,6 +187,10 @@ features = ["full"] [target.'cfg(target_os = "macos")'.dependencies.tar] version = "0.4" +[target.'cfg(target_os = "macos")'.dependencies.zstd] +version = "0.13.3" +default-features = false + [target.'cfg(target_os = "windows")'.dependencies.windows-sys] version = "0.61.0" features = [ diff --git a/src-tauri/vendor/tauri-plugin-updater/PATCHES.md b/src-tauri/vendor/tauri-plugin-updater/PATCHES.md index e6e81d09..f9ebfedb 100644 --- a/src-tauri/vendor/tauri-plugin-updater/PATCHES.md +++ b/src-tauri/vendor/tauri-plugin-updater/PATCHES.md @@ -24,14 +24,15 @@ reason (`.github/dependabot.yml`). | Upstream git sha1 | `44293a5722efcaf27060504e63b17aeba721b40f` (`.cargo_vcs_info.json`, path `plugins/updater`) | | Newest stable 2.x seen | `2.14.0` (checked 2026-10-17 via crates.io; `2.13.3` and `2.13.2` are older) | -`Cargo.toml`, `Cargo.toml.orig`, `README.md`, `build.rs`, `permissions/`, +`Cargo.toml.orig`, `README.md`, `build.rs`, `permissions/`, `CHANGELOG.md`, `SECURITY.md`, `api-iife.js`, the `LICENSE*` files and `.cargo_vcs_info.json` are byte-identical to upstream 2.14.0. Upstream 2.14.0 excludes `guest-js/`, `package.json`, `rollup.config.js`, `tsconfig.json` and `banner.png` from the crate, so they are not vendored any more. -All ROSI changes are under `src/`. `ROSI.patch` is the complete diff -(upstream `src/` to vendored `src/`), excluding `target/`, `Cargo.lock`, -`.cargo-ok`, `.cargo_vcs_info.json`, `PATCHES.md` and `ROSI.patch`. +ROSI changes are under `src/`, plus one dependency in `Cargo.toml`. +`ROSI.patch` is the complete diff (upstream crate to vendored crate), +excluding `target/`, `Cargo.lock`, `.cargo-ok`, `.cargo_vcs_info.json`, +`PATCHES.md` and `ROSI.patch`. Apply the patch to a pristine copy with: @@ -45,10 +46,11 @@ patch -p1 -d -i ROSI.patch | --- | --- | --- | | `src/install_safety.rs` | new | Shared install checks. macOS: bundle identity and completeness, a sibling backup path, a process-wide install lock, and a privileged replacement script whose arguments are shell-quoted. Windows: `ShellExecuteW` result check (values `<= 32` are failures). Archives: confined tar member, parent-directory and symlink-target checks, so an update cannot write outside the extract root. Linux: helper binaries (`pkexec`, `sudo`, `zenity`, `kdialog`, `sh`) are resolved only from fixed root-owned system directories and never through `PATH`; the privileged environment is an allowlist (session display, D-Bus, locale vars) and sets `PATH` to fixed system directories. Also cross-device move and copy fallback. Its `#[cfg(test)]` module runs with `cargo test`. | | `src/appimage_install.rs` | new | Validates an AppImage before it replaces the live file: ELF class, machine and entrypoint checks, squashfs and ISO9660 structure for Type 2 images. Stages in a private work directory, moves the old image aside, then renames the stage into place, restoring the old image if that fails. Used on Linux and BSD only. | -| `src/appimage_archive.rs` | new | Bounded `.tar.gz` extraction for AppImage updates: entry-count limit, total decompressed-byte limit, exactly one regular `.AppImage` member, no links, truncation detection. Used on Linux and BSD only. | +| `src/appimage_archive.rs` | new | Bounded `.tar.gz` extraction for AppImage updates: entry-count limit, total decompressed-byte limit, exactly one regular `.AppImage` member, no links, truncation detection. Used on Linux and BSD. Its `BoundedArchiveReader` (decompressed-byte cap, tar end-block and trailing-data check) also bounds macOS app extraction. | | `src/updater.rs` | modified | See details below. | | `src/lib.rs` | modified | Adds `mod install_safety;`. Plumbs the fallible `on_before_exit` hook and a new `on_windows_installer_launched` hook into the updater state. Windows cleanup now runs from the launched hook, not before launch. | | `src/error.rs` | modified | Adds `Error::BeforeExit(String)` so a failed app-state flush aborts installation and keeps the update retryable. | +| `Cargo.toml` | modified | Adds the macOS-only `zstd` dependency (`default-features = false`) for per-arch `.app.tar.zst` updates. | | `src/commands.rs` | modified | `allow_downgrades` is accepted but ignored (`let _ = allow_downgrades;`). ROSI decision: the flag cannot select an older release, so the default newer-only comparator always applies. Upstream honours the flag by replacing `version_comparator`. The config-level `allowDowngrades` (`Config::allow_downgrades`, parsed from `tauri.conf`) is not applied either: `lib.rs` does not install the downgrade comparator from it. | ### `src/updater.rs` details @@ -68,6 +70,12 @@ patch -p1 -d -i ROSI.patch after the identity check passes. `restore_macos_live_bundle` and `recover_macos_live_bundle` roll back a partial swap. When the user-owned path is not writable, the privileged AppleScript path runs with quoted arguments. +- macOS archives: `extract_macos_app_archive` picks gzip (Tauri `.app.tar.gz`) or zstd (ROSI + per-arch `.app.tar.zst`, `scripts/pack-macos-updater-zst.js`) by magic bytes and rejects + anything else. zstd frames may not ask for a window above 2^27 + (`MACOS_ZSTD_WINDOW_LOG_MAX`, matching the packer's `--long=27`). Both formats share the + member checks, a 2 GiB decompressed cap, and a full-stream trailer check. Failure modes: + `e2e/updater-zst.failure-modes.md`. - Linux: privileged commands go through `linux_privileged_command` (env allowlist, fixed `PATH`, `LC_ALL=C`). Child processes run in their own process group with timeouts (`wait_child_output_timeout`, 600 s for package installs). Helper paths come from @@ -128,7 +136,8 @@ compile on macOS so their tests keep running. `src-tauri` as the seed. It is a standalone root package, so its unit tests run with `cargo test --locked --manifest-path src-tauri/vendor/tauri-plugin-updater/Cargo.toml --lib` (CI gate `vendorUpdater` in `scripts/test-all.js`). The root `cargo test --all-targets` - gate does not run them. Last run: 34 pass. + gate does not run them. Last run (macOS, 2026-10-24): 50 pass, 1 ignored (the real-archive + test that `scripts/e2e-updater-zst.mjs` runs). ## Rebase procedure (new upstream version X) diff --git a/src-tauri/vendor/tauri-plugin-updater/ROSI.patch b/src-tauri/vendor/tauri-plugin-updater/ROSI.patch index eb9547fd..63d9d46e 100644 --- a/src-tauri/vendor/tauri-plugin-updater/ROSI.patch +++ b/src-tauri/vendor/tauri-plugin-updater/ROSI.patch @@ -1,7 +1,21 @@ +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/Cargo.toml b/Cargo.toml +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -187,6 +187,10 @@ + [target.'cfg(target_os = "macos")'.dependencies.tar] + version = "0.4" + ++[target.'cfg(target_os = "macos")'.dependencies.zstd] ++version = "0.13.3" ++default-features = false ++ + [target.'cfg(target_os = "windows")'.dependencies.windows-sys] + version = "0.61.0" + features = [ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/appimage_archive.rs b/src/appimage_archive.rs --- a/src/appimage_archive.rs +++ b/src/appimage_archive.rs -@@ -0,0 +1,391 @@ +@@ -0,0 +1,397 @@ +// The AppImage helpers are compiled for macOS only because the shared module +// list includes it; their callers are Linux and BSD only. Keep dead_code quiet there. +#![cfg_attr(target_os = "macos", allow(dead_code))] @@ -82,19 +96,12 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/app + // `tar::Archive` accepts EOF without an end marker. Drain the complete gzip + // stream, then require both tar zero blocks and validate CRC/trailer errors, + // hidden trailing entries, and decompression caps. -+ decompressed.begin_trailer_check(); -+ io::copy(&mut decompressed, &mut io::sink()).map_err(|_| Error::InvalidUpdaterFormat)?; -+ if !decompressed.reached_eof -+ || decompressed.consecutive_zero_blocks < 2 -+ || decompressed.trailing_nonzero -+ { -+ return Err(Error::InvalidUpdaterFormat); -+ } ++ decompressed.drain_and_check_trailer()?; + + appimage.ok_or(Error::BinaryNotFoundInArchive) +} + -+struct BoundedArchiveReader { ++pub(crate) struct BoundedArchiveReader { + inner: R, + max_bytes: u64, + bytes_read: u64, @@ -107,7 +114,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/app +} + +impl BoundedArchiveReader { -+ fn new(inner: R, max_bytes: u64) -> Self { ++ pub(crate) fn new(inner: R, max_bytes: u64) -> Self { + Self { + inner, + max_bytes, @@ -126,6 +133,19 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/app + } +} + ++impl BoundedArchiveReader { ++ /// Call after `tar::Archive` stops reading. Drains the rest of the stream, ++ /// then requires both tar end blocks and no nonzero trailing data. ++ pub(crate) fn drain_and_check_trailer(&mut self) -> Result<()> { ++ self.begin_trailer_check(); ++ io::copy(self, &mut io::sink()).map_err(|_| Error::InvalidUpdaterFormat)?; ++ if !self.reached_eof || self.consecutive_zero_blocks < 2 || self.trailing_nonzero { ++ return Err(Error::InvalidUpdaterFormat); ++ } ++ Ok(()) ++ } ++} ++ +impl Read for BoundedArchiveReader { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + if buffer.is_empty() { @@ -140,7 +160,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/app + } + _ => Err(io::Error::new( + io::ErrorKind::InvalidData, -+ "AppImage archive exceeds the decompressed size limit", ++ "updater archive exceeds the decompressed size limit", + )), + }; + } @@ -2630,7 +2650,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd const UPDATER_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),); /// The kind of bundle the running application was installed from. -@@ -143,9 +168,10 @@ +@@ -143,9 +168,11 @@ } } @@ -2640,11 +2660,12 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd +/// Function executed right before the updater is launched. Returning an error aborts the installation, +/// keeping the downloaded update retryable. See [`UpdaterBuilder::on_before_exit`]. +pub type OnBeforeExit = Arc std::result::Result<(), String> + Send + Sync + 'static>; ++#[cfg(windows)] +type OnWindowsInstallerLaunched = Arc; /// Function that customizes the `reqwest` client builder used for the updater requests. /// See [`UpdaterBuilder::configure_client`]. pub type OnBeforeRequest = Arc ClientBuilder + Send + Sync + 'static>; -@@ -154,6 +180,75 @@ +@@ -154,6 +181,75 @@ /// It receives the current application version and the remote release, /// and returns `true` when the release should be treated as an update. pub type VersionComparator = Arc bool + Send + Sync>; @@ -2720,7 +2741,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd #[cfg(target_os = "macos")] type MainThreadClosure = Box; #[cfg(target_os = "macos")] -@@ -170,13 +265,16 @@ +@@ -170,13 +266,16 @@ /// App name, used for creating named tempfiles #[cfg(windows)] app_name: String, @@ -2738,7 +2759,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd restart_after_install: bool, } -@@ -218,11 +316,13 @@ +@@ -218,11 +317,13 @@ run_on_main_thread, #[cfg(windows)] app_name: app.package_info().name.clone(), @@ -2753,7 +2774,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd restart_after_install: true, }, current_version: app.package_info().version.clone(), -@@ -400,22 +500,34 @@ +@@ -400,22 +501,34 @@ self } @@ -2794,7 +2815,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } self } -@@ -453,6 +565,10 @@ +@@ -453,6 +566,10 @@ let arch = updater_arch().ok_or(Error::UnsupportedArch)?; let executable_path = self.executable_path.clone().unwrap_or(current_exe()?); @@ -2805,7 +2826,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd // Get the extract_path from the provided executable_path let extract_path = if cfg!(target_os = "linux") { -@@ -462,6 +578,7 @@ +@@ -462,6 +579,7 @@ }; Ok(Updater { @@ -2813,7 +2834,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd current_version: self.current_version, version_comparator: self.version_comparator, timeout: self.timeout, -@@ -495,6 +612,7 @@ +@@ -495,6 +613,7 @@ /// /// Get one from [`crate::UpdaterExt::updater`] or by calling [`UpdaterBuilder::build`]. pub struct Updater { @@ -2821,7 +2842,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd current_version: Version, version_comparator: Option, timeout: Option, -@@ -537,6 +655,27 @@ +@@ -537,6 +656,27 @@ headers.insert(ACCEPT, HeaderValue::from_static("application/json")); } @@ -2849,7 +2870,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd let target = self.current_target()?; let mut remote_release: Option = None; -@@ -726,6 +865,7 @@ +@@ -726,6 +866,7 @@ current_version: self.current_version.to_string(), target: target.to_owned(), extract_path: self.extract_path.clone(), @@ -2857,7 +2878,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd version: release.version.to_string(), date: release.pub_date, download_url: download_url.clone(), -@@ -807,6 +947,8 @@ +@@ -807,6 +948,8 @@ /// Extract path #[allow(unused)] extract_path: PathBuf, @@ -2866,7 +2887,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd context: UpdaterContext, } -@@ -877,14 +1019,20 @@ +@@ -877,14 +1020,20 @@ .get("Content-Length") .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse().ok()); @@ -2888,7 +2909,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } on_download_finish(); -@@ -921,7 +1069,7 @@ +@@ -921,7 +1070,7 @@ pub fn install(&self, bytes: impl AsRef<[u8]>) -> Result<()> { let bytes = bytes.as_ref(); self.verify(bytes)?; @@ -2897,7 +2918,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } /// Downloads and installs the updater package -@@ -935,9 +1083,8 @@ +@@ -935,9 +1084,8 @@ on_chunk: C, on_download_finish: D, ) -> Result<()> { @@ -2908,7 +2929,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } /// Updates are not supported on mobile, where apps are updated through the app stores. -@@ -1014,10 +1161,6 @@ +@@ -1014,10 +1162,6 @@ let updater_type = self.extract(bytes)?; @@ -2919,7 +2940,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd let file = match &updater_type { WindowsUpdaterType::Nsis { path, .. } => path.as_os_str().to_os_string(), -@@ -1033,7 +1176,7 @@ +@@ -1033,7 +1177,7 @@ let file = encode_wide(file); let parameters = encode_wide(parameters); @@ -2928,7 +2949,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd ShellExecuteW( std::ptr::null_mut(), w!("open"), -@@ -1042,12 +1185,16 @@ +@@ -1042,12 +1186,16 @@ std::ptr::null(), SW_SHOW, ) @@ -2951,7 +2972,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } fn updater_parameters(&self, updater_type: &WindowsUpdaterType) -> OsString { -@@ -1219,111 +1366,34 @@ +@@ -1219,113 +1367,36 @@ } fn install_appimage(&self, bytes: &[u8]) -> Result<()> { @@ -2979,7 +3000,8 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - log::error!("the update is neither an AppImage nor a compressed AppImage"); - return Err(Error::InvalidUpdaterFormat); - } -- ++ let payload = bytes.to_vec(); + - for tmp_dir_location in self.tmp_dir_locations() { - let Some(tmp_dir_location) = tmp_dir_location() else { - continue; @@ -3054,27 +3076,15 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - Ok(_) => Ok(()), - }; - } -- } -- -- Err(Error::TempDirNotOnSameMountPoint) -- } -+ let payload = bytes.to_vec(); - -- /// Directories to try, in order, for the temporary files of an install: the system temporary -- /// directory, the user cache directory and the directory holding the app. -- fn tmp_dir_locations(&self) -> Vec Option + '_>> { -- vec![ -- Box::new(|| Some(std::env::temp_dir())), -- Box::new(dirs::cache_dir), -- Box::new(|| self.extract_path.parent().map(Path::to_path_buf)), -- ] + // Keep the recovery copy beside the installed image when possible so + // it survives ordinary `/tmp` cleanup and remains on the install + // filesystem for an atomic replacement. + let mut temporary_roots = Vec::new(); + if let Some(parent) = self.extract_path.parent() { + temporary_roots.push(parent.to_path_buf()); -+ } + } +- +- Err(Error::TempDirNotOnSameMountPoint) + if let Some(cache_directory) = dirs::cache_dir() { + temporary_roots.push(cache_directory); + } @@ -3088,8 +3098,20 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + Ok(()) } +- /// Directories to try, in order, for the temporary files of an install: the system temporary +- /// directory, the user cache directory and the directory holding the app. +- fn tmp_dir_locations(&self) -> Vec Option + '_>> { +- vec![ +- Box::new(|| Some(std::env::temp_dir())), +- Box::new(dirs::cache_dir), +- Box::new(|| self.extract_path.parent().map(Path::to_path_buf)), +- ] +- } +- fn install_deb(&self, bytes: &[u8]) -> Result<()> { -@@ -1333,7 +1403,7 @@ + // First verify the bytes are actually a .deb package + if !infer::archive::is_deb(bytes) { +@@ -1333,7 +1404,7 @@ return Err(Error::InvalidUpdaterFormat); } @@ -3098,7 +3120,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } fn install_rpm(&self, bytes: &[u8]) -> Result<()> { -@@ -1341,29 +1411,43 @@ +@@ -1341,29 +1412,43 @@ if !infer::archive::is_rpm(bytes) { return Err(Error::InvalidUpdaterFormat); } @@ -3132,17 +3154,16 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - let prefix = format!("tauri_{package_extension}_update"); - if let Ok(tmp_dir) = tempfile::Builder::new().prefix(&prefix).tempdir_in(path) { - let pkg_path = tmp_dir.path().join(format!("package.{package_extension}")); -- -- // Try writing the .deb / .rpm file -- if std::fs::write(&pkg_path, bytes).is_ok() { -- // If write succeeds, proceed with installation -- return self.try_install_with_privileges(&pkg_path, install_cmd, install_arg); + for tmp_dir_location in tmp_dir_locations { + if let Some(path) = tmp_dir_location() { + let prefix = format!("tauri_{package_extension}_update"); + if let Ok(tmp_dir) = tempfile::Builder::new().prefix(&prefix).tempdir_in(path) { + let pkg_path = tmp_dir.path().join(format!("package.{package_extension}")); -+ + +- // Try writing the .deb / .rpm file +- if std::fs::write(&pkg_path, bytes).is_ok() { +- // If write succeeds, proceed with installation +- return self.try_install_with_privileges(&pkg_path, install_cmd, install_arg); + // Try writing the .deb / .rpm file + if std::fs::write(&pkg_path, bytes).is_ok() { + // If write succeeds, proceed with installation @@ -3156,7 +3177,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } // If write fails, continue to next temp location } -@@ -1377,68 +1461,78 @@ +@@ -1377,68 +1462,78 @@ &self, pkg_path: &Path, install_cmd: &str, @@ -3198,13 +3219,6 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - log::debug!("installed {pkg_path:?} with GUI sudo"); - return Ok(()); - } -- -- // 3. Final fallback: terminal sudo -- let status = std::process::Command::new("sudo") -- .arg(install_cmd) -- .arg(install_arg) -- .arg(pkg_path) -- .status()?; + if let Some(sudo) = sudo.as_ref() { + if let Ok(password) = self.get_password_graphically() { + if self.install_with_sudo(sudo, &installer, pkg_path, &password, install_args)? { @@ -3213,17 +3227,23 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + } + } -- if status.success() { -- log::debug!("installed {pkg_path:?} with sudo"); -- Ok(()) -- } else { -- Err(Error::PackageInstallFailed) +- // 3. Final fallback: terminal sudo +- let status = std::process::Command::new("sudo") +- .arg(install_cmd) +- .arg(install_arg) +- .arg(pkg_path) +- .status()?; + // 3. Final fallback: terminal sudo + let mut command = linux_privileged_command(sudo); + command.arg(&installer).args(install_args).arg(pkg_path); + let status = + linux_privileged_wait_status(command, std::time::Duration::from_secs(600))?; -+ + +- if status.success() { +- log::debug!("installed {pkg_path:?} with sudo"); +- Ok(()) +- } else { +- Err(Error::PackageInstallFailed) + if status.success() { + log::debug!("installed {pkg_path:?} with sudo"); + return Ok(()); @@ -3242,11 +3262,6 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - "--text=Enter your password to install the update:", - ]) - .output(); -- -- if let Ok(output) = zenity_result -- && output.status.success() -- { -- return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); + if let Ok(zenity) = crate::install_safety::resolve_trusted_system_helper("zenity") { + let zenity_result = linux_privileged_command(&zenity) + .args([ @@ -3255,7 +3270,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + "--text=Enter your password to install the update:", + ]) + .output(); -+ + +- if let Ok(output) = zenity_result +- && output.status.success() +- { +- return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); + if let Ok(output) = zenity_result { + if output.status.success() { + return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); @@ -3267,16 +3286,15 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - let kdialog_result = std::process::Command::new("kdialog") - .args(["--password", "Enter your password to install the update:"]) - .output(); -- -- if let Ok(output) = kdialog_result -- && output.status.success() -- { -- return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); + if let Ok(kdialog) = crate::install_safety::resolve_trusted_system_helper("kdialog") { + let kdialog_result = linux_privileged_command(&kdialog) + .args(["--password", "Enter your password to install the update:"]) + .output(); -+ + +- if let Ok(output) = kdialog_result +- && output.status.success() +- { +- return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); + if let Ok(output) = kdialog_result { + if output.status.success() { + return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); @@ -3285,7 +3303,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } Err(Error::AuthenticationFailed) -@@ -1446,34 +1540,105 @@ +@@ -1446,34 +1541,105 @@ fn install_with_sudo( &self, @@ -3319,10 +3337,10 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + .stderr(Stdio::piped()); + // Isolate the sudo/dpkg group so a timeout can kill the whole tree. + command.process_group(0); -+ + + let mut child = command.spawn()?; + let pid = child.id(); - ++ if let Some(mut stdin) = child.stdin.take() { - // Write password to stdin writeln!(stdin, "{password}")?; @@ -3402,7 +3420,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd /// MacOS #[cfg(target_os = "macos")] impl Update { -@@ -1484,143 +1649,192 @@ +@@ -1484,143 +1650,192 @@ /// │ └── ... /// └── ... fn install_inner(&self, bytes: &[u8]) -> Result<()> { @@ -3434,11 +3452,34 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - .flatten() - .find(|dir| dir.metadata().is_ok_and(|m| m.dev() == app_dev)) - .ok_or(Error::TempDirNotOnSameMountPoint)?; -- ++ let app_parent = self ++ .extract_path ++ .parent() ++ .ok_or(Error::FailedToDetermineExtractPath)?; ++ let backup_path = macos_update_backup_path(&self.extract_path) ++ .ok_or(Error::FailedToDetermineExtractPath)?; + - let tmp_backup_dir = tempfile::Builder::new() - .prefix("tauri_current_app") - .tempdir_in(&tmp_root)?; -- ++ let expected_identity = MacosBundleIdentity { ++ bundle_identifier: self.context.bundle_identifier.clone(), ++ executable: self.executable_name.clone().ok_or_else(|| { ++ Error::Io(std::io::Error::new( ++ std::io::ErrorKind::InvalidData, ++ "could not determine the installed app executable name", ++ )) ++ })?, ++ }; ++ if !macos_bundle_matches(&self.extract_path, &expected_identity) ++ && !macos_bundle_matches(&backup_path, &expected_identity) ++ { ++ return Err(Error::Io(std::io::Error::new( ++ std::io::ErrorKind::InvalidData, ++ "neither the installed app nor its recovery backup matches the configured app identity", ++ ))); ++ } + - let tmp_extract_dir = tempfile::Builder::new() - .prefix("tauri_updated_app") - .tempdir_in(&tmp_root)?; @@ -3455,16 +3496,39 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - // Ensure parent directories exist - if let Some(parent) = extraction_path.parent() { - std::fs::create_dir_all(parent)?; -- } -- ++ let tmp_extract_dir = match tempfile::Builder::new() ++ .prefix(".rosi-updated-app-") ++ .tempdir_in(app_parent) ++ { ++ Ok(dir) => dir, ++ Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => { ++ // `/Applications` is not user-writable. Extract in a user temp ++ // dir; the privileged swap copies onto the app volume. Restore ++ // must never nest `mv` into a partial `$SRC`. ++ tempfile::Builder::new() ++ .prefix("tauri_updated_app") ++ .tempdir()? + } ++ Err(err) => return Err(err.into()), ++ }; + - if let Err(err) = entry.unpack(&extraction_path) { - // Cleanup on error - std::fs::remove_dir_all(tmp_extract_dir.path()).ok(); - return Err(err.into()); - } - extracted_files.push(extraction_path); -- } -- ++ extract_macos_app_archive(bytes, tmp_extract_dir.path())?; ++ let staged_identity = macos_app_bundle_identity(tmp_extract_dir.path()); ++ if !macos_app_bundle_complete(tmp_extract_dir.path()) ++ || staged_identity.as_ref() != Some(&expected_identity) ++ { ++ return Err(Error::Io(std::io::Error::new( ++ std::io::ErrorKind::InvalidData, ++ "staged updater bundle is incomplete or has a different app identity", ++ ))); + } + - // The temp dir becomes the installed bundle's root, and tempfile creates it - // with mode 0700, which stops every other user of the machine from launching - // the updated app. @@ -3472,30 +3536,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - tmp_extract_dir.path(), - std::fs::Permissions::from_mode(0o755), - )?; -+ let app_parent = self -+ .extract_path -+ .parent() -+ .ok_or(Error::FailedToDetermineExtractPath)?; -+ let backup_path = macos_update_backup_path(&self.extract_path) -+ .ok_or(Error::FailedToDetermineExtractPath)?; -+ -+ let expected_identity = MacosBundleIdentity { -+ bundle_identifier: self.context.bundle_identifier.clone(), -+ executable: self.executable_name.clone().ok_or_else(|| { -+ Error::Io(std::io::Error::new( -+ std::io::ErrorKind::InvalidData, -+ "could not determine the installed app executable name", -+ )) -+ })?, -+ }; -+ if !macos_bundle_matches(&self.extract_path, &expected_identity) -+ && !macos_bundle_matches(&backup_path, &expected_identity) -+ { -+ return Err(Error::Io(std::io::Error::new( -+ std::io::ErrorKind::InvalidData, -+ "neither the installed app nor its recovery backup matches the configured app identity", -+ ))); -+ } ++ // Recovery can mutate a protected install tree. Delay it until the ++ // downloaded bundle has passed identity and completeness validation, ++ // then route only permission failures through the existing admin path. ++ let recovery = ++ recover_macos_live_bundle(&self.extract_path, &backup_path, &expected_identity)?; - // Exchange the current app and the new one in a single step where the file - // system supports it, so the install path is never empty; the previous app @@ -3509,22 +3554,9 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - Err(err) if err.kind() != std::io::ErrorKind::PermissionDenied => { - log::debug!("cannot swap the app bundles ({err}), moving them instead"); - replace_bundle(&self.extract_path, tmp_extract_dir.path(), &backup) -+ let tmp_extract_dir = match tempfile::Builder::new() -+ .prefix(".rosi-updated-app-") -+ .tempdir_in(app_parent) -+ { -+ Ok(dir) => dir, -+ Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => { -+ // `/Applications` is not user-writable. Extract in a user temp -+ // dir; the privileged swap copies onto the app volume. Restore -+ // must never nest `mv` into a partial `$SRC`. -+ tempfile::Builder::new() -+ .prefix("tauri_updated_app") -+ .tempdir()? - } +- } - other => other, -+ Err(err) => return Err(err.into()), - }; +- }; - let need_authorization = match moved { - Ok(()) => false, - Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => true, @@ -3537,24 +3569,6 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - ) { - log::error!("failed to install the update: {err}"); - return Err(Error::PreviousAppNotRestored(kept)); -+ -+ extract_macos_app_archive(bytes, tmp_extract_dir.path())?; -+ let staged_identity = macos_app_bundle_identity(tmp_extract_dir.path()); -+ if !macos_app_bundle_complete(tmp_extract_dir.path()) -+ || staged_identity.as_ref() != Some(&expected_identity) -+ { -+ return Err(Error::Io(std::io::Error::new( -+ std::io::ErrorKind::InvalidData, -+ "staged updater bundle is incomplete or has a different app identity", -+ ))); -+ } -+ -+ // Recovery can mutate a protected install tree. Delay it until the -+ // downloaded bundle has passed identity and completeness validation, -+ // then route only permission failures through the existing admin path. -+ let recovery = -+ recover_macos_live_bundle(&self.extract_path, &backup_path, &expected_identity)?; -+ + let unprivileged = if matches!(recovery, MacosRecoveryDisposition::RequiresPrivilegedSwap) { + // A validated recovery entry can live in a protected install + // directory. Keep it untouched until the staged bundle is fully @@ -3721,7 +3735,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } let _ = std::process::Command::new("touch") -@@ -1631,115 +1845,262 @@ +@@ -1631,115 +1846,299 @@ } } @@ -3732,14 +3746,6 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd -fn swap_bundle(target: &Path, staged: &Path) -> std::io::Result<()> { - use std::ffi::CString; - use std::os::unix::ffi::OsStrExt; -- -- let from = CString::new(staged.as_os_str().as_bytes())?; -- let to = CString::new(target.as_os_str().as_bytes())?; -- // SAFETY: both pointers are valid NUL-terminated strings that outlive the call, -- // and `renamex_np` only reads them. -- let result = unsafe { libc::renamex_np(from.as_ptr(), to.as_ptr(), libc::RENAME_SWAP) }; -- if result == 0 { -- Ok(()) +fn macos_bundle_matches( + path: &Path, + expected: &crate::install_safety::MacosBundleIdentity, @@ -3747,7 +3753,14 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + crate::install_safety::macos_app_bundle_complete(path) + && crate::install_safety::macos_app_bundle_identity(path).as_ref() == Some(expected) +} -+ + +- let from = CString::new(staged.as_os_str().as_bytes())?; +- let to = CString::new(target.as_os_str().as_bytes())?; +- // SAFETY: both pointers are valid NUL-terminated strings that outlive the call, +- // and `renamex_np` only reads them. +- let result = unsafe { libc::renamex_np(from.as_ptr(), to.as_ptr(), libc::RENAME_SWAP) }; +- if result == 0 { +- Ok(()) +#[cfg(target_os = "macos")] +fn remove_macos_bundle_entry(path: &Path) -> std::io::Result<()> { + let metadata = match std::fs::symlink_metadata(path) { @@ -3783,7 +3796,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + std::io::ErrorKind::InvalidData, + "refusing to retire an incomplete or identity-mismatched updater backup", + )); -+ } + } + let parent = backup.parent().ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, @@ -3842,7 +3855,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + return Ok(()); + } + return Err(error); - } ++ } + Ok(()) } @@ -3852,25 +3865,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd -/// Automation can call `renamex_np` (`2` is `RENAME_SWAP`), and ships with every macOS. -/// It prints `swapped` or `failed`, so the caller can tell a swap that did not happen -/// from an `osascript` failure that leaves unknown whether it did. --#[cfg(target_os = "macos")] + #[cfg(target_os = "macos")] -const SWAP_BUNDLE_JXA: &str = r#"function run(argv) { - ObjC.import("stdio"); - return $.renamex_np(argv[0], argv[1], 2) === 0 ? "swapped" : "failed"; -}"#; -- --/// The shell command the privileged install runs: the same swap as [`swap_bundle`], and --/// where the file system cannot swap, the same moves as [`replace_bundle`], deleting the --/// previous app only once the new one is in place. The moves only run once the swap is --/// known not to have happened, since after a swap they would put the previous app back. - #[cfg(target_os = "macos")] --fn privileged_install_command(target: &Path, staged: &Path, backup: &Path) -> String { -- let swap = sh_quote(Path::new(SWAP_BUNDLE_JXA)); -- let target = sh_quote(target); -- let staged = sh_quote(staged); -- let backup = sh_quote(backup); -- format!( -- "case \"$(/usr/bin/osascript -l JavaScript -e {swap} {staged} {target} 2>/dev/null)\" in swapped) rm -rf {staged};; failed) mv -f {target} {backup} && {{ mv -f {staged} {target} || {{ mv -f {backup} {target}; exit 1; }}; }} && rm -rf {backup};; *) exit 1;; esac" -- ) +fn restore_macos_live_bundle( + live: &Path, + backup: &Path, @@ -3891,22 +3890,31 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + )); + } + Ok(()) - } ++} --/// Quotes `path` as a single `sh` word, whatever characters it holds. +-/// The shell command the privileged install runs: the same swap as [`swap_bundle`], and +-/// where the file system cannot swap, the same moves as [`replace_bundle`], deleting the +-/// previous app only once the new one is in place. The moves only run once the swap is +-/// known not to have happened, since after a swap they would put the previous app back. #[cfg(target_os = "macos")] --fn sh_quote(path: &Path) -> String { -- format!("'{}'", path.to_string_lossy().replace('\'', r"'\''")) +-fn privileged_install_command(target: &Path, staged: &Path, backup: &Path) -> String { +- let swap = sh_quote(Path::new(SWAP_BUNDLE_JXA)); +- let target = sh_quote(target); +- let staged = sh_quote(staged); +- let backup = sh_quote(backup); +- format!( +- "case \"$(/usr/bin/osascript -l JavaScript -e {swap} {staged} {target} 2>/dev/null)\" in swapped) rm -rf {staged};; failed) mv -f {target} {backup} && {{ mv -f {staged} {target} || {{ mv -f {backup} {target}; exit 1; }}; }} && rm -rf {backup};; *) exit 1;; esac" +- ) +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MacosRecoveryDisposition { + ReadyForUnprivilegedSwap, + RequiresPrivilegedSwap, } --/// Quotes `s` as an AppleScript string literal. +-/// Quotes `path` as a single `sh` word, whatever characters it holds. #[cfg(target_os = "macos")] --fn applescript_string(s: &str) -> String { -- format!("\"{}\"", s.replace('\\', r"\\").replace('"', "\\\"")) +-fn sh_quote(path: &Path) -> String { +- format!("'{}'", path.to_string_lossy().replace('\'', r"'\''")) +fn recover_macos_live_bundle( + live: &Path, + backup: &Path, @@ -3952,6 +3960,14 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + ))) } +-/// Quotes `s` as an AppleScript string literal. + #[cfg(target_os = "macos")] +-fn applescript_string(s: &str) -> String { +- format!("\"{}\"", s.replace('\\', r"\\").replace('"', "\\\"")) ++fn extract_macos_app_archive(bytes: &[u8], dest_root: &Path) -> Result<()> { ++ extract_macos_app_archive_with_limit(bytes, dest_root, MACOS_MAX_DECOMPRESSED_BYTES) + } + -/// After a failed install, returns where the previous app is if it never made it back to -/// `target`. `backup` is then the only copy left, and usually sits in the system temp dir, -/// which macOS empties on its own, so it is moved next to `target`, or to `fallback_dir` @@ -3967,13 +3983,30 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - if std::fs::symlink_metadata(target).is_ok() || std::fs::symlink_metadata(backup).is_err() { - return None; - } -- ++/// Upper bound for an extracted `.app` (a universal ROSI bundle is ~300 MB). ++#[cfg(target_os = "macos")] ++const MACOS_MAX_DECOMPRESSED_BYTES: u64 = 2 * 1024 * 1024 * 1024; ++/// Per-arch `.app.tar.zst` archives are packed with `zstd --long=27`. Refuse ++/// frames that ask for a larger window instead of allocating it. ++#[cfg(target_os = "macos")] ++const MACOS_ZSTD_WINDOW_LOG_MAX: u32 = 27; + - let mut name = target.file_stem().unwrap_or_default().to_os_string(); - name.push(" (previous version)"); - if let Some(extension) = target.extension() { - name.push("."); - name.push(extension); -- } ++/// `.app.tar.gz` (Tauri) or `.app.tar.zst` (ROSI per-arch), chosen by magic bytes. ++#[cfg(target_os = "macos")] ++fn macos_archive_decoder<'a>(bytes: &'a [u8]) -> Result> { ++ const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b]; ++ const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd]; ++ let reader = std::io::Cursor::new(bytes); ++ if bytes.starts_with(&ZSTD_MAGIC) { ++ let mut decoder = zstd::stream::read::Decoder::new(reader)?; ++ decoder.window_log_max(MACOS_ZSTD_WINDOW_LOG_MAX)?; ++ return Ok(Box::new(decoder)); + } - let kept = [target.parent(), fallback_dir] - .into_iter() - .flatten() @@ -3981,23 +4014,33 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - // `rename` replaces an empty directory, so never move onto anything already there - .filter(|kept| std::fs::symlink_metadata(kept).is_err()) - .find(|kept| std::fs::rename(backup, kept).is_ok()); -- ++ if bytes.starts_with(&GZIP_MAGIC) { ++ return Ok(Box::new(flate2::read::GzDecoder::new(reader))); ++ } ++ Err(Error::InvalidUpdaterFormat) ++} + - match kept { - Some(kept) => Some(kept), - None => { - let _ = backup_dir.keep(); - Some(backup.to_path_buf()) +#[cfg(target_os = "macos")] -+fn extract_macos_app_archive(bytes: &[u8], dest_root: &Path) -> Result<()> { ++fn extract_macos_app_archive_with_limit( ++ bytes: &[u8], ++ dest_root: &Path, ++ max_decompressed_bytes: u64, ++) -> Result<()> { ++ use self::appimage_archive::BoundedArchiveReader; + use crate::install_safety::{ + confined_symlink_target, confined_tar_member_relative, create_confined_parent_dirs, + path_is_inside, + }; -+ use flate2::read::GzDecoder; + use tar::EntryType; + -+ let decoder = GzDecoder::new(Cursor::new(bytes)); -+ let mut archive = tar::Archive::new(decoder); ++ let mut decompressed = ++ BoundedArchiveReader::new(macos_archive_decoder(bytes)?, max_decompressed_bytes); ++ let mut archive = tar::Archive::new(&mut decompressed); + for entry in archive.entries()? { + let mut entry = entry?; + let entry_path = entry.path()?.into_owned(); @@ -4009,7 +4052,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + })?; + if relative.as_os_str().is_empty() { + continue; -+ } + } + let dest = dest_root.join(&relative); + if !path_is_inside(dest_root, &dest) { + return Err(Error::Io(std::io::Error::new( @@ -4058,7 +4101,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + Err(err) => return Err(err.into()), + } + continue; - } ++ } + if kind.is_file() || matches!(kind, EntryType::GNUSparse) { + create_confined_parent_dirs(dest_root, &dest)?; + entry.unpack(&dest)?; @@ -4069,11 +4112,13 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + format!("unsupported updater archive member type {kind:?}"), + ))); } -+ Ok(()) ++ // A truncated stream can end on a member boundary, which `tar::Archive` ++ // accepts. Require the full stream, both end blocks and nothing after them. ++ decompressed.drain_and_check_trailer() } /// Gets the base target string used by the updater. If bundle type is available it -@@ -1985,48 +2346,6 @@ +@@ -1985,49 +2384,7 @@ .collect() } @@ -4081,7 +4126,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd -/// -/// `ShellExecuteW` reports failures through its return value, not reliably through -/// `GetLastError`. --#[cfg(windows)] + #[cfg(windows)] -fn shell_execute_error(code: isize) -> std::io::Error { - use std::io::{Error, ErrorKind}; - use windows_sys::Win32::{ @@ -4119,10 +4164,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - } -} - - #[cfg(windows)] +-#[cfg(windows)] trait PathExt { fn wrap_in_quotes(&self) -> Self; -@@ -2116,13 +2435,13 @@ + } +@@ -2116,13 +2473,13 @@ // A throwaway key pair generated with `tauri signer generate`, and the signature of the // payload `test` made with `tauri signer sign --app-version 2.0.0`. @@ -4139,7 +4185,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd base64::engine::general_purpose::STANDARD.encode(value) } -@@ -2344,15 +2663,22 @@ +@@ -2344,15 +2701,22 @@ assert!(restored.context.config.require_signed_version); } @@ -4165,7 +4211,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd let update = builder() .executable_path(&appimage) .build() -@@ -2363,12 +2689,9 @@ +@@ -2363,12 +2727,9 @@ (dir, appimage, update) } @@ -4179,7 +4225,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } #[cfg(all(target_os = "linux", feature = "zip"))] -@@ -2389,11 +2712,12 @@ +@@ -2389,11 +2750,12 @@ #[cfg(target_os = "linux")] fn appimage_install_rejects_a_payload_that_is_not_an_appimage() { let (_dir, appimage, update) = appimage_update(); @@ -4194,7 +4240,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } #[test] -@@ -2402,7 +2726,6 @@ +@@ -2402,7 +2764,6 @@ use std::os::unix::fs::PermissionsExt; let (_dir, appimage, update) = appimage_update(); @@ -4202,7 +4248,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd update.install_appimage(&new_appimage()).unwrap(); assert_eq!(std::fs::read(&appimage).unwrap(), new_appimage()); assert_eq!( -@@ -2429,7 +2752,7 @@ +@@ -2429,7 +2790,7 @@ update.install_appimage(&compressed_appimage("readme.txt", b"hello")), Err(Error::BinaryNotFoundInArchive) )); @@ -4211,7 +4257,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } #[test] -@@ -2441,7 +2764,7 @@ +@@ -2441,7 +2802,7 @@ update.install_appimage(b"\x1f\x8b\x08\x00 compressed AppImage"), Err(Error::InvalidUpdaterFormat) )); @@ -4220,7 +4266,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } } -@@ -2501,277 +2824,119 @@ +@@ -2501,280 +2862,122 @@ assert!(verify_signed_version(comment, "2024-01-02", true).is_err()); } @@ -4234,7 +4280,13 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - std::fs::write(target.join("version"), "old").unwrap(); - std::fs::create_dir(&staged).unwrap(); - std::fs::write(staged.join("version"), "new").unwrap(); -- ++ use super::{finish_windows_installer_launch, OnBeforeExit, Update, UpdaterContext}; ++ use crate::Config; ++ use std::sync::{ ++ atomic::{AtomicUsize, Ordering}, ++ Arc, ++ }; + - super::replace_bundle(&target, &staged, &backup).unwrap(); - - assert_eq!( @@ -4260,13 +4312,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - let name = unsafe { std::ffi::CStr::from_ptr(stat.f_fstypename.as_ptr()) }; - name.to_bytes() == b"apfs" - } -+ use super::{finish_windows_installer_launch, OnBeforeExit, Update, UpdaterContext}; -+ use crate::Config; -+ use std::sync::{ -+ atomic::{AtomicUsize, Ordering}, -+ Arc, -+ }; - +- - #[test] - #[cfg(target_os = "macos")] - fn swap_bundle_exchanges_the_two_bundles_in_place() { @@ -4362,7 +4408,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd ); - assert!(!backup.exists()); - } -- + - /// A directory whose name `sh` and AppleScript would both misread unquoted. - #[cfg(target_os = "macos")] - fn hostile_dir() -> tempfile::TempDir { @@ -4370,7 +4416,16 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - .prefix("it's \"a\" \\ $(touch pwned) `dir`\n") - .tempdir() - .unwrap() -- } ++ let error = update ++ .install(b"test") ++ .expect_err("a failed pre-install hook must reject the actual install call"); ++ assert!(matches!( ++ error, ++ Error::BeforeExit(message) if message == "round2 forced durable-state flush failure" ++ )); ++ assert_eq!(hook_calls.load(Ordering::SeqCst), 1); ++ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 0); + } - #[cfg(target_os = "macos")] - fn assert_privileged_install_command_moved(dir: &std::path::Path) { @@ -4395,7 +4450,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - super::privileged_install_command(&target, &staged, &dir.join("backup")) - } - -- #[test] + #[test] - #[cfg(target_os = "macos")] - fn privileged_install_command_quotes_every_path() { - let dir = hostile_dir(); @@ -4430,26 +4485,27 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - .output() - .unwrap(); - -- assert!( ++ fn round2_windows_cleanup_runs_only_after_a_successful_installer_launch() { ++ let events = std::cell::RefCell::new(Vec::new()); ++ let failure = finish_windows_installer_launch( ++ 32, ++ || events.borrow_mut().push("cleanup"), ++ || events.borrow_mut().push("exit"), ++ ); ++ assert!(failure.is_err()); + assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) -- ); ++ events.borrow().is_empty(), ++ "failed launch must preserve Tauri resources" + ); - assert_privileged_install_command_moved(dir.path()); -+ let error = update -+ .install(b"test") -+ .expect_err("a failed pre-install hook must reject the actual install call"); -+ assert!(matches!( -+ error, -+ Error::BeforeExit(message) if message == "round2 forced durable-state flush failure" -+ )); -+ assert_eq!(hook_calls.load(Ordering::SeqCst), 1); -+ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 0); - } +- } - /// The privileged install swaps the bundles where the file system can, so on APFS it - /// never touches the backup: one in a directory that does not exist must not matter. - #[test] +- #[test] - #[cfg(target_os = "macos")] - fn privileged_install_command_swaps_the_bundles() { - let dir = tempfile::tempdir().unwrap(); @@ -4474,17 +4530,18 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - assert_eq!( - std::fs::read_to_string(target.join("version")).unwrap(), - "new" -+ fn round2_windows_cleanup_runs_only_after_a_successful_installer_launch() { -+ let events = std::cell::RefCell::new(Vec::new()); -+ let failure = finish_windows_installer_launch( -+ 32, +- ); +- assert!(!staged.exists()); ++ finish_windows_installer_launch( ++ 33, + || events.borrow_mut().push("cleanup"), + || events.borrow_mut().push("exit"), - ); -- assert!(!staged.exists()); -- } -- -- #[test] ++ ) ++ .expect("successful launch must finish cleanup and exit sequence"); ++ assert_eq!(&*events.borrow(), &["cleanup", "exit"]); + } + + #[test] - fn keeps_the_backup_when_the_previous_app_was_not_restored() { - let dir = tempfile::tempdir().unwrap(); - let target = dir.path().join("App.app"); @@ -4501,15 +4558,19 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - assert_eq!( - std::fs::read_to_string(expected.join("version")).unwrap(), - "old" -+ assert!(failure.is_err()); -+ assert!( -+ events.borrow().is_empty(), -+ "failed launch must preserve Tauri resources" - ); +- ); - assert!(!backup_dir_path.exists()); -- } ++ fn round2_download_cap_rejects_oversize_chunks_without_content_length() { ++ let mut received = Vec::new(); ++ super::append_download_chunk(&mut received, b"123", None, 4) ++ .expect("under-limit chunk should be accepted without a length header"); ++ let error = super::append_download_chunk(&mut received, b"45", None, 4) ++ .expect_err("actual streamed size must be capped without Content-Length"); ++ assert!(error.to_string().contains("package exceeds")); ++ assert_eq!(received, b"123", "over-limit bytes must not be buffered"); + } -- #[test] + #[test] - fn moves_the_backup_to_the_fallback_dir_when_it_cannot_go_next_to_the_app() { - let dir = tempfile::tempdir().unwrap(); - let target = dir.path().join("App.app"); @@ -4529,13 +4590,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - std::fs::read_to_string(expected.join("version")).unwrap(), - "old" - ); -+ finish_windows_installer_launch( -+ 33, -+ || events.borrow_mut().push("cleanup"), -+ || events.borrow_mut().push("exit"), -+ ) -+ .expect("successful launch must finish cleanup and exit sequence"); -+ assert_eq!(&*events.borrow(), &["cleanup", "exit"]); ++ fn round2_download_cap_rejects_declared_oversize_and_actual_oversize() { ++ let mut received = Vec::new(); ++ assert!(super::validate_download_content_length(Some(5), 4).is_err()); ++ assert!(super::append_download_chunk(&mut received, b"12345", Some(1), 4).is_err()); ++ assert!(received.is_empty(), "rejected bytes must not be buffered"); } #[test] @@ -4562,17 +4621,9 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - std::fs::read_to_string(dir.path().join("App (previous version).app")).unwrap(), - "other" - ); -+ fn round2_download_cap_rejects_oversize_chunks_without_content_length() { -+ let mut received = Vec::new(); -+ super::append_download_chunk(&mut received, b"123", None, 4) -+ .expect("under-limit chunk should be accepted without a length header"); -+ let error = super::append_download_chunk(&mut received, b"45", None, 4) -+ .expect_err("actual streamed size must be capped without Content-Length"); -+ assert!(error.to_string().contains("package exceeds")); -+ assert_eq!(received, b"123", "over-limit bytes must not be buffered"); - } - - #[test] +- } +- +- #[test] - fn drops_the_backup_when_the_previous_app_is_in_place() { - let dir = tempfile::tempdir().unwrap(); - let target = dir.path().join("App.app"); @@ -4584,18 +4635,18 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - - assert!(super::keep_backup_if_not_restored(&target, backup_dir, &backup, None).is_none()); - assert!(!backup_dir_path.exists()); -+ fn round2_download_cap_rejects_declared_oversize_and_actual_oversize() { -+ let mut received = Vec::new(); -+ assert!(super::validate_download_content_length(Some(5), 4).is_err()); -+ assert!(super::append_download_chunk(&mut received, b"12345", Some(1), 4).is_err()); -+ assert!(received.is_empty(), "rejected bytes must not be buffered"); - } +- } +- +- #[test] + #[cfg(windows)] + fn it_wraps_correctly() { + use super::PathExt; +@@ -2874,6 +3077,195 @@ - #[test] -@@ -2876,4 +3041,45 @@ + for (orig, escaped) in cases.iter().zip(cases_escaped) { assert_eq!(escape_nsis_current_exe_arg(OsStr::new(orig)), escaped); - } - } ++ } ++ } + + #[test] + fn macos_admin_install_script_quotes_paths_via_handler_args() { @@ -4637,4 +4688,152 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + "malicious path must stay outside the constant script body" + ); + } ++} ++ ++// e2e/updater-zst.failure-modes.md, Z01. ++#[cfg(all(test, target_os = "macos"))] ++mod macos_archive_tests { ++ use super::{extract_macos_app_archive, extract_macos_app_archive_with_limit}; ++ use crate::error::Error; ++ use std::io::Write; ++ use tar::{EntryType, Header}; ++ ++ const EXECUTABLE: &str = "ROSI.app/Contents/MacOS/ROSI"; ++ ++ fn app_tar(payload: &[u8]) -> Vec { ++ let mut builder = tar::Builder::new(Vec::new()); ++ for dir in ["ROSI.app/", "ROSI.app/Contents/", "ROSI.app/Contents/MacOS/"] { ++ let mut header = Header::new_gnu(); ++ header.set_entry_type(EntryType::Directory); ++ header.set_mode(0o755); ++ header.set_size(0); ++ header.set_cksum(); ++ builder.append_data(&mut header, dir, &[][..]).unwrap(); ++ } ++ let mut header = Header::new_gnu(); ++ header.set_entry_type(EntryType::Regular); ++ header.set_mode(0o755); ++ header.set_size(payload.len() as u64); ++ header.set_cksum(); ++ builder.append_data(&mut header, EXECUTABLE, payload).unwrap(); ++ builder.into_inner().unwrap() ++ } ++ ++ fn gzip(raw: &[u8]) -> Vec { ++ let mut encoder = ++ flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); ++ encoder.write_all(raw).unwrap(); ++ encoder.finish().unwrap() ++ } ++ ++ fn zstd_with_window_log(raw: &[u8], window_log: u32) -> Vec { ++ let mut encoder = zstd::stream::write::Encoder::new(Vec::new(), 3).unwrap(); ++ encoder.long_distance_matching(true).unwrap(); ++ encoder.window_log(window_log).unwrap(); ++ encoder.write_all(raw).unwrap(); ++ encoder.finish().unwrap() ++ } ++ ++ fn zstd(raw: &[u8]) -> Vec { ++ zstd_with_window_log(raw, 27) ++ } ++ ++ fn extracted_executable(archive: &[u8]) -> crate::Result> { ++ let dir = tempfile::tempdir().unwrap(); ++ extract_macos_app_archive(archive, dir.path())?; ++ Ok(std::fs::read(dir.path().join("Contents/MacOS/ROSI")).unwrap()) ++ } ++ ++ #[test] ++ fn gzip_and_zstd_archives_extract_the_same_bundle() { ++ let payload = b"\xcf\xfa\xed\xfe rosi executable".repeat(64); ++ let raw = app_tar(&payload); ++ assert_eq!(extracted_executable(&gzip(&raw)).unwrap(), payload); ++ assert_eq!(extracted_executable(&zstd(&raw)).unwrap(), payload); ++ } ++ ++ #[test] ++ fn rejects_a_truncated_zstd_archive() { ++ let archive = zstd(&app_tar(&[7_u8; 64 * 1024])); ++ let truncated = &archive[..archive.len() / 2]; ++ assert!(extracted_executable(truncated).is_err()); ++ } ++ ++ #[test] ++ fn rejects_a_zstd_window_larger_than_the_cap() { ++ // The frame header asks for a 256 MiB window; the content stays small. ++ let archive = zstd_with_window_log(&app_tar(b"payload"), 28); ++ assert!(extracted_executable(&archive).is_err()); ++ } ++ ++ #[test] ++ fn stops_a_decompression_bomb_at_the_cap() { ++ let archive = zstd(&app_tar(&vec![0_u8; 4 * 1024 * 1024])); ++ assert!(archive.len() < 64 * 1024, "fixture must compress well"); ++ let dir = tempfile::tempdir().unwrap(); ++ assert!(extract_macos_app_archive_with_limit(&archive, dir.path(), 1024 * 1024).is_err()); ++ } ++ ++ #[test] ++ fn rejects_trailing_data_after_the_zstd_frame() { ++ let mut archive = zstd(&app_tar(b"payload")); ++ archive.extend_from_slice(b"not a zstd frame"); ++ assert!(extracted_executable(&archive).is_err()); ++ } ++ ++ #[test] ++ fn rejects_a_tar_stream_without_end_blocks() { ++ let mut raw = app_tar(b"payload"); ++ raw.truncate(raw.len() - 1024); ++ assert!(extracted_executable(&zstd(&raw)).is_err()); ++ assert!(extracted_executable(&gzip(&raw)).is_err()); ++ } ++ ++ #[test] ++ fn rejects_unknown_archive_magic() { ++ let raw = app_tar(b"payload"); ++ assert!(matches!( ++ extracted_executable(&raw), ++ Err(Error::InvalidUpdaterFormat) ++ )); ++ } ++ ++ #[test] ++ fn keeps_member_confinement_for_zstd_archives() { ++ let mut raw = Vec::new(); ++ let mut header = Header::new_gnu(); ++ header.set_entry_type(EntryType::Regular); ++ header.set_mode(0o644); ++ header.set_size(1); ++ // `set_path` refuses `..`; write the name bytes directly. ++ header.as_gnu_mut().unwrap().name[..17].copy_from_slice(b"ROSI.app/../../x\0"); ++ header.set_cksum(); ++ raw.extend_from_slice(header.as_bytes()); ++ raw.extend_from_slice(&[b'x'; 512]); ++ raw.extend_from_slice(&[0_u8; 1024]); ++ assert!(extracted_executable(&zstd(&raw)).is_err()); ++ } ++ ++ /// Run by scripts/e2e-updater-zst.mjs against real release archives. ++ #[test] ++ #[ignore = "needs ROSI_UPDATER_ZST_E2E_ARCHIVES"] ++ fn extracts_real_release_archives() { ++ let paths = std::env::var("ROSI_UPDATER_ZST_E2E_ARCHIVES") ++ .expect("ROSI_UPDATER_ZST_E2E_ARCHIVES lists archives separated by ':'"); ++ for path in paths.split(':').filter(|p| !p.is_empty()) { ++ let bytes = std::fs::read(path).unwrap(); ++ let dir = tempfile::tempdir().unwrap(); ++ let started = std::time::Instant::now(); ++ extract_macos_app_archive(&bytes, dir.path()) ++ .unwrap_or_else(|err| panic!("{path}: {err}")); ++ assert!( ++ crate::install_safety::macos_app_bundle_complete(dir.path()), ++ "{path}: extracted bundle is incomplete" ++ ); ++ println!( ++ "ROSI_UPDATER_ZST_E2E {path} extract_ms={}", ++ started.elapsed().as_millis() ++ ); + } + } } diff --git a/src-tauri/vendor/tauri-plugin-updater/src/appimage_archive.rs b/src-tauri/vendor/tauri-plugin-updater/src/appimage_archive.rs index fb00205f..edac1b08 100644 --- a/src-tauri/vendor/tauri-plugin-updater/src/appimage_archive.rs +++ b/src-tauri/vendor/tauri-plugin-updater/src/appimage_archive.rs @@ -78,19 +78,12 @@ fn extract_appimage_from_archive_with_limits( // `tar::Archive` accepts EOF without an end marker. Drain the complete gzip // stream, then require both tar zero blocks and validate CRC/trailer errors, // hidden trailing entries, and decompression caps. - decompressed.begin_trailer_check(); - io::copy(&mut decompressed, &mut io::sink()).map_err(|_| Error::InvalidUpdaterFormat)?; - if !decompressed.reached_eof - || decompressed.consecutive_zero_blocks < 2 - || decompressed.trailing_nonzero - { - return Err(Error::InvalidUpdaterFormat); - } + decompressed.drain_and_check_trailer()?; appimage.ok_or(Error::BinaryNotFoundInArchive) } -struct BoundedArchiveReader { +pub(crate) struct BoundedArchiveReader { inner: R, max_bytes: u64, bytes_read: u64, @@ -103,7 +96,7 @@ struct BoundedArchiveReader { } impl BoundedArchiveReader { - fn new(inner: R, max_bytes: u64) -> Self { + pub(crate) fn new(inner: R, max_bytes: u64) -> Self { Self { inner, max_bytes, @@ -122,6 +115,19 @@ impl BoundedArchiveReader { } } +impl BoundedArchiveReader { + /// Call after `tar::Archive` stops reading. Drains the rest of the stream, + /// then requires both tar end blocks and no nonzero trailing data. + pub(crate) fn drain_and_check_trailer(&mut self) -> Result<()> { + self.begin_trailer_check(); + io::copy(self, &mut io::sink()).map_err(|_| Error::InvalidUpdaterFormat)?; + if !self.reached_eof || self.consecutive_zero_blocks < 2 || self.trailing_nonzero { + return Err(Error::InvalidUpdaterFormat); + } + Ok(()) + } +} + impl Read for BoundedArchiveReader { fn read(&mut self, buffer: &mut [u8]) -> io::Result { if buffer.is_empty() { @@ -136,7 +142,7 @@ impl Read for BoundedArchiveReader { } _ => Err(io::Error::new( io::ErrorKind::InvalidData, - "AppImage archive exceeds the decompressed size limit", + "updater archive exceeds the decompressed size limit", )), }; } diff --git a/src-tauri/vendor/tauri-plugin-updater/src/updater.rs b/src-tauri/vendor/tauri-plugin-updater/src/updater.rs index 98967429..49777dea 100644 --- a/src-tauri/vendor/tauri-plugin-updater/src/updater.rs +++ b/src-tauri/vendor/tauri-plugin-updater/src/updater.rs @@ -2021,15 +2021,50 @@ fn recover_macos_live_bundle( #[cfg(target_os = "macos")] fn extract_macos_app_archive(bytes: &[u8], dest_root: &Path) -> Result<()> { + extract_macos_app_archive_with_limit(bytes, dest_root, MACOS_MAX_DECOMPRESSED_BYTES) +} + +/// Upper bound for an extracted `.app` (a universal ROSI bundle is ~300 MB). +#[cfg(target_os = "macos")] +const MACOS_MAX_DECOMPRESSED_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// Per-arch `.app.tar.zst` archives are packed with `zstd --long=27`. Refuse +/// frames that ask for a larger window instead of allocating it. +#[cfg(target_os = "macos")] +const MACOS_ZSTD_WINDOW_LOG_MAX: u32 = 27; + +/// `.app.tar.gz` (Tauri) or `.app.tar.zst` (ROSI per-arch), chosen by magic bytes. +#[cfg(target_os = "macos")] +fn macos_archive_decoder<'a>(bytes: &'a [u8]) -> Result> { + const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b]; + const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd]; + let reader = std::io::Cursor::new(bytes); + if bytes.starts_with(&ZSTD_MAGIC) { + let mut decoder = zstd::stream::read::Decoder::new(reader)?; + decoder.window_log_max(MACOS_ZSTD_WINDOW_LOG_MAX)?; + return Ok(Box::new(decoder)); + } + if bytes.starts_with(&GZIP_MAGIC) { + return Ok(Box::new(flate2::read::GzDecoder::new(reader))); + } + Err(Error::InvalidUpdaterFormat) +} + +#[cfg(target_os = "macos")] +fn extract_macos_app_archive_with_limit( + bytes: &[u8], + dest_root: &Path, + max_decompressed_bytes: u64, +) -> Result<()> { + use self::appimage_archive::BoundedArchiveReader; use crate::install_safety::{ confined_symlink_target, confined_tar_member_relative, create_confined_parent_dirs, path_is_inside, }; - use flate2::read::GzDecoder; use tar::EntryType; - let decoder = GzDecoder::new(std::io::Cursor::new(bytes)); - let mut archive = tar::Archive::new(decoder); + let mut decompressed = + BoundedArchiveReader::new(macos_archive_decoder(bytes)?, max_decompressed_bytes); + let mut archive = tar::Archive::new(&mut decompressed); for entry in archive.entries()? { let mut entry = entry?; let entry_path = entry.path()?.into_owned(); @@ -2101,7 +2136,9 @@ fn extract_macos_app_archive(bytes: &[u8], dest_root: &Path) -> Result<()> { format!("unsupported updater archive member type {kind:?}"), ))); } - Ok(()) + // A truncated stream can end on a member boundary, which `tar::Archive` + // accepts. Require the full stream, both end blocks and nothing after them. + decompressed.drain_and_check_trailer() } /// Gets the base target string used by the updater. If bundle type is available it @@ -3084,3 +3121,151 @@ mod tests { ); } } + +// e2e/updater-zst.failure-modes.md, Z01. +#[cfg(all(test, target_os = "macos"))] +mod macos_archive_tests { + use super::{extract_macos_app_archive, extract_macos_app_archive_with_limit}; + use crate::error::Error; + use std::io::Write; + use tar::{EntryType, Header}; + + const EXECUTABLE: &str = "ROSI.app/Contents/MacOS/ROSI"; + + fn app_tar(payload: &[u8]) -> Vec { + let mut builder = tar::Builder::new(Vec::new()); + for dir in ["ROSI.app/", "ROSI.app/Contents/", "ROSI.app/Contents/MacOS/"] { + let mut header = Header::new_gnu(); + header.set_entry_type(EntryType::Directory); + header.set_mode(0o755); + header.set_size(0); + header.set_cksum(); + builder.append_data(&mut header, dir, &[][..]).unwrap(); + } + let mut header = Header::new_gnu(); + header.set_entry_type(EntryType::Regular); + header.set_mode(0o755); + header.set_size(payload.len() as u64); + header.set_cksum(); + builder.append_data(&mut header, EXECUTABLE, payload).unwrap(); + builder.into_inner().unwrap() + } + + fn gzip(raw: &[u8]) -> Vec { + let mut encoder = + flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(raw).unwrap(); + encoder.finish().unwrap() + } + + fn zstd_with_window_log(raw: &[u8], window_log: u32) -> Vec { + let mut encoder = zstd::stream::write::Encoder::new(Vec::new(), 3).unwrap(); + encoder.long_distance_matching(true).unwrap(); + encoder.window_log(window_log).unwrap(); + encoder.write_all(raw).unwrap(); + encoder.finish().unwrap() + } + + fn zstd(raw: &[u8]) -> Vec { + zstd_with_window_log(raw, 27) + } + + fn extracted_executable(archive: &[u8]) -> crate::Result> { + let dir = tempfile::tempdir().unwrap(); + extract_macos_app_archive(archive, dir.path())?; + Ok(std::fs::read(dir.path().join("Contents/MacOS/ROSI")).unwrap()) + } + + #[test] + fn gzip_and_zstd_archives_extract_the_same_bundle() { + let payload = b"\xcf\xfa\xed\xfe rosi executable".repeat(64); + let raw = app_tar(&payload); + assert_eq!(extracted_executable(&gzip(&raw)).unwrap(), payload); + assert_eq!(extracted_executable(&zstd(&raw)).unwrap(), payload); + } + + #[test] + fn rejects_a_truncated_zstd_archive() { + let archive = zstd(&app_tar(&[7_u8; 64 * 1024])); + let truncated = &archive[..archive.len() / 2]; + assert!(extracted_executable(truncated).is_err()); + } + + #[test] + fn rejects_a_zstd_window_larger_than_the_cap() { + // The frame header asks for a 256 MiB window; the content stays small. + let archive = zstd_with_window_log(&app_tar(b"payload"), 28); + assert!(extracted_executable(&archive).is_err()); + } + + #[test] + fn stops_a_decompression_bomb_at_the_cap() { + let archive = zstd(&app_tar(&vec![0_u8; 4 * 1024 * 1024])); + assert!(archive.len() < 64 * 1024, "fixture must compress well"); + let dir = tempfile::tempdir().unwrap(); + assert!(extract_macos_app_archive_with_limit(&archive, dir.path(), 1024 * 1024).is_err()); + } + + #[test] + fn rejects_trailing_data_after_the_zstd_frame() { + let mut archive = zstd(&app_tar(b"payload")); + archive.extend_from_slice(b"not a zstd frame"); + assert!(extracted_executable(&archive).is_err()); + } + + #[test] + fn rejects_a_tar_stream_without_end_blocks() { + let mut raw = app_tar(b"payload"); + raw.truncate(raw.len() - 1024); + assert!(extracted_executable(&zstd(&raw)).is_err()); + assert!(extracted_executable(&gzip(&raw)).is_err()); + } + + #[test] + fn rejects_unknown_archive_magic() { + let raw = app_tar(b"payload"); + assert!(matches!( + extracted_executable(&raw), + Err(Error::InvalidUpdaterFormat) + )); + } + + #[test] + fn keeps_member_confinement_for_zstd_archives() { + let mut raw = Vec::new(); + let mut header = Header::new_gnu(); + header.set_entry_type(EntryType::Regular); + header.set_mode(0o644); + header.set_size(1); + // `set_path` refuses `..`; write the name bytes directly. + header.as_gnu_mut().unwrap().name[..17].copy_from_slice(b"ROSI.app/../../x\0"); + header.set_cksum(); + raw.extend_from_slice(header.as_bytes()); + raw.extend_from_slice(&[b'x'; 512]); + raw.extend_from_slice(&[0_u8; 1024]); + assert!(extracted_executable(&zstd(&raw)).is_err()); + } + + /// Run by scripts/e2e-updater-zst.mjs against real release archives. + #[test] + #[ignore = "needs ROSI_UPDATER_ZST_E2E_ARCHIVES"] + fn extracts_real_release_archives() { + let paths = std::env::var("ROSI_UPDATER_ZST_E2E_ARCHIVES") + .expect("ROSI_UPDATER_ZST_E2E_ARCHIVES lists archives separated by ':'"); + for path in paths.split(':').filter(|p| !p.is_empty()) { + let bytes = std::fs::read(path).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let started = std::time::Instant::now(); + extract_macos_app_archive(&bytes, dir.path()) + .unwrap_or_else(|err| panic!("{path}: {err}")); + assert!( + crate::install_safety::macos_app_bundle_complete(dir.path()), + "{path}: extracted bundle is incomplete" + ); + println!( + "ROSI_UPDATER_ZST_E2E {path} extract_ms={}", + started.elapsed().as_millis() + ); + } + } +} diff --git a/src/commands.ts b/src/commands.ts index 35910c22..3b03b541 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -59,6 +59,7 @@ export interface Commands { get_app_platform: { args: void; result: NodeJS.Platform }; get_distribution_channel: { args: void; result: string }; get_beta_updater_target: { args: void; result: string }; + get_compact_updater_target: { args: { beta: boolean }; result: string | null }; restart_app: { args: void; result: void }; log_error: { args: { message: string }; result: void }; notify_settings_flushed: { args: { generation: number }; result: void }; diff --git a/src/updater.ts b/src/updater.ts index 81566eee..342740a9 100644 --- a/src/updater.ts +++ b/src/updater.ts @@ -3,6 +3,8 @@ // latest-{target}-{arch}.json endpoints; beta checks pass a custom // `{os}-beta-{arch}-{installer}` target so they read the beta manifests // published (and synced onto the latest stable release) by scripts/gpg-sign.js. +// Packaged macOS apps instead pass `darwin[-beta]-{arch}-app-zst`, which +// points at per-arch zstd archives, and fall back to the targets above. import { call, type CommandArgs, type CommandName, type Commands } from './commands'; import { getVersion } from '@tauri-apps/api/app'; import { check, type DownloadEvent, type Update } from '@tauri-apps/plugin-updater'; @@ -135,10 +137,19 @@ async function updateCheckTarget(): Promise { } const channel = updateChannelOverride ?? (await updaterInvoke('get_settings')).updateChannel ?? 'auto'; - if (channel === 'stable') return undefined; - if (channel === 'beta') return updaterInvoke('get_beta_updater_target'); // auto: follow the installed version. - return isBetaVersion(await getVersion()) ? updaterInvoke('get_beta_updater_target') : undefined; + const beta = channel === 'beta' || (channel === 'auto' && isBetaVersion(await getVersion())); + const compact = await updaterInvoke('get_compact_updater_target', { beta }); + if (compact) return compact; + return beta ? updaterInvoke('get_beta_updater_target') : undefined; +} + +const COMPACT_TARGET_SUFFIX = '-app-zst'; + +// The target a packaged macOS app used before per-arch zstd feeds existed. +function legacyTarget(compactTarget: string): string | undefined { + // darwin-beta-aarch64-app-zst -> darwin-beta-aarch64-app; stable uses the default target. + return compactTarget.includes('-beta-') ? compactTarget.slice(0, -'-zst'.length) : undefined; } export function notifyUpdaterChannelChanged( @@ -190,6 +201,21 @@ async function retiredLinuxPackageMessage(): Promise { async function checkFeed( target: string | undefined, isCurrent: () => boolean +): Promise { + if (!target?.endsWith(COMPACT_TARGET_SUFFIX)) return checkTargetFeed(target, isCurrent); + try { + return await checkTargetFeed(target, isCurrent); + } catch { + if (!isCurrent()) return null; + // A release published without per-arch zstd archives still updates + // through the universal .app.tar.gz feed. + return checkTargetFeed(legacyTarget(target), isCurrent); + } +} + +async function checkTargetFeed( + target: string | undefined, + isCurrent: () => boolean ): Promise { const testCheck = e2eUpdaterAdapter()?.check; if (testCheck) { From a07a5a81469eef21836e4095f67b05844705a133 Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:33:31 -0700 Subject: [PATCH 02/58] changes and fixes --- ARCHITECTURE.md | 12 +- CHANGELOG.md | 6 +- THIRD-PARTY-NOTICES.md | 39 + build-setup.md | 1 + e2e/updater-zst.failure-modes.md | 35 +- package.json | 2 +- run.rosie.rosi.metainfo.xml | 2 +- scripts/check-stable-metadata-pr.mjs | 61 +- scripts/e2e-updater-zst.mjs | 280 +++++- scripts/pack-macos-updater-zst.js | 205 ++++- scripts/release-preflight.js | 15 + scripts/round2-release-updater.test.mjs | 22 +- scripts/validate-updater-live.js | 8 +- scripts/validate-updater-manifest.js | 35 + scripts/verify-release-draft.js | 29 +- src-tauri/gen/schemas/linux-schema.json | 100 +- src-tauri/gen/schemas/windows-schema.json | 12 + src-tauri/src/platform.rs | 47 +- src-tauri/tauri.conf.json | 7 +- .../vendor/tauri-plugin-updater/PATCHES.md | 27 +- .../vendor/tauri-plugin-updater/ROSI.patch | 858 +++++++++++------- .../src/appimage_archive.rs | 5 +- .../src/install_safety.rs | 172 ++++ .../tauri-plugin-updater/src/updater.rs | 74 +- src/updater.ts | 25 +- .../latest-darwin-aarch64-app-zst.json | 11 + testdata/updater/latest-darwin-aarch64.json | 2 +- .../latest-darwin-beta-aarch64-app-zst.json | 11 + .../updater/latest-darwin-beta-aarch64.json | 4 +- testdata/updater/latest-darwin-x86_64.json | 2 +- testdata/updater/latest-linux-x86_64.json | 4 +- testdata/updater/latest-windows-aarch64.json | 4 +- testdata/updater/latest-windows-x86_64.json | 4 +- 33 files changed, 1668 insertions(+), 453 deletions(-) create mode 100644 testdata/updater/latest-darwin-aarch64-app-zst.json create mode 100644 testdata/updater/latest-darwin-beta-aarch64-app-zst.json diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 3806d87a..927325c0 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -69,7 +69,11 @@ normal loaders validate everything, and the result is recorded in DOM tests and the E2E specs drive. - `updater.ts` wraps `@tauri-apps/plugin-updater`. Stable checks use the default `latest-{target}-{arch}.json` endpoints; beta checks pass the - `{os}-beta-{arch}-{installer}` target from `get_beta_updater_target`. + `{os}-beta-{arch}-{installer}` target from `get_beta_updater_target`. Packaged + macOS apps call `get_compact_updater_target` to check per-arch zstd updates + (`darwin[-beta]-{arch}-app-zst`) and fall back to the universal target if unavailable. + Under Rosetta 2, `get_compact_updater_target` selects the native `aarch64` target to + migrate the app to native Apple Silicon execution. - `main.ts` is the entry point. It imports the bridge first, then the renderer modules, then `rosiEngine.ts`. After the renderer reports startup readiness it calls `mark_main_window_ready`, which lets the backend close the splash. @@ -126,7 +130,11 @@ per-arch `ROSI-{aarch64,x86_64}.app.tar.zst` instead of the universal and never collects the per-arch builds' arch-less `.app.tar.gz`. - Packaged macOS apps ask for that target (`get_compact_updater_target`). If the compact feed is missing they fall back to the universal feed, which stays published - for clients older than 5.1.0. + for clients older than 5.1.0. An x86_64 process running under Rosetta 2 requests + `darwin[-beta]-aarch64-app-zst` so it updates directly to native Apple Silicon execution. +- Staged updates are verified prior to installation: the vendored updater validates that + the extracted executable and sidecars match the host architecture before live bundle + replacement or backup retirement. - `rosi-yt-dlp` is upstream's universal2 binary and already compressed, so about 36 MB of every update is yt-dlp. diff --git a/CHANGELOG.md b/CHANGELOG.md index d45e6d60..f0ba4e6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,11 @@ ROSI! A cross platform yt-dlp GUI built on Tauri V2! ## Changes in `v5.1.0-beta.1:` -- **Fix:** (add release notes) +- **Updater:** macOS in-app updates now download compact per-architecture archives (`.app.tar.zst`), reducing update sizes from ~141 MB to ~60 MB using zstd compression. +- **Updater:** Added seamless fallback to universal updates if per-architecture manifests are missing. +- **Updater:** Architecture verification ensures downloaded macOS updates match the host machine before installation. +- **Updater:** Rosetta-translated processes on Apple Silicon automatically request the native arm64 target to migrate away from emulation. +- **Packaging:** Per-architecture updater archives are verified for codesigning and notarization stapling prior to packaging. ## Changes in `v5.0.2:` diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 04c23c0b..38dccdb1 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -1060,6 +1060,45 @@ The complete, version-specific license notices for every Rust crate compiled into ROSI (including Tauri and its plugins) are generated at build time and shown in the app under **Licenses > Rust Crate Dependencies**. +## zstd (libzstd) + +License: BSD-3-Clause +Link: https://github.com/facebook/zstd + +The macOS updater statically compiles the libzstd reference implementation +via the `zstd-sys` crate for per-architecture archive extraction. + +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + --- # Bundled yt-dlp binary diff --git a/build-setup.md b/build-setup.md index 0f470669..b71dfa33 100644 --- a/build-setup.md +++ b/build-setup.md @@ -22,6 +22,7 @@ 15.0 because the bundled FFmpeg is built for macOS 15; `build:mac:zip` rejects any bundled Mach-O whose minimum OS is above that floor. - Xcode Command Line Tools (`lipo`, `codesign`, `notarytool`) +- zstd CLI (`brew install zstd`) for the updater archives; checked by `npm run prerelease:prepare` - Node.js `^24.15.0 || >=26` - Rust (rustup) diff --git a/e2e/updater-zst.failure-modes.md b/e2e/updater-zst.failure-modes.md index bdbc4fe2..0344f1ad 100644 --- a/e2e/updater-zst.failure-modes.md +++ b/e2e/updater-zst.failure-modes.md @@ -26,23 +26,35 @@ Enumerated before implementation. Each case names the layer that must catch it. 1. A zstd archive whose app lacks a sidecar, or whose identity differs, must be refused by the existing completeness and identity checks. 2. A per-arch bundle for the wrong architecture must never be offered: the - feed key carries the arch, and the client asks for its own compile-time - arch (Rosetta processes ask for x86_64). + feed key carries the arch, and the client asks for its host target. 3. An arm64-only app later moved to an Intel Mac will not launch. This is accepted and documented; recovery is the universal DMG. +4. A bundle whose executable or sidecars do not support the host architecture + (for example, an arm64-only bundle on an Intel Mac, or an x86_64-only bundle + on native Apple Silicon) must be rejected before live app replacement or + backup retirement, while a translated x86_64 process under Rosetta 2 accepts + both `aarch64` and `x86_64` bundles. ## Z03: client target selection and fallback 1. A packaged macOS app asks for `darwin-{arch}-app-zst` (stable) or `darwin-beta-{arch}-app-zst` (beta). -2. If the compact feed is missing or lacks the key (a release published +2. A translated process on Apple Silicon (Rosetta) requests the native `aarch64` + target so that updates automatically migrate to native arm64 execution. +3. If the compact feed is missing or lacks the key (a release published without zst artifacts), the check must fall back to the legacy target and - still find the update. -3. A compact feed that exists and reports no newer version must not trigger + still find the update. The endpoint configuration must not mask a missing + compact feed with an installed-version manifest. +4. A compact feed that exists and reports no newer version must not trigger the fallback. -4. Clients on 5.0.x never request the compact key and keep receiving the +5. Clients on 5.0.x never request the compact key and keep receiving the universal `.app.tar.gz`. -5. Windows, Linux, and Flatpak targets must not change. +6. Windows, Linux, and Flatpak targets must not change. + +Scope: Z03.1 through Z03.6 mock `get_compact_updater_target`, so they test renderer +routing given the command's answer. The Rust target selection itself (bundle-type +gate, Rosetta sysctl, arch) is covered only by Z03.2's `sysctl.proc_translated` +probe and must be confirmed on real macOS hardware. ## Z04: release pipeline @@ -57,5 +69,10 @@ Enumerated before implementation. Each case names the layer that must catch it. 4. A missing or mismatched `.sig` must stop manifest generation. 5. Stable and beta compact manifests must be generated, validated, listed in the required beta-manifest set, and pass the live validator. -6. Compact entries must never become the generic `darwin-{arch}` fallback for - old clients. +6. Compact entries must never become the generic `darwin-{arch}` or + `darwin-beta-{arch}[-app]` fallback for old clients. +7. Per-arch input bundles in release builds must have valid Developer ID code + signatures, stapled notarization tickets, and pass Gatekeeper assessment + (`spctl`) before being repacked. +8. The E2E test harness supports a strict `--require-real-builds` mode to prevent + synthetic bundles from being accepted as final release proof. diff --git a/package.json b/package.json index bfbf745c..d1eb9b2e 100644 --- a/package.json +++ b/package.json @@ -141,7 +141,7 @@ "release:win:continue": "npm run release:session:verify && npm run release:licenses && npm run release:draft && npm run release:legacy-v4-feed && npm run rust:targets:win && npm run build:win:prepared && npm run prepare:sidecars && npm run release:sign:gpg && npm run release:finalize", "release:win:resume": "npm run prerelease:prepare && npm run release:win:continue", "release:win": "node scripts/run-release.js win", - "release:mac:continue": "npm run release:session:verify && npm run release:licenses && npm run release:wait-draft && npm run rust:targets:mac && npm run build:mac:universal:prepared && npm run build:mac:zip && npm run build:mac:updater-arches:prepared && npm run build:mac:updater-zst && npm run release:sign:gpg && npm run release:finalize", + "release:mac:continue": "npm run release:session:verify && npm run release:licenses && npm run release:wait-draft && npm run rust:targets:mac && npm run build:mac:universal:prepared && npm run build:mac:zip && npm run build:mac:updater-arches:prepared && npm run build:mac:updater-zst && node scripts/e2e-updater-zst.mjs --require-real-builds && npm run release:sign:gpg && npm run release:finalize", "release:mac:resume": "npm run prerelease:prepare && npm run release:mac:continue", "release:mac": "node scripts/run-release.js mac", "release:mac:ssh": "npm run mac:ssh:keychain && node scripts/run-release.js mac", diff --git a/run.rosie.rosi.metainfo.xml b/run.rosie.rosi.metainfo.xml index f5eb72d8..17b04966 100644 --- a/run.rosie.rosi.metainfo.xml +++ b/run.rosie.rosi.metainfo.xml @@ -41,7 +41,7 @@ - + diff --git a/scripts/check-stable-metadata-pr.mjs b/scripts/check-stable-metadata-pr.mjs index 6a676875..fc93d1e5 100644 --- a/scripts/check-stable-metadata-pr.mjs +++ b/scripts/check-stable-metadata-pr.mjs @@ -3,7 +3,10 @@ import { resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { isDeepStrictEqual } from "node:util"; import { stripSupersededPrereleases } from "./update-metainfo.js"; -import { syncChangelogForVersion } from "./sync-version-helpers.js"; +import { + macBundleVersionFromSemver, + syncChangelogForVersion, +} from "./sync-version-helpers.js"; import { validateChangelogForVersion } from "./validate-changelog-version.js"; const STABLE_METADATA_PATHS = new Set([ @@ -42,17 +45,18 @@ function parseJson(file, text) { } } -function assertJsonVersionOnly( - file, - baseText, - headText, - allowedFields, - expectedBaseVersion, - expectedHeadVersion, -) { +/** + * Each allowed field is [fieldPath, expectedBaseValue, expectedHeadValue], so + * derived values such as macOS bundleVersion get their own expectations. + */ +function assertJsonVersionOnly(file, baseText, headText, allowedFields) { const base = parseJson(file, baseText); const head = parseJson(file, headText); - for (const fieldPath of allowedFields) { + for (const [ + fieldPath, + expectedBaseValue, + expectedHeadValue, + ] of allowedFields) { let baseParent = base; let headParent = head; for (const key of fieldPath.slice(0, -1)) { @@ -67,10 +71,7 @@ function assertJsonVersionOnly( `${file} is missing the allowed version field ${fieldPath.join(".")}.`, ); } - if ( - baseValue !== expectedBaseVersion || - headValue !== expectedHeadVersion - ) { + if (baseValue !== expectedBaseValue || headValue !== expectedHeadValue) { throw new Error( `${file} has an unexpected value in ${fieldPath.join(".")}.`, ); @@ -416,25 +417,25 @@ export function validateStableMetadataChange({ } switch (file) { case "package.json": + assertJsonVersionOnly(file, change.baseText, change.headText, [ + [["version"], baseVersion, headVersion], + ]); + break; case "src-tauri/tauri.conf.json": - assertJsonVersionOnly( - file, - change.baseText, - change.headText, - [["version"]], - baseVersion, - headVersion, - ); + assertJsonVersionOnly(file, change.baseText, change.headText, [ + [["version"], baseVersion, headVersion], + [ + ["bundle", "macOS", "bundleVersion"], + macBundleVersionFromSemver(baseVersion), + macBundleVersionFromSemver(headVersion), + ], + ]); break; case "package-lock.json": - assertJsonVersionOnly( - file, - change.baseText, - change.headText, - [["version"], ["packages", "", "version"]], - baseVersion, - headVersion, - ); + assertJsonVersionOnly(file, change.baseText, change.headText, [ + [["version"], baseVersion, headVersion], + [["packages", "", "version"], baseVersion, headVersion], + ]); break; case "src-tauri/Cargo.toml": case "src-tauri/Cargo.lock": diff --git a/scripts/e2e-updater-zst.mjs b/scripts/e2e-updater-zst.mjs index fba994c9..e3e92074 100644 --- a/scripts/e2e-updater-zst.mjs +++ b/scripts/e2e-updater-zst.mjs @@ -152,12 +152,42 @@ function tauriCli(args) { }); } -/** Runs src/updater.ts against a scripted feed; returns the targets it checked. */ -async function runRendererCheck({ channel, compactTarget, feed }) { +/** + * Resolves an updater target against the generated manifests the way + * tauri-plugin-updater does with tauri.conf.json's endpoints: `{{target}}` is + * the custom target or `darwin`, `{{arch}}` is aarch64. A default target looks + * up `darwin-aarch64-app` then `darwin-aarch64`; a custom target only its key. + */ +function resolveFeed(manifests, target) { + const templateTarget = target ?? "darwin"; + const keys = target ? [target] : ["darwin-aarch64-app", "darwin-aarch64"]; + for (const name of [ + `latest-${templateTarget}-aarch64.json`, + `latest-${templateTarget}.json`, + ]) { + const platforms = manifests[name]?.platforms ?? {}; + const key = keys.find((candidate) => platforms[candidate]); + if (key) return { manifest: name, key, url: platforms[key].url }; + } + return null; +} + +/** + * Runs an updater.ts against a scripted feed; returns the targets it checked + * and the warnings it logged. `sourceText` defaults to src/updater.ts. + */ +async function runRendererCheck({ + channel, + compactTarget, + betaTarget = "darwin-beta-aarch64-app", + feed, + installedVersion = "5.1.0", + sourceText, +}) { const ts = require(path.join(root, "node_modules/typescript")); - const source = fs - .readFileSync(path.join(root, "src/updater.ts"), "utf8") - .replaceAll("import.meta.env.VITE_ROSI_E2E", "'1'"); + const source = ( + sourceText ?? fs.readFileSync(path.join(root, "src/updater.ts"), "utf8") + ).replaceAll("import.meta.env.VITE_ROSI_E2E", "'1'"); const js = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2020, @@ -165,18 +195,26 @@ async function runRendererCheck({ channel, compactTarget, feed }) { }, }).outputText; const checks = []; + const compactArgs = []; + const warnings = []; const statuses = []; const window = { __ROSI_E2E__: { updaterAdapter: { - invoke: async (command) => - ({ + invoke: async (command, args) => { + if (command === "get_compact_updater_target") { + compactArgs.push(args ?? null); + return typeof compactTarget === "function" + ? compactTarget(args) + : compactTarget; + } + return { is_packaged: true, is_flatpak: false, get_settings: { updateChannel: channel }, - get_beta_updater_target: "darwin-beta-aarch64-app", - get_compact_updater_target: compactTarget, - })[command], + get_beta_updater_target: betaTarget, + }[command]; + }, check: async (target) => { checks.push(target ?? null); const result = feed(target ?? null); @@ -199,10 +237,13 @@ async function runRendererCheck({ channel, compactTarget, feed }) { exports, require: (id) => id.includes("/app") - ? { getVersion: async () => "5.1.0" } + ? { getVersion: async () => installedVersion } : { invoke: () => {}, check: () => {} }, window, - console, + console: { + error: console.error, + warn: (...args) => warnings.push(args.join(" ")), + }, Date, Set, Object, @@ -215,6 +256,8 @@ async function runRendererCheck({ channel, compactTarget, feed }) { const error = await exports.checkForUpdates(); return { checks, + compactArgs, + warnings, error, available: statuses.find((event) => event.status === "available")?.version ?? null, @@ -236,18 +279,54 @@ async function main() { fs.mkdirSync(releaseDir); const packed = {}; const inputs = {}; + const requireRealBuilds = process.argv.includes("--require-real-builds"); try { for (const arch of Object.keys(ARCHES)) inputs[arch] = perArchInput(arch, scratch); + if (requireRealBuilds) { + await scenario( + "Z04.8", + "real per-arch builds are present (strict release proof)", + () => { + for (const arch of Object.keys(ARCHES)) { + assert.equal( + inputs[arch].source, + "tauri-per-arch-build", + `missing real per-arch build for ${arch}`, + ); + } + }, + ); + for (const arch of Object.keys(ARCHES)) { + await scenario( + `Z04.7-${arch}`, + `real per-arch bundle for ${arch} passes codesign, stapler, and spctl`, + () => { + assertPerArchBundle(inputs[arch].path, arch, { + verifySignature: true, + }); + }, + ); + } + } + await scenario( "Z04.2", - "packer refuses a universal bundle as a per-arch input", + "packer refuses universal or wrong-arch bundles as per-arch input", () => { assert.throws( () => assertPerArchBundle(universalArchive, "aarch64"), /expected "arm64"/, ); + assert.throws( + () => assertPerArchBundle(inputs.x86_64.path, "aarch64"), + /expected "arm64"/, + ); + assert.throws( + () => assertPerArchBundle(inputs.aarch64.path, "x86_64"), + /expected "x86_64"/, + ); }, ); @@ -352,6 +431,17 @@ async function main() { for (const key of [`darwin-${arch}`, `darwin-${arch}-app`]) { assert.match(generic[key].url, /\/ROSI\.app\.tar\.gz$/, key); } + for (const betaKey of [ + `darwin-beta-${arch}`, + `darwin-beta-${arch}-app`, + ]) { + const betaPlatforms = manifests[`latest-${betaKey}.json`].platforms; + assert.match( + betaPlatforms[betaKey].url, + /\/ROSI\.app\.tar\.gz$/, + betaKey, + ); + } } }, ); @@ -385,6 +475,7 @@ async function main() { }, ); + let archMatrix = {}; await scenario( "Z01/Z02", "vendored plugin extracts real archives into complete bundles", @@ -397,6 +488,7 @@ async function main() { "cargo", [ "test", + "--locked", "--manifest-path", "src-tauri/vendor/tauri-plugin-updater/Cargo.toml", "--lib", @@ -413,15 +505,51 @@ async function main() { }, }, ); + const matches = [ + ...output.matchAll( + /ROSI_UPDATER_ZST_E2E (\S+) extract_ms=(\d+) aarch64=(true|false) x86_64=(true|false) rosetta=(true|false)/g, + ), + ]; const extractMs = Object.fromEntries( - [ - ...output.matchAll(/ROSI_UPDATER_ZST_E2E (\S+) extract_ms=(\d+)/g), - ].map((m) => [path.basename(m[1]), Number(m[2])]), + matches.map((m) => [path.basename(m[1]), Number(m[2])]), + ); + archMatrix = Object.fromEntries( + matches.map((m) => [ + path.basename(m[1]), + { + aarch64: m[3] === "true", + x86_64: m[4] === "true", + rosetta: m[5] === "true", + }, + ]), ); assert.equal(Object.keys(extractMs).length, archives.length); const passed = output.match(/test result: ok\. (\d+) passed/); assert.ok(passed, "plugin archive tests did not pass"); - return { pluginTestsPassed: Number(passed[1]), extractMs }; + return { pluginTestsPassed: Number(passed[1]), extractMs, archMatrix }; + }, + ); + + await scenario( + "Z02.4", + "vendored updater rejects staged wrong-arch bundles and accepts host/Rosetta bundles", + () => { + assert.deepEqual(archMatrix["ROSI.app.tar.gz"], { + aarch64: true, + x86_64: true, + rosetta: true, + }); + assert.deepEqual(archMatrix["ROSI-aarch64.app.tar.zst"], { + aarch64: true, + x86_64: false, + rosetta: true, + }); + assert.deepEqual(archMatrix["ROSI-x86_64.app.tar.zst"], { + aarch64: false, + x86_64: true, + rosetta: true, + }); + return archMatrix; }, ); @@ -435,6 +563,9 @@ async function main() { feed: () => "9.0.0", }); assert.deepEqual(result.checks, ["darwin-aarch64-app-zst"]); + // The channel is re-read before and after the feed request. + assert.ok(result.compactArgs.length > 0); + assert.ok(result.compactArgs.every((args) => args.beta === false)); assert.equal(result.available, "9.0.0"); return result; }, @@ -442,6 +573,50 @@ async function main() { await scenario( "Z03.2", + "renderer routes the native aarch64 target the command returns under Rosetta (command mocked)", + async () => { + const rosettaTarget = (args) => + args?.beta ? "darwin-beta-aarch64-app-zst" : "darwin-aarch64-app-zst"; + const stable = await runRendererCheck({ + channel: "stable", + compactTarget: rosettaTarget, + feed: () => "9.0.0", + }); + assert.deepEqual(stable.checks, ["darwin-aarch64-app-zst"]); + assert.ok(stable.compactArgs.every((args) => args.beta === false)); + assert.equal(stable.available, "9.0.0"); + const beta = await runRendererCheck({ + channel: "beta", + compactTarget: rosettaTarget, + feed: () => "9.0.0-beta.1", + }); + assert.deepEqual(beta.checks, ["darwin-beta-aarch64-app-zst"]); + assert.ok(beta.compactArgs.every((args) => args.beta === true)); + assert.equal(beta.available, "9.0.0-beta.1"); + assert.equal(archMatrix["ROSI-aarch64.app.tar.zst"]?.rosetta, true); + let rosettaSysctl = "skipped"; + if (os.arch() === "arm64") { + const probe = spawnSync( + "arch", + ["-x86_64", "/usr/sbin/sysctl", "-n", "sysctl.proc_translated"], + { encoding: "utf8" }, + ); + if (probe.status === 0) { + rosettaSysctl = probe.stdout.trim(); + assert.equal(rosettaSysctl, "1"); + } + } + return { + stable: stable.checks, + beta: beta.checks, + rosettaMachOAccepted: archMatrix["ROSI-aarch64.app.tar.zst"]?.rosetta, + rosettaSysctl, + }; + }, + ); + + await scenario( + "Z03.3", "missing compact feed falls back to the legacy target", async () => { const missing = new Error( @@ -452,22 +627,36 @@ async function main() { compactTarget: "darwin-aarch64-app-zst", feed: (target) => (target ? missing : "9.0.0"), }); - assert.equal(stable.checks.at(-1), null); + // The compact check is not retried in place; the legacy target is the retry. + assert.deepEqual(stable.checks, ["darwin-aarch64-app-zst", null]); assert.equal(stable.available, "9.0.0"); + assert.equal(stable.warnings.length, 1); + assert.match( + stable.warnings[0], + /darwin-aarch64-app-zst check failed, falling back to the default target: Could not fetch/, + ); const beta = await runRendererCheck({ channel: "beta", compactTarget: "darwin-beta-aarch64-app-zst", feed: (target) => target.endsWith("-zst") ? missing : "9.0.0-beta.1", }); - assert.equal(beta.checks.at(-1), "darwin-beta-aarch64-app"); + assert.deepEqual(beta.checks, [ + "darwin-beta-aarch64-app-zst", + "darwin-beta-aarch64-app", + ]); assert.equal(beta.available, "9.0.0-beta.1"); + assert.equal(beta.warnings.length, 1); + assert.match( + beta.warnings[0], + /darwin-beta-aarch64-app-zst check failed, falling back to darwin-beta-aarch64-app target/, + ); return { stable, beta }; }, ); await scenario( - "Z03.3", + "Z03.4", "compact feed reporting no update does not fall back", async () => { const result = await runRendererCheck({ @@ -479,13 +668,62 @@ async function main() { result.checks.every((target) => target === "darwin-aarch64-app-zst"), ); assert.equal(result.available, null); + assert.deepEqual(result.warnings, []); return result; }, ); await scenario( "Z03.5", - "non-macOS builds keep their existing targets", + "clients on 5.0.x never request the compact key", + async () => { + // The real 5.0.2 renderer. Its command would answer with a compact key, + // and the 5.0.2 renderer must still never ask for one. + const sourceText = run("git", ["show", "v5.0.2:src/updater.ts"], { + cwd: root, + }); + const stable = await runRendererCheck({ + channel: "auto", + compactTarget: "darwin-aarch64-app-zst", + installedVersion: "5.0.2", + sourceText, + feed: (target) => (resolveFeed(manifests, target) ? "9.0.0" : null), + }); + assert.deepEqual(stable.compactArgs, []); + assert.ok(stable.checks.every((target) => target === null)); + assert.equal(stable.available, "9.0.0"); + const stableFeed = resolveFeed(manifests, null); + assert.equal(stableFeed?.manifest, "latest-darwin-aarch64.json"); + assert.equal(stableFeed?.key, "darwin-aarch64-app"); + assert.match(stableFeed?.url ?? "", /\/ROSI\.app\.tar\.gz$/); + + const beta = await runRendererCheck({ + channel: "auto", + compactTarget: "darwin-beta-aarch64-app-zst", + installedVersion: "5.0.2-beta.1", + sourceText, + feed: (target) => + resolveFeed(manifests, target) ? "9.0.0-beta.1" : null, + }); + assert.deepEqual(beta.compactArgs, []); + assert.ok( + beta.checks.every((target) => target === "darwin-beta-aarch64-app"), + ); + assert.equal(beta.available, "9.0.0-beta.1"); + const betaFeed = resolveFeed(manifests, "darwin-beta-aarch64-app"); + assert.equal(betaFeed?.manifest, "latest-darwin-beta-aarch64-app.json"); + assert.equal(betaFeed?.key, "darwin-beta-aarch64-app"); + assert.match(betaFeed?.url ?? "", /\/ROSI\.app\.tar\.gz$/); + return { + stable: { checks: stable.checks, feed: stableFeed }, + beta: { checks: beta.checks, feed: betaFeed }, + }; + }, + ); + + await scenario( + "Z03.6", + "renderer keeps existing targets when the command returns no compact target (non-macOS)", async () => { const stable = await runRendererCheck({ channel: "stable", diff --git a/scripts/pack-macos-updater-zst.js b/scripts/pack-macos-updater-zst.js index 30c4a219..507a7851 100644 --- a/scripts/pack-macos-updater-zst.js +++ b/scripts/pack-macos-updater-zst.js @@ -15,6 +15,7 @@ import { spawn, spawnSync } from "child_process"; import { Transform, Writable } from "stream"; import { pipeline } from "stream/promises"; import { fileURLToPath } from "url"; +import { isDeepStrictEqual } from "util"; import zlib from "zlib"; import { isDirectExecutionOf } from "./direct-execution.mjs"; import { verifyReleaseSession } from "./release-session.js"; @@ -76,8 +77,104 @@ function compactArchiveName(arch) { return `ROSI-${arch}.app.tar.zst`; } -/** Z04.2: one top-level ROSI.app, and executables built for `arch`. */ -function assertPerArchBundle(input, arch) { +function compareVersions(left, right) { + const leftParts = left.split(".").map(Number); + const rightParts = right.split(".").map(Number); + const length = Math.max(leftParts.length, rightParts.length); + for (let index = 0; index < length; index += 1) { + const delta = (leftParts[index] ?? 0) - (rightParts[index] ?? 0); + if (delta !== 0) return Math.sign(delta); + } + return 0; +} + +function parseMachOMinimumVersion(otoolOutput) { + const buildVersion = otoolOutput.match( + /cmd LC_BUILD_VERSION[\s\S]*?\bminos\s+(\d+(?:\.\d+)*)/, + ); + if (buildVersion?.[1]) return buildVersion[1]; + const legacy = otoolOutput.match( + /cmd LC_VERSION_MIN_MACOSX[\s\S]*?\bversion\s+(\d+(?:\.\d+)*)/, + ); + return legacy?.[1] ?? null; +} + +function readMachOMinimumVersion(binary, arch) { + const output = run("otool", ["-arch", arch, "-l", binary]); + const minimum = parseMachOMinimumVersion(output); + if (!minimum) { + throw new Error( + `Could not read the minimum macOS version for ${binary} (${arch})`, + ); + } + return minimum; +} + +function readEntitlementsTemplate(templatePath) { + return JSON.parse( + run("plutil", ["-convert", "json", "-o", "-", templatePath]), + ); +} + +function verifySignedEntitlements(targetPath, expected) { + const temporaryDirectory = fs.mkdtempSync( + path.join(os.tmpdir(), "rosi-entitlements-"), + ); + const plistPath = path.join(temporaryDirectory, "entitlements.plist"); + try { + const inspection = spawnSync( + "codesign", + ["--display", "--entitlements", plistPath, "--xml", targetPath], + { encoding: "utf8" }, + ); + if (inspection.error || inspection.status !== 0) { + throw ( + inspection.error ?? + new Error( + `Could not inspect entitlements for ${targetPath}: ${inspection.stderr}`, + ) + ); + } + const actual = fs.existsSync(plistPath) + ? JSON.parse(run("plutil", ["-convert", "json", "-o", "-", plistPath])) + : {}; + if (!isDeepStrictEqual(actual, expected)) { + throw new Error( + `Unexpected signed entitlements for ${targetPath}: ${JSON.stringify(actual)}`, + ); + } + } finally { + fs.rmSync(temporaryDirectory, { recursive: true, force: true }); + } +} + +function verifyDeveloperIdSignature(targetPath, label) { + const inspection = spawnSync( + "codesign", + ["--display", "--verbose=4", targetPath], + { encoding: "utf8" }, + ); + if (inspection.error || inspection.status !== 0) { + throw inspection.error ?? new Error(inspection.stderr); + } + const details = `${inspection.stdout}${inspection.stderr}`; + if ( + /Signature=adhoc/i.test(details) || + !/Authority=Developer ID Application:/i.test(details) + ) { + throw new Error( + `${label} is not signed with a Developer ID Application certificate.`, + ); + } + const teamIdentifier = details.match(/^TeamIdentifier=(.+)$/m)?.[1]?.trim(); + if (!teamIdentifier || teamIdentifier === "not set") { + throw new Error(`${label} signature has no TeamIdentifier.`); + } + return teamIdentifier; +} + +/** Z04.2: one top-level ROSI.app, and executables built for `arch`. Z04.7: code sign & staple. */ +function assertPerArchBundle(input, arch, { verifySignature = false } = {}) { const members = run("tar", ["-tzf", input], { maxBuffer: 64 * 1024 * 1024 }) .split("\n") .filter(Boolean); @@ -89,14 +186,7 @@ function assertPerArchBundle(input, arch) { } const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "rosi-updater-zst-")); try { - run("tar", [ - "-xzf", - input, - "-C", - scratch, - ...THIN_MEMBERS, - ...MULTI_ARCH_MEMBERS, - ]); + run("tar", ["-xzf", input, "-C", scratch]); const expected = ARCHES[arch].lipoArch; for (const member of [...THIN_MEMBERS, ...MULTI_ARCH_MEMBERS]) { const archs = run("lipo", ["-archs", path.join(scratch, member)]).trim(); @@ -107,6 +197,98 @@ function assertPerArchBundle(input, arch) { ); } } + if (verifySignature) { + const appPath = path.join(scratch, "ROSI.app"); + const tauriConfig = JSON.parse( + fs.readFileSync( + path.join(root, "src-tauri", "tauri.conf.json"), + "utf8", + ), + ); + const requiredMacOS = tauriConfig.bundle?.macOS?.minimumSystemVersion; + const expectedBundleVersion = tauriConfig.bundle?.macOS?.bundleVersion; + const marketingMatch = tauriConfig.version?.match( + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-beta\.(?:0|[1-9]\d*))?$/, + ); + const expectedMarketingVersion = marketingMatch + ? `${marketingMatch[1]}.${marketingMatch[2]}.${marketingMatch[3]}` + : undefined; + if ( + !requiredMacOS || + !expectedBundleVersion || + !expectedMarketingVersion + ) { + throw new Error( + "tauri.conf.json must define a supported version, bundle.macOS.minimumSystemVersion, and bundleVersion", + ); + } + + const infoPlist = path.join(appPath, "Contents", "Info.plist"); + const bundleVersion = run("/usr/libexec/PlistBuddy", [ + "-c", + "Print:CFBundleVersion", + infoPlist, + ]).trim(); + if (!/^\d+(?:\.\d+){0,2}$/.test(bundleVersion)) { + throw new Error(`CFBundleVersion must be numeric: ${bundleVersion}`); + } + if (bundleVersion !== expectedBundleVersion) { + throw new Error( + `CFBundleVersion ${bundleVersion} does not match configured ${expectedBundleVersion}`, + ); + } + const marketingVersion = run("/usr/libexec/PlistBuddy", [ + "-c", + "Print:CFBundleShortVersionString", + infoPlist, + ]).trim(); + if (marketingVersion !== expectedMarketingVersion) { + throw new Error( + `CFBundleShortVersionString ${marketingVersion} does not match expected ${expectedMarketingVersion}`, + ); + } + + for (const member of [...THIN_MEMBERS, ...MULTI_ARCH_MEMBERS]) { + const fullMember = path.join(scratch, member); + const minos = readMachOMinimumVersion(fullMember, expected); + if (compareVersions(minos, requiredMacOS) > 0) { + throw new Error( + `${member} (${expected}) requires macOS ${minos}, above ROSI's declared ${requiredMacOS} floor`, + ); + } + } + + run("codesign", [ + "--verify", + "--deep", + "--strict", + "--verbose=2", + appPath, + ]); + const hostTeam = verifyDeveloperIdSignature(appPath, "macOS app"); + const hostEntitlements = readEntitlementsTemplate( + path.join(root, "src-tauri", "entitlements.plist"), + ); + verifySignedEntitlements(appPath, hostEntitlements); + for (const member of [...THIN_MEMBERS, ...MULTI_ARCH_MEMBERS].filter( + (m) => !m.endsWith("/rosi"), + )) { + const fullMember = path.join(scratch, member); + verifySignedEntitlements(fullMember, hostEntitlements); + const sidecarTeam = verifyDeveloperIdSignature( + fullMember, + `${path.basename(member)} sidecar`, + ); + if (sidecarTeam !== hostTeam) { + throw new Error( + `${member} TeamIdentifier ${sidecarTeam} does not match host ${hostTeam}`, + ); + } + } + + run("xcrun", ["stapler", "validate", appPath]); + run("spctl", ["--assess", "--type", "execute", "--verbose=2", appPath]); + } } finally { fs.rmSync(scratch, { recursive: true, force: true }); } @@ -212,11 +394,12 @@ async function packMacosUpdaterArchive({ version, outputDir, sign = true, + verifySignature = sign, }) { if (!ARCHES[arch]) throw new Error(`unsupported macOS arch: ${arch}`); if (!fs.existsSync(input)) throw new Error(`missing per-arch updater archive: ${input}`); - assertPerArchBundle(input, arch); + assertPerArchBundle(input, arch, { verifySignature }); const output = path.join( outputDir ?? path.dirname(input), diff --git a/scripts/release-preflight.js b/scripts/release-preflight.js index 52779269..4cc108b6 100644 --- a/scripts/release-preflight.js +++ b/scripts/release-preflight.js @@ -41,12 +41,27 @@ function git(args) { }).trimEnd(); } +function assertZstdRunnable() { + try { + execFileSync("zstd", ["--version"], { stdio: "ignore" }); + } catch { + throw new Error( + "zstd was not found or cannot run. Install it with: brew install zstd", + ); + } +} + /** * Release source checks: the right branch, a clean tree, and HEAD pushed to * its upstream. Hosted CI is not required here; it runs on pushes but does * not gate releases. */ function runPreflight() { + // macOS updater archives need the zstd CLI; fail before any mac build starts. + if (process.platform === "darwin") { + assertZstdRunnable(); + } + const version = String(packageJson.version ?? ""); const expectedBranch = expectedReleaseBranch(version); const branch = git(["branch", "--show-current"]); diff --git a/scripts/round2-release-updater.test.mjs b/scripts/round2-release-updater.test.mjs index 3240396c..436b9c67 100644 --- a/scripts/round2-release-updater.test.mjs +++ b/scripts/round2-release-updater.test.mjs @@ -9,7 +9,10 @@ import { fileURLToPath } from "node:url"; import { createRequire } from "node:module"; import { copyBundledNotices } from "./copy-bundled-licenses.js"; import { validateStableMetadataChange } from "./check-stable-metadata-pr.mjs"; -import { syncChangelogForVersion } from "./sync-version-helpers.js"; +import { + macBundleVersionFromSemver, + syncChangelogForVersion, +} from "./sync-version-helpers.js"; import { run as updateMetainfo } from "./update-metainfo.js"; import { validateChangelogForVersion } from "./validate-changelog-version.js"; import { @@ -55,7 +58,10 @@ function metadataFiles() { "src-tauri/tauri.conf.json": json({ productName: "ROSI", version: beta, - bundle: { resources: {} }, + bundle: { + resources: {}, + macOS: { bundleVersion: macBundleVersionFromSemver(beta) }, + }, }), "CHANGELOG.md": `# ROSI\n\n## Changes in \`v${beta}:\`\n\n- Beta notes.\n`, "run.rosie.rosi.metainfo.xml": `\n run.rosie.rosi.desktop\n https://example.invalid/rosi\n \n \n \n \n \n\n`, @@ -88,6 +94,10 @@ function metadataFiles() { head["src-tauri/tauri.conf.json"] = json({ ...JSON.parse(base["src-tauri/tauri.conf.json"]), version: stable, + bundle: { + resources: {}, + macOS: { bundleVersion: macBundleVersionFromSemver(stable) }, + }, }); head["CHANGELOG.md"] = `# ROSI\n\n## Changes in \`v${stable}:\`\n\n- Stable notes.\n\n${base["CHANGELOG.md"]}`; @@ -162,6 +172,14 @@ function realStablePromotionFixture() { .replaceAll(stable, stableVersion); } } + for (const [files, version] of [ + [base, betaVersion], + [head, stableVersion], + ]) { + const conf = JSON.parse(files["src-tauri/tauri.conf.json"]); + conf.bundle.macOS.bundleVersion = macBundleVersionFromSemver(version); + files["src-tauri/tauri.conf.json"] = json(conf); + } const betaCallout = /^> \[!NOTE\]\r?\n> 🅱️ This is a Beta build\.\r?\n(?:\r?\n)?/mu; diff --git a/scripts/validate-updater-live.js b/scripts/validate-updater-live.js index 385171dd..218c8e63 100644 --- a/scripts/validate-updater-live.js +++ b/scripts/validate-updater-live.js @@ -26,6 +26,7 @@ import path from "path"; import { fileURLToPath, pathToFileURL } from "url"; import { spawnSync } from "child_process"; import { verifyUpdaterSignatures } from "./updater-signature-verifier.js"; +import { resolveUpdaterTargets } from "./gpg-sign.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const root = path.join(__dirname, ".."); @@ -264,7 +265,12 @@ export function resolveLiveUpdaterTargets(name) { ) { return []; } - if (/\.(exe|msi|dmg|flatpak|appimage|zip)$/i.test(name)) { + // Manifests also reference macOS .app.tar.gz / .app.tar.zst archives, which + // only gpg-sign's resolver knows about. + if ( + /\.(exe|msi|dmg|flatpak|appimage|zip)$/i.test(name) || + resolveUpdaterTargets(name).length > 0 + ) { return [{ os: "live", arch: "artifact" }]; } return []; diff --git a/scripts/validate-updater-manifest.js b/scripts/validate-updater-manifest.js index 7050fd9f..2c145c92 100644 --- a/scripts/validate-updater-manifest.js +++ b/scripts/validate-updater-manifest.js @@ -65,6 +65,28 @@ function hasMinisignEnvelope(value) { ); } +// Only a line starting with the exact "trusted comment: " prefix counts; the +// untrusted comment line also contains "trusted comment:" as a substring. +function minisignTrustedComment(value) { + const outer = decodeStrictBase64(value); + if (!outer) return null; + const line = outer + .toString("utf8") + .trim() + .split(/\r?\n/) + .find((entry) => entry.startsWith("trusted comment: ")); + return line === undefined ? null : line.slice("trusted comment: ".length); +} + +// Tauri writes tab-separated key:value fields, e.g. +// timestamp:1700000000\tfile:ROSI.app.tar.gz\tversion:5.0.2. +function minisignSignedVersion(value) { + const comment = minisignTrustedComment(value); + if (comment === null) return null; + const field = comment.split("\t").find((part) => part.startsWith("version:")); + return field === undefined ? null : field.slice("version:".length); +} + export function validateManifestData(data, filePath) { const problems = []; const fail = (message) => problems.push(message); @@ -196,6 +218,19 @@ export function validateManifestData(data, filePath) { fail( `${filePath}: platforms.${key}.signature must be a base64-encoded minisign envelope`, ); + } else { + // tauri.conf.json sets requireSignedVersion, so the signed version must + // be present and must match the manifest it is served under. + const signedVersion = minisignSignedVersion(platform.signature); + if (signedVersion === null) { + fail( + `${filePath}: platforms.${key}.signature has no version: field in its trusted comment`, + ); + } else if (signedVersion !== data.version) { + fail( + `${filePath}: platforms.${key}.signature is signed for version ${signedVersion}, manifest version is ${data.version}`, + ); + } } } return problems; diff --git a/scripts/verify-release-draft.js b/scripts/verify-release-draft.js index 412c9557..fb8e2cb9 100644 --- a/scripts/verify-release-draft.js +++ b/scripts/verify-release-draft.js @@ -77,10 +77,24 @@ export function requiredDraftInstallerNames({ return names; } +// macOS updater archives are not installers, but each one ships with the same +// minisign `.sig` and GPG `.asc` sidecars and must be listed in a SHA256SUMS. +export function requiredDraftUpdaterArchiveNames() { + return [ + "ROSI.app.tar.gz", + "ROSI-aarch64.app.tar.zst", + "ROSI-x86_64.app.tar.zst", + ]; +} + export function requiredDraftSidecarNames(installers) { return installers.flatMap((name) => { const names = [`${name}.asc`]; - if (/\.exe$/i.test(name) || /\.AppImage$/i.test(name)) { + if ( + /\.exe$/i.test(name) || + /\.AppImage$/i.test(name) || + /\.app\.tar\.(?:gz|zst)$/i.test(name) + ) { names.unshift(`${name}.sig`); } return names; @@ -366,10 +380,12 @@ export function verifyGpgDetachedSignature({ export function requiredDraftAssetNames(options = {}) { const requireLinuxAarch64 = Boolean(options.requireLinuxAarch64); const installers = requiredDraftInstallerNames({ requireLinuxAarch64 }); + const updaterArchives = requiredDraftUpdaterArchiveNames(); return Array.from( new Set([ ...installers, - ...requiredDraftSidecarNames(installers), + ...updaterArchives, + ...requiredDraftSidecarNames([...installers, ...updaterArchives]), ...requiredDraftChecksumNames({ requireLinuxAarch64 }), ...requiredDraftStableManifestNames({ requireLinuxAarch64 }), ...requiredDraftBetaManifestNames({ requireLinuxAarch64 }), @@ -678,7 +694,10 @@ async function verifyDraftGpgAndChecksums({ } assetsByName.set(asset.name, asset); } - const installers = requiredDraftInstallerNames({ requireLinuxAarch64 }); + const signedNames = [ + ...requiredDraftInstallerNames({ requireLinuxAarch64 }), + ...requiredDraftUpdaterArchiveNames(), + ]; const requiredChecksumNames = requiredDraftChecksumNames({ requireLinuxAarch64, }) @@ -703,7 +722,7 @@ async function verifyDraftGpgAndChecksums({ ); } const expectedSignatureNames = [ - ...requiredDraftSidecarNames(installers).filter((name) => + ...requiredDraftSidecarNames(signedNames).filter((name) => name.endsWith(".asc"), ), ...checksumNames.map((name) => `${name}.asc`), @@ -773,7 +792,7 @@ async function verifyDraftGpgAndChecksums({ for (const payloadName of listed) covered.add(payloadName); } const requiredPayloadNames = [ - ...installers, + ...signedNames, ...requiredDraftStableManifestNames({ requireLinuxAarch64 }), ...requiredDraftBetaManifestNames({ requireLinuxAarch64 }), ]; diff --git a/src-tauri/gen/schemas/linux-schema.json b/src-tauri/gen/schemas/linux-schema.json index 4018a152..c8e4edfd 100644 --- a/src-tauri/gen/schemas/linux-schema.json +++ b/src-tauri/gen/schemas/linux-schema.json @@ -410,6 +410,30 @@ "const": "allow-download-video", "markdownDescription": "Enables the download_video command without any pre-configured scope." }, + { + "description": "Enables the e2e_cancel_close_request command without any pre-configured scope.", + "type": "string", + "const": "allow-e2e-cancel-close-request", + "markdownDescription": "Enables the e2e_cancel_close_request command without any pre-configured scope." + }, + { + "description": "Enables the e2e_emit_stale_download_events command without any pre-configured scope.", + "type": "string", + "const": "allow-e2e-emit-stale-download-events", + "markdownDescription": "Enables the e2e_emit_stale_download_events command without any pre-configured scope." + }, + { + "description": "Enables the e2e_network_pipelining_probe command without any pre-configured scope.", + "type": "string", + "const": "allow-e2e-network-pipelining-probe", + "markdownDescription": "Enables the e2e_network_pipelining_probe command without any pre-configured scope." + }, + { + "description": "Enables the e2e_updater_install_probe command without any pre-configured scope.", + "type": "string", + "const": "allow-e2e-updater-install-probe", + "markdownDescription": "Enables the e2e_updater_install_probe command without any pre-configured scope." + }, { "description": "Enables the export_settings command without any pre-configured scope.", "type": "string", @@ -428,6 +452,12 @@ "const": "allow-get-beta-updater-target", "markdownDescription": "Enables the get_beta_updater_target command without any pre-configured scope." }, + { + "description": "Enables the get_compact_updater_target command without any pre-configured scope.", + "type": "string", + "const": "allow-get-compact-updater-target", + "markdownDescription": "Enables the get_compact_updater_target command without any pre-configured scope." + }, { "description": "Enables the get_default_settings command without any pre-configured scope.", "type": "string", @@ -656,6 +686,30 @@ "const": "deny-download-video", "markdownDescription": "Denies the download_video command without any pre-configured scope." }, + { + "description": "Denies the e2e_cancel_close_request command without any pre-configured scope.", + "type": "string", + "const": "deny-e2e-cancel-close-request", + "markdownDescription": "Denies the e2e_cancel_close_request command without any pre-configured scope." + }, + { + "description": "Denies the e2e_emit_stale_download_events command without any pre-configured scope.", + "type": "string", + "const": "deny-e2e-emit-stale-download-events", + "markdownDescription": "Denies the e2e_emit_stale_download_events command without any pre-configured scope." + }, + { + "description": "Denies the e2e_network_pipelining_probe command without any pre-configured scope.", + "type": "string", + "const": "deny-e2e-network-pipelining-probe", + "markdownDescription": "Denies the e2e_network_pipelining_probe command without any pre-configured scope." + }, + { + "description": "Denies the e2e_updater_install_probe command without any pre-configured scope.", + "type": "string", + "const": "deny-e2e-updater-install-probe", + "markdownDescription": "Denies the e2e_updater_install_probe command without any pre-configured scope." + }, { "description": "Denies the export_settings command without any pre-configured scope.", "type": "string", @@ -674,6 +728,12 @@ "const": "deny-get-beta-updater-target", "markdownDescription": "Denies the get_beta_updater_target command without any pre-configured scope." }, + { + "description": "Denies the get_compact_updater_target command without any pre-configured scope.", + "type": "string", + "const": "deny-get-compact-updater-target", + "markdownDescription": "Denies the get_compact_updater_target command without any pre-configured scope." + }, { "description": "Denies the get_default_settings command without any pre-configured scope.", "type": "string", @@ -872,6 +932,12 @@ "const": "core:app:allow-default-window-icon", "markdownDescription": "Enables the default_window_icon command without any pre-configured scope." }, + { + "description": "Enables the exit command without any pre-configured scope.", + "type": "string", + "const": "core:app:allow-exit", + "markdownDescription": "Enables the exit command without any pre-configured scope." + }, { "description": "Enables the fetch_data_store_identifiers command without any pre-configured scope.", "type": "string", @@ -962,6 +1028,12 @@ "const": "core:app:deny-default-window-icon", "markdownDescription": "Denies the default_window_icon command without any pre-configured scope." }, + { + "description": "Denies the exit command without any pre-configured scope.", + "type": "string", + "const": "core:app:deny-exit", + "markdownDescription": "Denies the exit command without any pre-configured scope." + }, { "description": "Denies the fetch_data_store_identifiers command without any pre-configured scope.", "type": "string", @@ -2222,6 +2294,12 @@ "const": "core:window:allow-set-fullscreen", "markdownDescription": "Enables the set_fullscreen command without any pre-configured scope." }, + { + "description": "Enables the set_fullscreen_on_monitor command without any pre-configured scope.", + "type": "string", + "const": "core:window:allow-set-fullscreen-on-monitor", + "markdownDescription": "Enables the set_fullscreen_on_monitor command without any pre-configured scope." + }, { "description": "Enables the set_icon command without any pre-configured scope.", "type": "string", @@ -2690,6 +2768,12 @@ "const": "core:window:deny-set-fullscreen", "markdownDescription": "Denies the set_fullscreen command without any pre-configured scope." }, + { + "description": "Denies the set_fullscreen_on_monitor command without any pre-configured scope.", + "type": "string", + "const": "core:window:deny-set-fullscreen-on-monitor", + "markdownDescription": "Denies the set_fullscreen_on_monitor command without any pre-configured scope." + }, { "description": "Denies the set_icon command without any pre-configured scope.", "type": "string", @@ -2919,10 +3003,10 @@ "markdownDescription": "Denies the save command without any pre-configured scope." }, { - "description": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`", + "description": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`", "type": "string", "const": "notification:default", - "markdownDescription": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`" + "markdownDescription": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`" }, { "description": "Enables the batch command without any pre-configured scope.", @@ -3008,6 +3092,12 @@ "const": "notification:allow-remove-active", "markdownDescription": "Enables the remove_active command without any pre-configured scope." }, + { + "description": "Enables the remove_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-remove-listener", + "markdownDescription": "Enables the remove_listener command without any pre-configured scope." + }, { "description": "Enables the request_permission command without any pre-configured scope.", "type": "string", @@ -3104,6 +3194,12 @@ "const": "notification:deny-remove-active", "markdownDescription": "Denies the remove_active command without any pre-configured scope." }, + { + "description": "Denies the remove_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-remove-listener", + "markdownDescription": "Denies the remove_listener command without any pre-configured scope." + }, { "description": "Denies the request_permission command without any pre-configured scope.", "type": "string", diff --git a/src-tauri/gen/schemas/windows-schema.json b/src-tauri/gen/schemas/windows-schema.json index 7a0a3b48..c8e4edfd 100644 --- a/src-tauri/gen/schemas/windows-schema.json +++ b/src-tauri/gen/schemas/windows-schema.json @@ -452,6 +452,12 @@ "const": "allow-get-beta-updater-target", "markdownDescription": "Enables the get_beta_updater_target command without any pre-configured scope." }, + { + "description": "Enables the get_compact_updater_target command without any pre-configured scope.", + "type": "string", + "const": "allow-get-compact-updater-target", + "markdownDescription": "Enables the get_compact_updater_target command without any pre-configured scope." + }, { "description": "Enables the get_default_settings command without any pre-configured scope.", "type": "string", @@ -722,6 +728,12 @@ "const": "deny-get-beta-updater-target", "markdownDescription": "Denies the get_beta_updater_target command without any pre-configured scope." }, + { + "description": "Denies the get_compact_updater_target command without any pre-configured scope.", + "type": "string", + "const": "deny-get-compact-updater-target", + "markdownDescription": "Denies the get_compact_updater_target command without any pre-configured scope." + }, { "description": "Denies the get_default_settings command without any pre-configured scope.", "type": "string", diff --git a/src-tauri/src/platform.rs b/src-tauri/src/platform.rs index bc0bbfe8..17c6226d 100644 --- a/src-tauri/src/platform.rs +++ b/src-tauri/src/platform.rs @@ -32,6 +32,28 @@ pub fn get_distribution_channel() -> &'static str { distribution_channel() } +#[cfg(target_os = "macos")] +fn is_rosetta_translated() -> bool { + let mut ret: libc::c_int = 0; + let mut size: libc::size_t = std::mem::size_of_val(&ret); + let name = c"sysctl.proc_translated"; + let res = unsafe { + libc::sysctlbyname( + name.as_ptr(), + &mut ret as *mut _ as *mut libc::c_void, + &mut size, + std::ptr::null_mut(), + 0, + ) + }; + res == 0 && ret == 1 +} + +#[cfg(not(target_os = "macos"))] +fn is_rosetta_translated() -> bool { + false +} + #[tauri::command] pub fn get_beta_updater_target() -> String { use tauri::utils::config::BundleType; @@ -41,10 +63,14 @@ pub fn get_beta_updater_target() -> String { "macos" => "darwin", other => other, }; - let arch = match std::env::consts::ARCH { - "x86" => "i686", - "arm64" => "aarch64", - other => other, + let arch = if is_rosetta_translated() { + "aarch64" + } else { + match std::env::consts::ARCH { + "x86" => "i686", + "arm64" => "aarch64", + other => other, + } }; let installer = match tauri::utils::platform::bundle_type() { Some(BundleType::Deb) => Some("deb"), @@ -76,10 +102,15 @@ pub fn get_compact_updater_target(beta: bool) -> Option { { return None; } - // Compile-time arch: a Rosetta process asks for the x86_64 bundle. - let arch = match std::env::consts::ARCH { - arch @ ("aarch64" | "x86_64") => arch, - _ => return None, + // Target arch: an x86_64 process running under Rosetta translation requests + // the native aarch64 bundle so the update migrates to native execution. + let arch = if is_rosetta_translated() { + "aarch64" + } else { + match std::env::consts::ARCH { + arch @ ("aarch64" | "x86_64") => arch, + _ => return None, + } }; let channel = if beta { "-beta" } else { "" }; Some(format!("darwin{channel}-{arch}-app-zst")) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 75eb5f90..1d619b05 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -108,11 +108,10 @@ "updater": { "endpoints": [ "https://github.com/BurntToasters/ROSI/releases/latest/download/latest-{{target}}-{{arch}}.json", - "https://github.com/BurntToasters/ROSI/releases/latest/download/latest-{{target}}.json", - "https://github.com/BurntToasters/ROSI/releases/download/v{{current_version}}/latest-{{target}}-{{arch}}.json", - "https://github.com/BurntToasters/ROSI/releases/download/v{{current_version}}/latest-{{target}}.json" + "https://github.com/BurntToasters/ROSI/releases/latest/download/latest-{{target}}.json" ], - "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDc0MzRDOTlCMDBEQjQ2REEKUldUYVJ0c0FtOGswZEpNTnNPZlBOZXhyNkJFT0F1L0hMWjlWcWxiZlA4R3hUTERPbTEvWXY0YWoK" + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDc0MzRDOTlCMDBEQjQ2REEKUldUYVJ0c0FtOGswZEpNTnNPZlBOZXhyNkJFT0F1L0hMWjlWcWxiZlA4R3hUTERPbTEvWXY0YWoK", + "requireSignedVersion": true } } } diff --git a/src-tauri/vendor/tauri-plugin-updater/PATCHES.md b/src-tauri/vendor/tauri-plugin-updater/PATCHES.md index f9ebfedb..286a3ba2 100644 --- a/src-tauri/vendor/tauri-plugin-updater/PATCHES.md +++ b/src-tauri/vendor/tauri-plugin-updater/PATCHES.md @@ -22,7 +22,7 @@ reason (`.github/dependabot.yml`). | Source | `https://crates.io/api/v1/crates/tauri-plugin-updater/2.14.0/download` | | crates.io sha256 | `7259989d4fe11b2bf51f7d671642249b1837c4ae2da1430dc713ae38f98ceeec` | | Upstream git sha1 | `44293a5722efcaf27060504e63b17aeba721b40f` (`.cargo_vcs_info.json`, path `plugins/updater`) | -| Newest stable 2.x seen | `2.14.0` (checked 2026-10-17 via crates.io; `2.13.3` and `2.13.2` are older) | +| Newest stable 2.x seen | `2.14.1` (seen 2026-10-28 in the local crates.io cache). Dependency-only: `base64` 0.22 to 0.23 and `zip` 4 to 9 in `Cargo.toml`, `src/` byte-identical to 2.14.0. Not adopted; the base stays `2.14.0`. Before that, `2.14.0` was the newest (checked 2026-10-17; `2.13.3` and `2.13.2` are older) | `Cargo.toml.orig`, `README.md`, `build.rs`, `permissions/`, `CHANGELOG.md`, `SECURITY.md`, `api-iife.js`, the `LICENSE*` files and @@ -44,9 +44,9 @@ patch -p1 -d -i ROSI.patch | File | Status | Why the patch exists | | --- | --- | --- | -| `src/install_safety.rs` | new | Shared install checks. macOS: bundle identity and completeness, a sibling backup path, a process-wide install lock, and a privileged replacement script whose arguments are shell-quoted. Windows: `ShellExecuteW` result check (values `<= 32` are failures). Archives: confined tar member, parent-directory and symlink-target checks, so an update cannot write outside the extract root. Linux: helper binaries (`pkexec`, `sudo`, `zenity`, `kdialog`, `sh`) are resolved only from fixed root-owned system directories and never through `PATH`; the privileged environment is an allowlist (session display, D-Bus, locale vars) and sets `PATH` to fixed system directories. Also cross-device move and copy fallback. Its `#[cfg(test)]` module runs with `cargo test`. | +| `src/install_safety.rs` | new | Shared install checks. macOS: bundle identity and completeness, Mach-O architecture validation (`macos_bundle_executable_supports_host_arch`, checking both native execution and Rosetta 2 translation), a sibling backup path, a process-wide install lock, and a privileged replacement script whose arguments are shell-quoted. Windows: `ShellExecuteW` result check (values `<= 32` are failures). Archives: confined tar member, parent-directory and symlink-target checks, so an update cannot write outside the extract root. Linux: helper binaries (`pkexec`, `sudo`, `zenity`, `kdialog`, `sh`) are resolved only from fixed root-owned system directories and never through `PATH`; the privileged environment is an allowlist (session display, D-Bus, locale vars) and sets `PATH` to fixed system directories. Also cross-device move and copy fallback. Its `#[cfg(test)]` module runs with `cargo test`. | | `src/appimage_install.rs` | new | Validates an AppImage before it replaces the live file: ELF class, machine and entrypoint checks, squashfs and ISO9660 structure for Type 2 images. Stages in a private work directory, moves the old image aside, then renames the stage into place, restoring the old image if that fails. Used on Linux and BSD only. | -| `src/appimage_archive.rs` | new | Bounded `.tar.gz` extraction for AppImage updates: entry-count limit, total decompressed-byte limit, exactly one regular `.AppImage` member, no links, truncation detection. Used on Linux and BSD. Its `BoundedArchiveReader` (decompressed-byte cap, tar end-block and trailing-data check) also bounds macOS app extraction. | +| `src/appimage_archive.rs` | new | Bounded `.tar.gz` extraction for AppImage updates: entry-count limit, total decompressed-byte limit, exactly one regular `.AppImage` member, no links, truncation detection. Used on Linux and BSD. Its `BoundedArchiveReader` (decompressed-byte cap, tar end-block and trailing-data check) also bounds macOS app extraction. The module is compiled on macOS without the `zip` feature, because its `flate2` and `tar` dependencies are unconditional there. On Linux and BSD it still needs `zip`. | | `src/updater.rs` | modified | See details below. | | `src/lib.rs` | modified | Adds `mod install_safety;`. Plumbs the fallible `on_before_exit` hook and a new `on_windows_installer_launched` hook into the updater state. Windows cleanup now runs from the launched hook, not before launch. | | `src/error.rs` | modified | Adds `Error::BeforeExit(String)` so a failed app-state flush aborts installation and keeps the update retryable. | @@ -65,7 +65,9 @@ patch -p1 -d -i ROSI.patch the running byte count (`append_download_chunk`). A body longer than its declared length is an error. - macOS: installs go through `install_inner_locked` inside the install lock. The new bundle - is extracted with the confined extractor (`extract_macos_app_archive`), the live bundle is + is extracted with the confined extractor (`extract_macos_app_archive`), verified to support + the host CPU architecture (`macos_bundle_executable_supports_host_arch` for the main executable + and bundled sidecars, including Rosetta 2 migration to native Apple Silicon), the live bundle is moved to the sibling backup, the new bundle is moved live, and the backup is removed only after the identity check passes. `restore_macos_live_bundle` and `recover_macos_live_bundle` roll back a partial swap. When the user-owned path is not @@ -112,8 +114,14 @@ functions are not dead: their only caller is the Linux/BSD `install_appimage` pa installs on Linux. Fix: a `#![cfg_attr(target_os = "macos", allow(dead_code))]` at the top of both files. -Linux and BSD still warn about real dead code. macOS stays clean. The modules still -compile on macOS so their tests keep running. +Linux and BSD still warn about real dead code. macOS has no dead-code warnings. The modules +still compile on macOS so their tests keep running. + +Other default clippy lints still fire on pre-existing code. On 2026-10-28, a cross check +(`cargo clippy --lib --tests --target aarch64-apple-darwin`, Rust 1.98.1, from Windows) +reported 5 lib lints (`map_or`, `div_ceil`, range `contains`) in `appimage_install.rs`, and 10 +more in test code (`appimage_install.rs`, `appimage_archive.rs`, `install_safety.rs`, +`updater.rs`). None is in the Mach-O, zstd or macOS archive extraction code. ## Known gaps @@ -136,8 +144,11 @@ compile on macOS so their tests keep running. `src-tauri` as the seed. It is a standalone root package, so its unit tests run with `cargo test --locked --manifest-path src-tauri/vendor/tauri-plugin-updater/Cargo.toml --lib` (CI gate `vendorUpdater` in `scripts/test-all.js`). The root `cargo test --all-targets` - gate does not run them. Last run (macOS, 2026-10-24): 50 pass, 1 ignored (the real-archive - test that `scripts/e2e-updater-zst.mjs` runs). + gate does not run them. Last run on Windows (2026-10-28, after the Mach-O and zstd changes): + 34 pass, 0 fail, 0 ignored. The macOS run is pending for this state. Its count and its one + ignored test (the real-archive test that `scripts/e2e-updater-zst.mjs` runs with + `ROSI_UPDATER_ZST_E2E_ARCHIVES`) must be confirmed on a Mac, through the macOS CI job or + `npm run test:e2e:updater-zst`. ## Rebase procedure (new upstream version X) diff --git a/src-tauri/vendor/tauri-plugin-updater/ROSI.patch b/src-tauri/vendor/tauri-plugin-updater/ROSI.patch index 63d9d46e..2f4347e8 100644 --- a/src-tauri/vendor/tauri-plugin-updater/ROSI.patch +++ b/src-tauri/vendor/tauri-plugin-updater/ROSI.patch @@ -1,6 +1,6 @@ -diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/Cargo.toml b/Cargo.toml ---- a/Cargo.toml -+++ b/Cargo.toml +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json -x PATCHES.md -x ROSI.patch a/Cargo.toml b/Cargo.toml +--- a/Cargo.toml 2006-07-23 18:21:28.000000000 -0700 ++++ b/Cargo.toml 2026-10-27 23:33:49.000000000 -0700 @@ -187,6 +187,10 @@ [target.'cfg(target_os = "macos")'.dependencies.tar] version = "0.4" @@ -12,12 +12,13 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/Cargo.t [target.'cfg(target_os = "windows")'.dependencies.windows-sys] version = "0.61.0" features = [ -diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/appimage_archive.rs b/src/appimage_archive.rs ---- a/src/appimage_archive.rs -+++ b/src/appimage_archive.rs -@@ -0,0 +1,397 @@ -+// The AppImage helpers are compiled for macOS only because the shared module -+// list includes it; their callers are Linux and BSD only. Keep dead_code quiet there. +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json -x PATCHES.md -x ROSI.patch a/src/appimage_archive.rs b/src/appimage_archive.rs +--- a/src/appimage_archive.rs 1969-12-31 16:00:00.000000000 -0800 ++++ b/src/appimage_archive.rs 2026-10-28 13:12:25.000000000 -0700 +@@ -0,0 +1,398 @@ ++// Bounded tar.gz helpers. `extract_appimage_from_archive` is called by the Linux and BSD ++// AppImage install path. On macOS, `BoundedArchiveReader` bounds app extraction, and the ++// AppImage-only functions have no caller, so dead_code is allowed there. +#![cfg_attr(target_os = "macos", allow(dead_code))] + +use super::{appimage_install, Error, Result}; @@ -413,9 +414,9 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/app + assert!(extract_with_limits(&too_many_entries, 1 << 20, 2 << 20, 2).is_err()); + } +} -diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/appimage_install.rs b/src/appimage_install.rs ---- a/src/appimage_install.rs -+++ b/src/appimage_install.rs +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json -x PATCHES.md -x ROSI.patch a/src/appimage_install.rs b/src/appimage_install.rs +--- a/src/appimage_install.rs 1969-12-31 16:00:00.000000000 -0800 ++++ b/src/appimage_install.rs 2026-10-18 13:21:50.000000000 -0700 @@ -0,0 +1,1115 @@ +// The AppImage helpers are compiled for macOS only because the shared module +// list includes it; their callers are Linux and BSD only. Keep dead_code quiet there. @@ -1532,9 +1533,9 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/app + super::tests::appimage(2, super::tests::host_machine(), suffix) + } +} -diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/commands.rs b/src/commands.rs ---- a/src/commands.rs -+++ b/src/commands.rs +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json -x PATCHES.md -x ROSI.patch a/src/commands.rs b/src/commands.rs +--- a/src/commands.rs 2006-07-23 18:21:28.000000000 -0700 ++++ b/src/commands.rs 2026-10-17 20:04:36.000000000 -0700 @@ -46,6 +46,7 @@ timeout: Option, proxy: Option, @@ -1551,9 +1552,9 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/com let updater = builder.build()?; let update = updater.check().await?; -diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/error.rs b/src/error.rs ---- a/src/error.rs -+++ b/src/error.rs +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json -x PATCHES.md -x ROSI.patch a/src/error.rs b/src/error.rs +--- a/src/error.rs 2006-07-23 18:21:28.000000000 -0700 ++++ b/src/error.rs 2026-10-17 20:04:37.000000000 -0700 @@ -89,6 +89,9 @@ /// The package manager could not install the downloaded Linux package. #[error("Failed to install package")] @@ -1564,10 +1565,10 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/err /// The downloaded update is not in a format the updater can install on the current platform. #[error("invalid updater binary format")] InvalidUpdaterFormat, -diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/install_safety.rs b/src/install_safety.rs ---- a/src/install_safety.rs -+++ b/src/install_safety.rs -@@ -0,0 +1,936 @@ +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json -x PATCHES.md -x ROSI.patch a/src/install_safety.rs b/src/install_safety.rs +--- a/src/install_safety.rs 1969-12-31 16:00:00.000000000 -0800 ++++ b/src/install_safety.rs 2026-10-28 13:11:58.000000000 -0700 +@@ -0,0 +1,1108 @@ +// Copyright 2019-2023 Tauri Programme within The Commons Conservancy +// SPDX-License-Identifier: Apache-2.0 +// SPDX-License-Identifier: MIT @@ -1733,6 +1734,178 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/ins + } +} + ++#[cfg(target_os = "macos")] ++fn is_rosetta_translated() -> bool { ++ let mut ret: libc::c_int = 0; ++ let mut size: libc::size_t = std::mem::size_of_val(&ret); ++ let name = c"sysctl.proc_translated"; ++ let res = unsafe { ++ libc::sysctlbyname( ++ name.as_ptr(), ++ &mut ret as *mut _ as *mut libc::c_void, ++ &mut size, ++ std::ptr::null_mut(), ++ 0, ++ ) ++ }; ++ res == 0 && ret == 1 ++} ++ ++#[cfg(not(target_os = "macos"))] ++fn is_rosetta_translated() -> bool { ++ false ++} ++ ++/// Z02.4: verifies that a Mach-O executable supports the host architecture ++/// before swapping into place. ++pub fn macos_bundle_executable_supports_host_arch(path: &Path) -> bool { ++ macos_executable_supports_runtime_host(path, std::env::consts::ARCH, is_rosetta_translated()) ++} ++ ++pub fn macos_executable_supports_runtime_host( ++ path: &Path, ++ compile_arch: &str, ++ rosetta_translated: bool, ++) -> bool { ++ let Ok(mut file) = std::fs::File::open(path) else { ++ return false; ++ }; ++ use std::io::Read; ++ let mut header = [0u8; 4096]; ++ let Ok(n) = file.read(&mut header) else { ++ return false; ++ }; ++ macho_bytes_support_runtime_host(&header[..n], compile_arch, rosetta_translated) ++} ++ ++pub fn macos_bundle_supports_runtime_host( ++ bundle_path: &Path, ++ compile_arch: &str, ++ rosetta_translated: bool, ++) -> bool { ++ let Some(identity) = macos_app_bundle_identity(bundle_path) else { ++ return false; ++ }; ++ let macos_dir = bundle_path.join("Contents/MacOS"); ++ let executable = macos_dir.join(&identity.executable); ++ if !macos_executable_supports_runtime_host(&executable, compile_arch, rosetta_translated) { ++ return false; ++ } ++ ["rosi-yt-dlp", "rosi-ffmpeg", "rosi-ffprobe"] ++ .iter() ++ .all(|sidecar| { ++ macos_executable_supports_runtime_host( ++ &macos_dir.join(sidecar), ++ compile_arch, ++ rosetta_translated, ++ ) ++ }) ++} ++ ++pub fn macho_bytes_support_host_arch(bytes: &[u8]) -> bool { ++ macho_bytes_support_runtime_host(bytes, std::env::consts::ARCH, is_rosetta_translated()) ++} ++ ++pub fn macho_bytes_support_runtime_host( ++ bytes: &[u8], ++ compile_arch: &str, ++ rosetta_translated: bool, ++) -> bool { ++ match compile_arch { ++ "aarch64" => macho_bytes_support_arch(bytes, "aarch64"), ++ "x86_64" if rosetta_translated => { ++ macho_bytes_support_arch(bytes, "aarch64") || macho_bytes_support_arch(bytes, "x86_64") ++ } ++ "x86_64" => macho_bytes_support_arch(bytes, "x86_64"), ++ _ => false, ++ } ++} ++ ++pub fn macho_bytes_support_arch(bytes: &[u8], target_arch: &str) -> bool { ++ const MH_MAGIC_64: [u8; 4] = [0xcf, 0xfa, 0xed, 0xfe]; ++ const MH_CIGAM_64: [u8; 4] = [0xfe, 0xed, 0xfa, 0xcf]; ++ const FAT_MAGIC: [u8; 4] = [0xca, 0xfe, 0xba, 0xbe]; ++ const FAT_CIGAM: [u8; 4] = [0xbe, 0xba, 0xfe, 0xca]; ++ const FAT_MAGIC_64: [u8; 4] = [0xca, 0xfe, 0xba, 0xbf]; ++ const FAT_CIGAM_64: [u8; 4] = [0xbf, 0xba, 0xfe, 0xca]; ++ ++ const CPU_TYPE_X86_64: u32 = 0x01000007; ++ const CPU_TYPE_ARM64: u32 = 0x0100000c; ++ ++ let expected_cputype = match target_arch { ++ "aarch64" | "arm64" => CPU_TYPE_ARM64, ++ "x86_64" | "amd64" => CPU_TYPE_X86_64, ++ _ => return false, ++ }; ++ ++ if bytes.len() < 8 { ++ return false; ++ } ++ ++ if bytes.starts_with(&MH_MAGIC_64) { ++ let cputype = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); ++ return cputype == expected_cputype; ++ } ++ if bytes.starts_with(&MH_CIGAM_64) { ++ let cputype = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); ++ return cputype == expected_cputype; ++ } ++ if bytes.starts_with(&FAT_MAGIC) || bytes.starts_with(&FAT_CIGAM) { ++ let is_be = bytes.starts_with(&FAT_MAGIC); ++ let nfat = if is_be { ++ u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) ++ } else { ++ u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) ++ }; ++ let count = (nfat as usize).min(64); ++ for i in 0..count { ++ let Some(offset) = i.checked_mul(20).and_then(|o| o.checked_add(8)) else { ++ return false; ++ }; ++ let Some(slice) = bytes.get(offset..offset + 4) else { ++ return false; ++ }; ++ let cputype = if is_be { ++ u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]) ++ } else { ++ u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) ++ }; ++ if cputype == expected_cputype { ++ return true; ++ } ++ } ++ return false; ++ } ++ if bytes.starts_with(&FAT_MAGIC_64) || bytes.starts_with(&FAT_CIGAM_64) { ++ let is_be = bytes.starts_with(&FAT_MAGIC_64); ++ let nfat = if is_be { ++ u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) ++ } else { ++ u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) ++ }; ++ let count = (nfat as usize).min(64); ++ for i in 0..count { ++ let Some(offset) = i.checked_mul(32).and_then(|o| o.checked_add(8)) else { ++ return false; ++ }; ++ let Some(slice) = bytes.get(offset..offset + 4) else { ++ return false; ++ }; ++ let cputype = if is_be { ++ u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]) ++ } else { ++ u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) ++ }; ++ if cputype == expected_cputype { ++ return true; ++ } ++ } ++ return false; ++ } ++ ++ false ++} ++ +/// Session variables pkexec, zenity, and polkit agents need after `env_clear`. +/// Never includes `PATH`. +pub const LINUX_PRIVILEGED_ENV_ALLOWLIST: &[&str] = &[ @@ -2504,9 +2677,9 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/ins + assert!(resolve_trusted_system_helper("definitely-not-a-zinnia-helper").is_err()); + } +} -diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/lib.rs b/src/lib.rs ---- a/src/lib.rs -+++ b/src/lib.rs +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json -x PATCHES.md -x ROSI.patch a/src/lib.rs b/src/lib.rs +--- a/src/lib.rs 2006-07-23 18:21:28.000000000 -0700 ++++ b/src/lib.rs 2026-10-17 20:04:37.000000000 -0700 @@ -31,6 +31,7 @@ mod commands; mod config; @@ -2606,9 +2779,9 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/lib }); Ok(()) }) -diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/updater.rs b/src/updater.rs ---- a/src/updater.rs -+++ b/src/updater.rs +diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json -x PATCHES.md -x ROSI.patch a/src/updater.rs b/src/updater.rs +--- a/src/updater.rs 2006-07-23 18:21:28.000000000 -0700 ++++ b/src/updater.rs 2026-10-28 13:12:24.000000000 -0700 @@ -22,7 +22,7 @@ }; use semver::Version; @@ -2618,7 +2791,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd use std::ffi::OsStr; use tauri::{ AppHandle, Resource, Runtime, -@@ -39,6 +39,31 @@ +@@ -39,6 +39,35 @@ error::{Error, Result}, }; @@ -2633,15 +2806,19 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd +#[path = "appimage_install.rs"] +mod appimage_install; + -+#[cfg(all( -+ feature = "zip", -+ any( -+ target_os = "linux", -+ target_os = "dragonfly", -+ target_os = "freebsd", -+ target_os = "netbsd", -+ target_os = "openbsd", -+ target_os = "macos" ++// macOS app extraction uses `BoundedArchiveReader` from this module. Its flate2 ++// and tar dependencies are unconditional on macOS, so macOS does not need `zip`. ++#[cfg(any( ++ target_os = "macos", ++ all( ++ feature = "zip", ++ any( ++ target_os = "linux", ++ target_os = "dragonfly", ++ target_os = "freebsd", ++ target_os = "netbsd", ++ target_os = "openbsd" ++ ) + ) +))] +#[path = "appimage_archive.rs"] @@ -2650,7 +2827,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd const UPDATER_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),); /// The kind of bundle the running application was installed from. -@@ -143,9 +168,11 @@ +@@ -143,9 +172,11 @@ } } @@ -2665,7 +2842,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd /// Function that customizes the `reqwest` client builder used for the updater requests. /// See [`UpdaterBuilder::configure_client`]. pub type OnBeforeRequest = Arc ClientBuilder + Send + Sync + 'static>; -@@ -154,6 +181,75 @@ +@@ -154,6 +185,75 @@ /// It receives the current application version and the remote release, /// and returns `true` when the release should be treated as an update. pub type VersionComparator = Arc bool + Send + Sync>; @@ -2741,7 +2918,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd #[cfg(target_os = "macos")] type MainThreadClosure = Box; #[cfg(target_os = "macos")] -@@ -170,13 +266,16 @@ +@@ -170,13 +270,16 @@ /// App name, used for creating named tempfiles #[cfg(windows)] app_name: String, @@ -2759,7 +2936,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd restart_after_install: bool, } -@@ -218,11 +317,13 @@ +@@ -218,11 +321,13 @@ run_on_main_thread, #[cfg(windows)] app_name: app.package_info().name.clone(), @@ -2774,7 +2951,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd restart_after_install: true, }, current_version: app.package_info().version.clone(), -@@ -400,22 +501,34 @@ +@@ -400,22 +505,34 @@ self } @@ -2815,7 +2992,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } self } -@@ -453,6 +566,10 @@ +@@ -453,6 +570,10 @@ let arch = updater_arch().ok_or(Error::UnsupportedArch)?; let executable_path = self.executable_path.clone().unwrap_or(current_exe()?); @@ -2826,7 +3003,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd // Get the extract_path from the provided executable_path let extract_path = if cfg!(target_os = "linux") { -@@ -462,6 +579,7 @@ +@@ -462,6 +583,7 @@ }; Ok(Updater { @@ -2834,7 +3011,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd current_version: self.current_version, version_comparator: self.version_comparator, timeout: self.timeout, -@@ -495,6 +613,7 @@ +@@ -495,6 +617,7 @@ /// /// Get one from [`crate::UpdaterExt::updater`] or by calling [`UpdaterBuilder::build`]. pub struct Updater { @@ -2842,7 +3019,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd current_version: Version, version_comparator: Option, timeout: Option, -@@ -537,6 +656,27 @@ +@@ -537,6 +660,27 @@ headers.insert(ACCEPT, HeaderValue::from_static("application/json")); } @@ -2870,7 +3047,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd let target = self.current_target()?; let mut remote_release: Option = None; -@@ -726,6 +866,7 @@ +@@ -726,6 +870,7 @@ current_version: self.current_version.to_string(), target: target.to_owned(), extract_path: self.extract_path.clone(), @@ -2878,7 +3055,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd version: release.version.to_string(), date: release.pub_date, download_url: download_url.clone(), -@@ -807,6 +948,8 @@ +@@ -807,6 +952,8 @@ /// Extract path #[allow(unused)] extract_path: PathBuf, @@ -2887,7 +3064,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd context: UpdaterContext, } -@@ -877,14 +1020,20 @@ +@@ -877,14 +1024,20 @@ .get("Content-Length") .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse().ok()); @@ -2909,7 +3086,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } on_download_finish(); -@@ -921,7 +1070,7 @@ +@@ -921,7 +1074,7 @@ pub fn install(&self, bytes: impl AsRef<[u8]>) -> Result<()> { let bytes = bytes.as_ref(); self.verify(bytes)?; @@ -2918,7 +3095,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } /// Downloads and installs the updater package -@@ -935,9 +1084,8 @@ +@@ -935,9 +1088,8 @@ on_chunk: C, on_download_finish: D, ) -> Result<()> { @@ -2929,7 +3106,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } /// Updates are not supported on mobile, where apps are updated through the app stores. -@@ -1014,10 +1162,6 @@ +@@ -1014,10 +1166,6 @@ let updater_type = self.extract(bytes)?; @@ -2940,7 +3117,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd let file = match &updater_type { WindowsUpdaterType::Nsis { path, .. } => path.as_os_str().to_os_string(), -@@ -1033,7 +1177,7 @@ +@@ -1033,7 +1181,7 @@ let file = encode_wide(file); let parameters = encode_wide(parameters); @@ -2949,7 +3126,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd ShellExecuteW( std::ptr::null_mut(), w!("open"), -@@ -1042,12 +1186,16 @@ +@@ -1042,12 +1190,16 @@ std::ptr::null(), SW_SHOW, ) @@ -2972,7 +3149,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } fn updater_parameters(&self, updater_type: &WindowsUpdaterType) -> OsString { -@@ -1219,113 +1367,36 @@ +@@ -1219,111 +1371,34 @@ } fn install_appimage(&self, bytes: &[u8]) -> Result<()> { @@ -3000,8 +3177,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - log::error!("the update is neither an AppImage nor a compressed AppImage"); - return Err(Error::InvalidUpdaterFormat); - } -+ let payload = bytes.to_vec(); - +- - for tmp_dir_location in self.tmp_dir_locations() { - let Some(tmp_dir_location) = tmp_dir_location() else { - continue; @@ -3076,15 +3252,27 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - Ok(_) => Ok(()), - }; - } +- } ++ let payload = bytes.to_vec(); + +- Err(Error::TempDirNotOnSameMountPoint) +- } +- +- /// Directories to try, in order, for the temporary files of an install: the system temporary +- /// directory, the user cache directory and the directory holding the app. +- fn tmp_dir_locations(&self) -> Vec Option + '_>> { +- vec![ +- Box::new(|| Some(std::env::temp_dir())), +- Box::new(dirs::cache_dir), +- Box::new(|| self.extract_path.parent().map(Path::to_path_buf)), +- ] + // Keep the recovery copy beside the installed image when possible so + // it survives ordinary `/tmp` cleanup and remains on the install + // filesystem for an atomic replacement. + let mut temporary_roots = Vec::new(); + if let Some(parent) = self.extract_path.parent() { + temporary_roots.push(parent.to_path_buf()); - } -- -- Err(Error::TempDirNotOnSameMountPoint) ++ } + if let Some(cache_directory) = dirs::cache_dir() { + temporary_roots.push(cache_directory); + } @@ -3098,20 +3286,8 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + Ok(()) } -- /// Directories to try, in order, for the temporary files of an install: the system temporary -- /// directory, the user cache directory and the directory holding the app. -- fn tmp_dir_locations(&self) -> Vec Option + '_>> { -- vec![ -- Box::new(|| Some(std::env::temp_dir())), -- Box::new(dirs::cache_dir), -- Box::new(|| self.extract_path.parent().map(Path::to_path_buf)), -- ] -- } -- fn install_deb(&self, bytes: &[u8]) -> Result<()> { - // First verify the bytes are actually a .deb package - if !infer::archive::is_deb(bytes) { -@@ -1333,7 +1404,7 @@ +@@ -1333,7 +1408,7 @@ return Err(Error::InvalidUpdaterFormat); } @@ -3120,7 +3296,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } fn install_rpm(&self, bytes: &[u8]) -> Result<()> { -@@ -1341,29 +1412,43 @@ +@@ -1341,29 +1416,43 @@ if !infer::archive::is_rpm(bytes) { return Err(Error::InvalidUpdaterFormat); } @@ -3154,16 +3330,17 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - let prefix = format!("tauri_{package_extension}_update"); - if let Ok(tmp_dir) = tempfile::Builder::new().prefix(&prefix).tempdir_in(path) { - let pkg_path = tmp_dir.path().join(format!("package.{package_extension}")); +- +- // Try writing the .deb / .rpm file +- if std::fs::write(&pkg_path, bytes).is_ok() { +- // If write succeeds, proceed with installation +- return self.try_install_with_privileges(&pkg_path, install_cmd, install_arg); + for tmp_dir_location in tmp_dir_locations { + if let Some(path) = tmp_dir_location() { + let prefix = format!("tauri_{package_extension}_update"); + if let Ok(tmp_dir) = tempfile::Builder::new().prefix(&prefix).tempdir_in(path) { + let pkg_path = tmp_dir.path().join(format!("package.{package_extension}")); - -- // Try writing the .deb / .rpm file -- if std::fs::write(&pkg_path, bytes).is_ok() { -- // If write succeeds, proceed with installation -- return self.try_install_with_privileges(&pkg_path, install_cmd, install_arg); ++ + // Try writing the .deb / .rpm file + if std::fs::write(&pkg_path, bytes).is_ok() { + // If write succeeds, proceed with installation @@ -3177,7 +3354,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } // If write fails, continue to next temp location } -@@ -1377,68 +1462,78 @@ +@@ -1377,68 +1466,78 @@ &self, pkg_path: &Path, install_cmd: &str, @@ -3219,6 +3396,13 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - log::debug!("installed {pkg_path:?} with GUI sudo"); - return Ok(()); - } +- +- // 3. Final fallback: terminal sudo +- let status = std::process::Command::new("sudo") +- .arg(install_cmd) +- .arg(install_arg) +- .arg(pkg_path) +- .status()?; + if let Some(sudo) = sudo.as_ref() { + if let Ok(password) = self.get_password_graphically() { + if self.install_with_sudo(sudo, &installer, pkg_path, &password, install_args)? { @@ -3227,23 +3411,17 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + } + } -- // 3. Final fallback: terminal sudo -- let status = std::process::Command::new("sudo") -- .arg(install_cmd) -- .arg(install_arg) -- .arg(pkg_path) -- .status()?; -+ // 3. Final fallback: terminal sudo -+ let mut command = linux_privileged_command(sudo); -+ command.arg(&installer).args(install_args).arg(pkg_path); -+ let status = -+ linux_privileged_wait_status(command, std::time::Duration::from_secs(600))?; - - if status.success() { - log::debug!("installed {pkg_path:?} with sudo"); - Ok(()) - } else { - Err(Error::PackageInstallFailed) ++ // 3. Final fallback: terminal sudo ++ let mut command = linux_privileged_command(sudo); ++ command.arg(&installer).args(install_args).arg(pkg_path); ++ let status = ++ linux_privileged_wait_status(command, std::time::Duration::from_secs(600))?; ++ + if status.success() { + log::debug!("installed {pkg_path:?} with sudo"); + return Ok(()); @@ -3262,6 +3440,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - "--text=Enter your password to install the update:", - ]) - .output(); +- +- if let Ok(output) = zenity_result +- && output.status.success() +- { +- return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); + if let Ok(zenity) = crate::install_safety::resolve_trusted_system_helper("zenity") { + let zenity_result = linux_privileged_command(&zenity) + .args([ @@ -3270,11 +3453,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + "--text=Enter your password to install the update:", + ]) + .output(); - -- if let Ok(output) = zenity_result -- && output.status.success() -- { -- return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); ++ + if let Ok(output) = zenity_result { + if output.status.success() { + return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); @@ -3286,15 +3465,16 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - let kdialog_result = std::process::Command::new("kdialog") - .args(["--password", "Enter your password to install the update:"]) - .output(); -+ if let Ok(kdialog) = crate::install_safety::resolve_trusted_system_helper("kdialog") { -+ let kdialog_result = linux_privileged_command(&kdialog) -+ .args(["--password", "Enter your password to install the update:"]) -+ .output(); - +- - if let Ok(output) = kdialog_result - && output.status.success() - { - return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); ++ if let Ok(kdialog) = crate::install_safety::resolve_trusted_system_helper("kdialog") { ++ let kdialog_result = linux_privileged_command(&kdialog) ++ .args(["--password", "Enter your password to install the update:"]) ++ .output(); ++ + if let Ok(output) = kdialog_result { + if output.status.success() { + return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()); @@ -3303,7 +3483,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } Err(Error::AuthenticationFailed) -@@ -1446,34 +1541,105 @@ +@@ -1446,34 +1545,105 @@ fn install_with_sudo( &self, @@ -3337,10 +3517,10 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + .stderr(Stdio::piped()); + // Isolate the sudo/dpkg group so a timeout can kill the whole tree. + command.process_group(0); - ++ + let mut child = command.spawn()?; + let pid = child.id(); -+ + if let Some(mut stdin) = child.stdin.take() { - // Write password to stdin writeln!(stdin, "{password}")?; @@ -3420,7 +3600,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd /// MacOS #[cfg(target_os = "macos")] impl Update { -@@ -1484,143 +1650,192 @@ +@@ -1484,143 +1654,214 @@ /// │ └── ... /// └── ... fn install_inner(&self, bytes: &[u8]) -> Result<()> { @@ -3452,34 +3632,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - .flatten() - .find(|dir| dir.metadata().is_ok_and(|m| m.dev() == app_dev)) - .ok_or(Error::TempDirNotOnSameMountPoint)?; -+ let app_parent = self -+ .extract_path -+ .parent() -+ .ok_or(Error::FailedToDetermineExtractPath)?; -+ let backup_path = macos_update_backup_path(&self.extract_path) -+ .ok_or(Error::FailedToDetermineExtractPath)?; - +- - let tmp_backup_dir = tempfile::Builder::new() - .prefix("tauri_current_app") - .tempdir_in(&tmp_root)?; -+ let expected_identity = MacosBundleIdentity { -+ bundle_identifier: self.context.bundle_identifier.clone(), -+ executable: self.executable_name.clone().ok_or_else(|| { -+ Error::Io(std::io::Error::new( -+ std::io::ErrorKind::InvalidData, -+ "could not determine the installed app executable name", -+ )) -+ })?, -+ }; -+ if !macos_bundle_matches(&self.extract_path, &expected_identity) -+ && !macos_bundle_matches(&backup_path, &expected_identity) -+ { -+ return Err(Error::Io(std::io::Error::new( -+ std::io::ErrorKind::InvalidData, -+ "neither the installed app nor its recovery backup matches the configured app identity", -+ ))); -+ } - +- - let tmp_extract_dir = tempfile::Builder::new() - .prefix("tauri_updated_app") - .tempdir_in(&tmp_root)?; @@ -3496,39 +3653,16 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - // Ensure parent directories exist - if let Some(parent) = extraction_path.parent() { - std::fs::create_dir_all(parent)?; -+ let tmp_extract_dir = match tempfile::Builder::new() -+ .prefix(".rosi-updated-app-") -+ .tempdir_in(app_parent) -+ { -+ Ok(dir) => dir, -+ Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => { -+ // `/Applications` is not user-writable. Extract in a user temp -+ // dir; the privileged swap copies onto the app volume. Restore -+ // must never nest `mv` into a partial `$SRC`. -+ tempfile::Builder::new() -+ .prefix("tauri_updated_app") -+ .tempdir()? - } -+ Err(err) => return Err(err.into()), -+ }; - +- } +- - if let Err(err) = entry.unpack(&extraction_path) { - // Cleanup on error - std::fs::remove_dir_all(tmp_extract_dir.path()).ok(); - return Err(err.into()); - } - extracted_files.push(extraction_path); -+ extract_macos_app_archive(bytes, tmp_extract_dir.path())?; -+ let staged_identity = macos_app_bundle_identity(tmp_extract_dir.path()); -+ if !macos_app_bundle_complete(tmp_extract_dir.path()) -+ || staged_identity.as_ref() != Some(&expected_identity) -+ { -+ return Err(Error::Io(std::io::Error::new( -+ std::io::ErrorKind::InvalidData, -+ "staged updater bundle is incomplete or has a different app identity", -+ ))); - } - +- } +- - // The temp dir becomes the installed bundle's root, and tempfile creates it - // with mode 0700, which stops every other user of the machine from launching - // the updated app. @@ -3536,11 +3670,30 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - tmp_extract_dir.path(), - std::fs::Permissions::from_mode(0o755), - )?; -+ // Recovery can mutate a protected install tree. Delay it until the -+ // downloaded bundle has passed identity and completeness validation, -+ // then route only permission failures through the existing admin path. -+ let recovery = -+ recover_macos_live_bundle(&self.extract_path, &backup_path, &expected_identity)?; ++ let app_parent = self ++ .extract_path ++ .parent() ++ .ok_or(Error::FailedToDetermineExtractPath)?; ++ let backup_path = macos_update_backup_path(&self.extract_path) ++ .ok_or(Error::FailedToDetermineExtractPath)?; ++ ++ let expected_identity = MacosBundleIdentity { ++ bundle_identifier: self.context.bundle_identifier.clone(), ++ executable: self.executable_name.clone().ok_or_else(|| { ++ Error::Io(std::io::Error::new( ++ std::io::ErrorKind::InvalidData, ++ "could not determine the installed app executable name", ++ )) ++ })?, ++ }; ++ if !macos_bundle_matches(&self.extract_path, &expected_identity) ++ && !macos_bundle_matches(&backup_path, &expected_identity) ++ { ++ return Err(Error::Io(std::io::Error::new( ++ std::io::ErrorKind::InvalidData, ++ "neither the installed app nor its recovery backup matches the configured app identity", ++ ))); ++ } - // Exchange the current app and the new one in a single step where the file - // system supports it, so the install path is never empty; the previous app @@ -3554,9 +3707,22 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - Err(err) if err.kind() != std::io::ErrorKind::PermissionDenied => { - log::debug!("cannot swap the app bundles ({err}), moving them instead"); - replace_bundle(&self.extract_path, tmp_extract_dir.path(), &backup) -- } -- other => other, -- }; ++ let tmp_extract_dir = match tempfile::Builder::new() ++ .prefix(".rosi-updated-app-") ++ .tempdir_in(app_parent) ++ { ++ Ok(dir) => dir, ++ Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => { ++ // `/Applications` is not user-writable. Extract in a user temp ++ // dir; the privileged swap copies onto the app volume. Restore ++ // must never nest `mv` into a partial `$SRC`. ++ tempfile::Builder::new() ++ .prefix("tauri_updated_app") ++ .tempdir()? + } +- other => other, ++ Err(err) => return Err(err.into()), + }; - let need_authorization = match moved { - Ok(()) => false, - Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => true, @@ -3569,6 +3735,49 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - ) { - log::error!("failed to install the update: {err}"); - return Err(Error::PreviousAppNotRestored(kept)); +- } +- std::fs::remove_dir_all(tmp_extract_dir.path()).ok(); +- return Err(err.into()); ++ ++ extract_macos_app_archive(bytes, tmp_extract_dir.path())?; ++ let staged_identity = macos_app_bundle_identity(tmp_extract_dir.path()); ++ if !macos_app_bundle_complete(tmp_extract_dir.path()) ++ || staged_identity.as_ref() != Some(&expected_identity) ++ { ++ return Err(Error::Io(std::io::Error::new( ++ std::io::ErrorKind::InvalidData, ++ "staged updater bundle is incomplete or has a different app identity", ++ ))); ++ } ++ ++ let staged_executable = tmp_extract_dir ++ .path() ++ .join("Contents/MacOS") ++ .join(&expected_identity.executable); ++ if !crate::install_safety::macos_bundle_executable_supports_host_arch(&staged_executable) { ++ return Err(Error::Io(std::io::Error::new( ++ std::io::ErrorKind::InvalidData, ++ "staged updater executable does not support the host architecture", ++ ))); ++ } ++ for sidecar in ["rosi-yt-dlp", "rosi-ffmpeg", "rosi-ffprobe"] { ++ let sidecar_path = tmp_extract_dir.path().join("Contents/MacOS").join(sidecar); ++ if !crate::install_safety::macos_bundle_executable_supports_host_arch(&sidecar_path) { ++ return Err(Error::Io(std::io::Error::new( ++ std::io::ErrorKind::InvalidData, ++ format!( ++ "staged updater sidecar {sidecar} does not support the host architecture" ++ ), ++ ))); + } ++ } ++ ++ // Recovery can mutate a protected install tree. Delay it until the ++ // downloaded bundle has passed identity and completeness validation, ++ // then route only permission failures through the existing admin path. ++ let recovery = ++ recover_macos_live_bundle(&self.extract_path, &backup_path, &expected_identity)?; ++ + let unprivileged = if matches!(recovery, MacosRecoveryDisposition::RequiresPrivilegedSwap) { + // A validated recovery entry can live in a protected install + // directory. Keep it untouched until the staged bundle is fully @@ -3615,10 +3824,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + )?; + Err(err) + } - } -- std::fs::remove_dir_all(tmp_extract_dir.path()).ok(); -- return Err(err.into()); -- } ++ } + })() }; @@ -3735,7 +3941,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } let _ = std::process::Command::new("touch") -@@ -1631,115 +1846,299 @@ +@@ -1631,115 +1872,299 @@ } } @@ -3746,14 +3952,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd -fn swap_bundle(target: &Path, staged: &Path) -> std::io::Result<()> { - use std::ffi::CString; - use std::os::unix::ffi::OsStrExt; -+fn macos_bundle_matches( -+ path: &Path, -+ expected: &crate::install_safety::MacosBundleIdentity, -+) -> bool { -+ crate::install_safety::macos_app_bundle_complete(path) -+ && crate::install_safety::macos_app_bundle_identity(path).as_ref() == Some(expected) -+} - +- - let from = CString::new(staged.as_os_str().as_bytes())?; - let to = CString::new(target.as_os_str().as_bytes())?; - // SAFETY: both pointers are valid NUL-terminated strings that outlive the call, @@ -3761,6 +3960,14 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - let result = unsafe { libc::renamex_np(from.as_ptr(), to.as_ptr(), libc::RENAME_SWAP) }; - if result == 0 { - Ok(()) ++fn macos_bundle_matches( ++ path: &Path, ++ expected: &crate::install_safety::MacosBundleIdentity, ++) -> bool { ++ crate::install_safety::macos_app_bundle_complete(path) ++ && crate::install_safety::macos_app_bundle_identity(path).as_ref() == Some(expected) ++} ++ +#[cfg(target_os = "macos")] +fn remove_macos_bundle_entry(path: &Path) -> std::io::Result<()> { + let metadata = match std::fs::symlink_metadata(path) { @@ -3796,7 +4003,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + std::io::ErrorKind::InvalidData, + "refusing to retire an incomplete or identity-mismatched updater backup", + )); - } ++ } + let parent = backup.parent().ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, @@ -3855,7 +4062,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + return Ok(()); + } + return Err(error); -+ } + } + Ok(()) } @@ -3870,6 +4077,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - ObjC.import("stdio"); - return $.renamex_np(argv[0], argv[1], 2) === 0 ? "swapped" : "failed"; -}"#; +- +-/// The shell command the privileged install runs: the same swap as [`swap_bundle`], and +-/// where the file system cannot swap, the same moves as [`replace_bundle`], deleting the +-/// previous app only once the new one is in place. The moves only run once the swap is +-/// known not to have happened, since after a swap they would put the previous app back. +fn restore_macos_live_bundle( + live: &Path, + backup: &Path, @@ -3891,11 +4103,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + } + Ok(()) +} - --/// The shell command the privileged install runs: the same swap as [`swap_bundle`], and --/// where the file system cannot swap, the same moves as [`replace_bundle`], deleting the --/// previous app only once the new one is in place. The moves only run once the swap is --/// known not to have happened, since after a swap they would put the previous app back. ++ #[cfg(target_os = "macos")] -fn privileged_install_command(target: &Path, staged: &Path, backup: &Path) -> String { - let swap = sh_quote(Path::new(SWAP_BUNDLE_JXA)); @@ -3983,6 +4191,27 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - if std::fs::symlink_metadata(target).is_ok() || std::fs::symlink_metadata(backup).is_err() { - return None; - } +- +- let mut name = target.file_stem().unwrap_or_default().to_os_string(); +- name.push(" (previous version)"); +- if let Some(extension) = target.extension() { +- name.push("."); +- name.push(extension); +- } +- let kept = [target.parent(), fallback_dir] +- .into_iter() +- .flatten() +- .map(|dir| dir.join(&name)) +- // `rename` replaces an empty directory, so never move onto anything already there +- .filter(|kept| std::fs::symlink_metadata(kept).is_err()) +- .find(|kept| std::fs::rename(backup, kept).is_ok()); +- +- match kept { +- Some(kept) => Some(kept), +- None => { +- let _ = backup_dir.keep(); +- Some(backup.to_path_buf()) +- } +/// Upper bound for an extracted `.app` (a universal ROSI bundle is ~300 MB). +#[cfg(target_os = "macos")] +const MACOS_MAX_DECOMPRESSED_BYTES: u64 = 2 * 1024 * 1024 * 1024; @@ -3990,12 +4219,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd +/// frames that ask for a larger window instead of allocating it. +#[cfg(target_os = "macos")] +const MACOS_ZSTD_WINDOW_LOG_MAX: u32 = 27; - -- let mut name = target.file_stem().unwrap_or_default().to_os_string(); -- name.push(" (previous version)"); -- if let Some(extension) = target.extension() { -- name.push("."); -- name.push(extension); ++ +/// `.app.tar.gz` (Tauri) or `.app.tar.zst` (ROSI per-arch), chosen by magic bytes. +#[cfg(target_os = "macos")] +fn macos_archive_decoder<'a>(bytes: &'a [u8]) -> Result> { @@ -4007,24 +4231,12 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + decoder.window_log_max(MACOS_ZSTD_WINDOW_LOG_MAX)?; + return Ok(Box::new(decoder)); } -- let kept = [target.parent(), fallback_dir] -- .into_iter() -- .flatten() -- .map(|dir| dir.join(&name)) -- // `rename` replaces an empty directory, so never move onto anything already there -- .filter(|kept| std::fs::symlink_metadata(kept).is_err()) -- .find(|kept| std::fs::rename(backup, kept).is_ok()); + if bytes.starts_with(&GZIP_MAGIC) { + return Ok(Box::new(flate2::read::GzDecoder::new(reader))); + } + Err(Error::InvalidUpdaterFormat) +} - -- match kept { -- Some(kept) => Some(kept), -- None => { -- let _ = backup_dir.keep(); -- Some(backup.to_path_buf()) ++ +#[cfg(target_os = "macos")] +fn extract_macos_app_archive_with_limit( + bytes: &[u8], @@ -4052,7 +4264,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + })?; + if relative.as_os_str().is_empty() { + continue; - } ++ } + let dest = dest_root.join(&relative); + if !path_is_inside(dest_root, &dest) { + return Err(Error::Io(std::io::Error::new( @@ -4111,14 +4323,14 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + std::io::ErrorKind::InvalidData, + format!("unsupported updater archive member type {kind:?}"), + ))); - } ++ } + // A truncated stream can end on a member boundary, which `tar::Archive` + // accepts. Require the full stream, both end blocks and nothing after them. + decompressed.drain_and_check_trailer() } /// Gets the base target string used by the updater. If bundle type is available it -@@ -1985,49 +2384,7 @@ +@@ -1985,48 +2410,6 @@ .collect() } @@ -4126,7 +4338,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd -/// -/// `ShellExecuteW` reports failures through its return value, not reliably through -/// `GetLastError`. - #[cfg(windows)] +-#[cfg(windows)] -fn shell_execute_error(code: isize) -> std::io::Error { - use std::io::{Error, ErrorKind}; - use windows_sys::Win32::{ @@ -4164,11 +4376,10 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - } -} - --#[cfg(windows)] + #[cfg(windows)] trait PathExt { fn wrap_in_quotes(&self) -> Self; - } -@@ -2116,13 +2473,13 @@ +@@ -2116,13 +2499,13 @@ // A throwaway key pair generated with `tauri signer generate`, and the signature of the // payload `test` made with `tauri signer sign --app-version 2.0.0`. @@ -4185,7 +4396,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd base64::engine::general_purpose::STANDARD.encode(value) } -@@ -2344,15 +2701,22 @@ +@@ -2344,15 +2727,22 @@ assert!(restored.context.config.require_signed_version); } @@ -4211,7 +4422,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd let update = builder() .executable_path(&appimage) .build() -@@ -2363,12 +2727,9 @@ +@@ -2363,12 +2753,9 @@ (dir, appimage, update) } @@ -4225,7 +4436,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } #[cfg(all(target_os = "linux", feature = "zip"))] -@@ -2389,11 +2750,12 @@ +@@ -2389,11 +2776,12 @@ #[cfg(target_os = "linux")] fn appimage_install_rejects_a_payload_that_is_not_an_appimage() { let (_dir, appimage, update) = appimage_update(); @@ -4240,7 +4451,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } #[test] -@@ -2402,7 +2764,6 @@ +@@ -2402,7 +2790,6 @@ use std::os::unix::fs::PermissionsExt; let (_dir, appimage, update) = appimage_update(); @@ -4248,7 +4459,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd update.install_appimage(&new_appimage()).unwrap(); assert_eq!(std::fs::read(&appimage).unwrap(), new_appimage()); assert_eq!( -@@ -2429,7 +2790,7 @@ +@@ -2429,7 +2816,7 @@ update.install_appimage(&compressed_appimage("readme.txt", b"hello")), Err(Error::BinaryNotFoundInArchive) )); @@ -4257,7 +4468,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } #[test] -@@ -2441,7 +2802,7 @@ +@@ -2441,7 +2828,7 @@ update.install_appimage(b"\x1f\x8b\x08\x00 compressed AppImage"), Err(Error::InvalidUpdaterFormat) )); @@ -4266,7 +4477,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd } } -@@ -2501,280 +2862,122 @@ +@@ -2501,277 +2888,119 @@ assert!(verify_signed_version(comment, "2024-01-02", true).is_err()); } @@ -4280,13 +4491,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - std::fs::write(target.join("version"), "old").unwrap(); - std::fs::create_dir(&staged).unwrap(); - std::fs::write(staged.join("version"), "new").unwrap(); -+ use super::{finish_windows_installer_launch, OnBeforeExit, Update, UpdaterContext}; -+ use crate::Config; -+ use std::sync::{ -+ atomic::{AtomicUsize, Ordering}, -+ Arc, -+ }; - +- - super::replace_bundle(&target, &staged, &backup).unwrap(); - - assert_eq!( @@ -4312,7 +4517,13 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - let name = unsafe { std::ffi::CStr::from_ptr(stat.f_fstypename.as_ptr()) }; - name.to_bytes() == b"apfs" - } -- ++ use super::{finish_windows_installer_launch, OnBeforeExit, Update, UpdaterContext}; ++ use crate::Config; ++ use std::sync::{ ++ atomic::{AtomicUsize, Ordering}, ++ Arc, ++ }; + - #[test] - #[cfg(target_os = "macos")] - fn swap_bundle_exchanges_the_two_bundles_in_place() { @@ -4395,20 +4606,10 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - assert_eq!( - std::fs::read_to_string(target.join("version")).unwrap(), - "old" -+ fn round2_actual_update_install_hook_failure_keeps_update_and_skips_cleanup() { -+ let hook_calls = Arc::new(AtomicUsize::new(0)); -+ let hook_calls_in = Arc::clone(&hook_calls); -+ let cleanup_calls = Arc::new(AtomicUsize::new(0)); -+ let update = round2_update_with_hook( -+ Arc::new(move || { -+ hook_calls_in.fetch_add(1, Ordering::SeqCst); -+ Err("round2 forced durable-state flush failure".to_string()) -+ }), -+ Arc::clone(&cleanup_calls), - ); +- ); - assert!(!backup.exists()); - } - +- - /// A directory whose name `sh` and AppleScript would both misread unquoted. - #[cfg(target_os = "macos")] - fn hostile_dir() -> tempfile::TempDir { @@ -4416,24 +4617,25 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - .prefix("it's \"a\" \\ $(touch pwned) `dir`\n") - .tempdir() - .unwrap() -+ let error = update -+ .install(b"test") -+ .expect_err("a failed pre-install hook must reject the actual install call"); -+ assert!(matches!( -+ error, -+ Error::BeforeExit(message) if message == "round2 forced durable-state flush failure" -+ )); -+ assert_eq!(hook_calls.load(Ordering::SeqCst), 1); -+ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 0); - } - +- } +- - #[cfg(target_os = "macos")] - fn assert_privileged_install_command_moved(dir: &std::path::Path) { - let target = dir.join("Bob's \"App\".app"); - assert_eq!( - std::fs::read_to_string(target.join("version")).unwrap(), - "new" -- ); ++ fn round2_actual_update_install_hook_failure_keeps_update_and_skips_cleanup() { ++ let hook_calls = Arc::new(AtomicUsize::new(0)); ++ let hook_calls_in = Arc::clone(&hook_calls); ++ let cleanup_calls = Arc::new(AtomicUsize::new(0)); ++ let update = round2_update_with_hook( ++ Arc::new(move || { ++ hook_calls_in.fetch_add(1, Ordering::SeqCst); ++ Err("round2 forced durable-state flush failure".to_string()) ++ }), ++ Arc::clone(&cleanup_calls), + ); - assert!(!dir.join("staged").exists()); - assert!(!dir.join("backup").exists()); - assert!(!dir.join("pwned").exists()); @@ -4450,7 +4652,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - super::privileged_install_command(&target, &staged, &dir.join("backup")) - } - - #[test] +- #[test] - #[cfg(target_os = "macos")] - fn privileged_install_command_quotes_every_path() { - let dir = hostile_dir(); @@ -4466,7 +4668,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - assert!(status.success()); - assert_privileged_install_command_moved(dir.path()); - } -- + - /// The command the install runs, wrapped the way it is handed to AppleScript, only without - /// `with administrator privileges` so it runs without a prompt. - #[test] @@ -4485,27 +4687,26 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - .output() - .unwrap(); - -+ fn round2_windows_cleanup_runs_only_after_a_successful_installer_launch() { -+ let events = std::cell::RefCell::new(Vec::new()); -+ let failure = finish_windows_installer_launch( -+ 32, -+ || events.borrow_mut().push("cleanup"), -+ || events.borrow_mut().push("exit"), -+ ); -+ assert!(failure.is_err()); - assert!( +- assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) -+ events.borrow().is_empty(), -+ "failed launch must preserve Tauri resources" - ); +- ); - assert_privileged_install_command_moved(dir.path()); -- } ++ let error = update ++ .install(b"test") ++ .expect_err("a failed pre-install hook must reject the actual install call"); ++ assert!(matches!( ++ error, ++ Error::BeforeExit(message) if message == "round2 forced durable-state flush failure" ++ )); ++ assert_eq!(hook_calls.load(Ordering::SeqCst), 1); ++ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 0); + } - /// The privileged install swaps the bundles where the file system can, so on APFS it - /// never touches the backup: one in a directory that does not exist must not matter. -- #[test] + #[test] - #[cfg(target_os = "macos")] - fn privileged_install_command_swaps_the_bundles() { - let dir = tempfile::tempdir().unwrap(); @@ -4530,18 +4731,17 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - assert_eq!( - std::fs::read_to_string(target.join("version")).unwrap(), - "new" -- ); -- assert!(!staged.exists()); -+ finish_windows_installer_launch( -+ 33, ++ fn round2_windows_cleanup_runs_only_after_a_successful_installer_launch() { ++ let events = std::cell::RefCell::new(Vec::new()); ++ let failure = finish_windows_installer_launch( ++ 32, + || events.borrow_mut().push("cleanup"), + || events.borrow_mut().push("exit"), -+ ) -+ .expect("successful launch must finish cleanup and exit sequence"); -+ assert_eq!(&*events.borrow(), &["cleanup", "exit"]); - } - - #[test] + ); +- assert!(!staged.exists()); +- } +- +- #[test] - fn keeps_the_backup_when_the_previous_app_was_not_restored() { - let dir = tempfile::tempdir().unwrap(); - let target = dir.path().join("App.app"); @@ -4558,19 +4758,15 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - assert_eq!( - std::fs::read_to_string(expected.join("version")).unwrap(), - "old" -- ); ++ assert!(failure.is_err()); ++ assert!( ++ events.borrow().is_empty(), ++ "failed launch must preserve Tauri resources" + ); - assert!(!backup_dir_path.exists()); -+ fn round2_download_cap_rejects_oversize_chunks_without_content_length() { -+ let mut received = Vec::new(); -+ super::append_download_chunk(&mut received, b"123", None, 4) -+ .expect("under-limit chunk should be accepted without a length header"); -+ let error = super::append_download_chunk(&mut received, b"45", None, 4) -+ .expect_err("actual streamed size must be capped without Content-Length"); -+ assert!(error.to_string().contains("package exceeds")); -+ assert_eq!(received, b"123", "over-limit bytes must not be buffered"); - } - - #[test] +- } +- +- #[test] - fn moves_the_backup_to_the_fallback_dir_when_it_cannot_go_next_to_the_app() { - let dir = tempfile::tempdir().unwrap(); - let target = dir.path().join("App.app"); @@ -4580,7 +4776,7 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - std::fs::create_dir(&backup).unwrap(); - std::fs::write(backup.join("version"), "old").unwrap(); - let fallback = tempfile::tempdir_in(dir.path()).unwrap(); -- + - let kept = - super::keep_backup_if_not_restored(&target, backup_dir, &backup, Some(fallback.path())); - @@ -4590,11 +4786,13 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - std::fs::read_to_string(expected.join("version")).unwrap(), - "old" - ); -+ fn round2_download_cap_rejects_declared_oversize_and_actual_oversize() { -+ let mut received = Vec::new(); -+ assert!(super::validate_download_content_length(Some(5), 4).is_err()); -+ assert!(super::append_download_chunk(&mut received, b"12345", Some(1), 4).is_err()); -+ assert!(received.is_empty(), "rejected bytes must not be buffered"); ++ finish_windows_installer_launch( ++ 33, ++ || events.borrow_mut().push("cleanup"), ++ || events.borrow_mut().push("exit"), ++ ) ++ .expect("successful launch must finish cleanup and exit sequence"); ++ assert_eq!(&*events.borrow(), &["cleanup", "exit"]); } #[test] @@ -4621,9 +4819,17 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - std::fs::read_to_string(dir.path().join("App (previous version).app")).unwrap(), - "other" - ); -- } -- -- #[test] ++ fn round2_download_cap_rejects_oversize_chunks_without_content_length() { ++ let mut received = Vec::new(); ++ super::append_download_chunk(&mut received, b"123", None, 4) ++ .expect("under-limit chunk should be accepted without a length header"); ++ let error = super::append_download_chunk(&mut received, b"45", None, 4) ++ .expect_err("actual streamed size must be capped without Content-Length"); ++ assert!(error.to_string().contains("package exceeds")); ++ assert_eq!(received, b"123", "over-limit bytes must not be buffered"); + } + + #[test] - fn drops_the_backup_when_the_previous_app_is_in_place() { - let dir = tempfile::tempdir().unwrap(); - let target = dir.path().join("App.app"); @@ -4635,18 +4841,18 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd - - assert!(super::keep_backup_if_not_restored(&target, backup_dir, &backup, None).is_none()); - assert!(!backup_dir_path.exists()); -- } -- -- #[test] - #[cfg(windows)] - fn it_wraps_correctly() { - use super::PathExt; -@@ -2874,6 +3077,195 @@ ++ fn round2_download_cap_rejects_declared_oversize_and_actual_oversize() { ++ let mut received = Vec::new(); ++ assert!(super::validate_download_content_length(Some(5), 4).is_err()); ++ assert!(super::append_download_chunk(&mut received, b"12345", Some(1), 4).is_err()); ++ assert!(received.is_empty(), "rejected bytes must not be buffered"); + } - for (orig, escaped) in cases.iter().zip(cases_escaped) { + #[test] +@@ -2876,4 +3105,213 @@ assert_eq!(escape_nsis_current_exe_arg(OsStr::new(orig)), escaped); -+ } -+ } + } + } + + #[test] + fn macos_admin_install_script_quotes_paths_via_handler_args() { @@ -4702,7 +4908,11 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + + fn app_tar(payload: &[u8]) -> Vec { + let mut builder = tar::Builder::new(Vec::new()); -+ for dir in ["ROSI.app/", "ROSI.app/Contents/", "ROSI.app/Contents/MacOS/"] { ++ for dir in [ ++ "ROSI.app/", ++ "ROSI.app/Contents/", ++ "ROSI.app/Contents/MacOS/", ++ ] { + let mut header = Header::new_gnu(); + header.set_entry_type(EntryType::Directory); + header.set_mode(0o755); @@ -4715,13 +4925,14 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + header.set_mode(0o755); + header.set_size(payload.len() as u64); + header.set_cksum(); -+ builder.append_data(&mut header, EXECUTABLE, payload).unwrap(); ++ builder ++ .append_data(&mut header, EXECUTABLE, payload) ++ .unwrap(); + builder.into_inner().unwrap() + } + + fn gzip(raw: &[u8]) -> Vec { -+ let mut encoder = -+ flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); ++ let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(raw).unwrap(); + encoder.finish().unwrap() + } @@ -4830,10 +5041,25 @@ diff -ruN -x target -x Cargo.lock -x .cargo-ok -x .cargo_vcs_info.json a/src/upd + crate::install_safety::macos_app_bundle_complete(dir.path()), + "{path}: extracted bundle is incomplete" + ); ++ let aarch64_ok = crate::install_safety::macos_bundle_supports_runtime_host( ++ dir.path(), ++ "aarch64", ++ false, ++ ); ++ let x86_64_ok = crate::install_safety::macos_bundle_supports_runtime_host( ++ dir.path(), ++ "x86_64", ++ false, ++ ); ++ let rosetta_ok = crate::install_safety::macos_bundle_supports_runtime_host( ++ dir.path(), ++ "x86_64", ++ true, ++ ); + println!( -+ "ROSI_UPDATER_ZST_E2E {path} extract_ms={}", ++ "ROSI_UPDATER_ZST_E2E {path} extract_ms={} aarch64={aarch64_ok} x86_64={x86_64_ok} rosetta={rosetta_ok}", + started.elapsed().as_millis() + ); - } - } ++ } ++ } } diff --git a/src-tauri/vendor/tauri-plugin-updater/src/appimage_archive.rs b/src-tauri/vendor/tauri-plugin-updater/src/appimage_archive.rs index edac1b08..54bf4869 100644 --- a/src-tauri/vendor/tauri-plugin-updater/src/appimage_archive.rs +++ b/src-tauri/vendor/tauri-plugin-updater/src/appimage_archive.rs @@ -1,5 +1,6 @@ -// The AppImage helpers are compiled for macOS only because the shared module -// list includes it; their callers are Linux and BSD only. Keep dead_code quiet there. +// Bounded tar.gz helpers. `extract_appimage_from_archive` is called by the Linux and BSD +// AppImage install path. On macOS, `BoundedArchiveReader` bounds app extraction, and the +// AppImage-only functions have no caller, so dead_code is allowed there. #![cfg_attr(target_os = "macos", allow(dead_code))] use super::{appimage_install, Error, Result}; diff --git a/src-tauri/vendor/tauri-plugin-updater/src/install_safety.rs b/src-tauri/vendor/tauri-plugin-updater/src/install_safety.rs index 4f5607df..56a42a8b 100644 --- a/src-tauri/vendor/tauri-plugin-updater/src/install_safety.rs +++ b/src-tauri/vendor/tauri-plugin-updater/src/install_safety.rs @@ -163,6 +163,178 @@ fn macos_bundle_executable_complete(path: &Path) -> bool { } } +#[cfg(target_os = "macos")] +fn is_rosetta_translated() -> bool { + let mut ret: libc::c_int = 0; + let mut size: libc::size_t = std::mem::size_of_val(&ret); + let name = c"sysctl.proc_translated"; + let res = unsafe { + libc::sysctlbyname( + name.as_ptr(), + &mut ret as *mut _ as *mut libc::c_void, + &mut size, + std::ptr::null_mut(), + 0, + ) + }; + res == 0 && ret == 1 +} + +#[cfg(not(target_os = "macos"))] +fn is_rosetta_translated() -> bool { + false +} + +/// Z02.4: verifies that a Mach-O executable supports the host architecture +/// before swapping into place. +pub fn macos_bundle_executable_supports_host_arch(path: &Path) -> bool { + macos_executable_supports_runtime_host(path, std::env::consts::ARCH, is_rosetta_translated()) +} + +pub fn macos_executable_supports_runtime_host( + path: &Path, + compile_arch: &str, + rosetta_translated: bool, +) -> bool { + let Ok(mut file) = std::fs::File::open(path) else { + return false; + }; + use std::io::Read; + let mut header = [0u8; 4096]; + let Ok(n) = file.read(&mut header) else { + return false; + }; + macho_bytes_support_runtime_host(&header[..n], compile_arch, rosetta_translated) +} + +pub fn macos_bundle_supports_runtime_host( + bundle_path: &Path, + compile_arch: &str, + rosetta_translated: bool, +) -> bool { + let Some(identity) = macos_app_bundle_identity(bundle_path) else { + return false; + }; + let macos_dir = bundle_path.join("Contents/MacOS"); + let executable = macos_dir.join(&identity.executable); + if !macos_executable_supports_runtime_host(&executable, compile_arch, rosetta_translated) { + return false; + } + ["rosi-yt-dlp", "rosi-ffmpeg", "rosi-ffprobe"] + .iter() + .all(|sidecar| { + macos_executable_supports_runtime_host( + &macos_dir.join(sidecar), + compile_arch, + rosetta_translated, + ) + }) +} + +pub fn macho_bytes_support_host_arch(bytes: &[u8]) -> bool { + macho_bytes_support_runtime_host(bytes, std::env::consts::ARCH, is_rosetta_translated()) +} + +pub fn macho_bytes_support_runtime_host( + bytes: &[u8], + compile_arch: &str, + rosetta_translated: bool, +) -> bool { + match compile_arch { + "aarch64" => macho_bytes_support_arch(bytes, "aarch64"), + "x86_64" if rosetta_translated => { + macho_bytes_support_arch(bytes, "aarch64") || macho_bytes_support_arch(bytes, "x86_64") + } + "x86_64" => macho_bytes_support_arch(bytes, "x86_64"), + _ => false, + } +} + +pub fn macho_bytes_support_arch(bytes: &[u8], target_arch: &str) -> bool { + const MH_MAGIC_64: [u8; 4] = [0xcf, 0xfa, 0xed, 0xfe]; + const MH_CIGAM_64: [u8; 4] = [0xfe, 0xed, 0xfa, 0xcf]; + const FAT_MAGIC: [u8; 4] = [0xca, 0xfe, 0xba, 0xbe]; + const FAT_CIGAM: [u8; 4] = [0xbe, 0xba, 0xfe, 0xca]; + const FAT_MAGIC_64: [u8; 4] = [0xca, 0xfe, 0xba, 0xbf]; + const FAT_CIGAM_64: [u8; 4] = [0xbf, 0xba, 0xfe, 0xca]; + + const CPU_TYPE_X86_64: u32 = 0x01000007; + const CPU_TYPE_ARM64: u32 = 0x0100000c; + + let expected_cputype = match target_arch { + "aarch64" | "arm64" => CPU_TYPE_ARM64, + "x86_64" | "amd64" => CPU_TYPE_X86_64, + _ => return false, + }; + + if bytes.len() < 8 { + return false; + } + + if bytes.starts_with(&MH_MAGIC_64) { + let cputype = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + return cputype == expected_cputype; + } + if bytes.starts_with(&MH_CIGAM_64) { + let cputype = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + return cputype == expected_cputype; + } + if bytes.starts_with(&FAT_MAGIC) || bytes.starts_with(&FAT_CIGAM) { + let is_be = bytes.starts_with(&FAT_MAGIC); + let nfat = if is_be { + u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) + } else { + u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) + }; + let count = (nfat as usize).min(64); + for i in 0..count { + let Some(offset) = i.checked_mul(20).and_then(|o| o.checked_add(8)) else { + return false; + }; + let Some(slice) = bytes.get(offset..offset + 4) else { + return false; + }; + let cputype = if is_be { + u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]) + } else { + u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) + }; + if cputype == expected_cputype { + return true; + } + } + return false; + } + if bytes.starts_with(&FAT_MAGIC_64) || bytes.starts_with(&FAT_CIGAM_64) { + let is_be = bytes.starts_with(&FAT_MAGIC_64); + let nfat = if is_be { + u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) + } else { + u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) + }; + let count = (nfat as usize).min(64); + for i in 0..count { + let Some(offset) = i.checked_mul(32).and_then(|o| o.checked_add(8)) else { + return false; + }; + let Some(slice) = bytes.get(offset..offset + 4) else { + return false; + }; + let cputype = if is_be { + u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]) + } else { + u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) + }; + if cputype == expected_cputype { + return true; + } + } + return false; + } + + false +} + /// Session variables pkexec, zenity, and polkit agents need after `env_clear`. /// Never includes `PATH`. pub const LINUX_PRIVILEGED_ENV_ALLOWLIST: &[&str] = &[ diff --git a/src-tauri/vendor/tauri-plugin-updater/src/updater.rs b/src-tauri/vendor/tauri-plugin-updater/src/updater.rs index 49777dea..927d900a 100644 --- a/src-tauri/vendor/tauri-plugin-updater/src/updater.rs +++ b/src-tauri/vendor/tauri-plugin-updater/src/updater.rs @@ -50,15 +50,19 @@ use crate::{ #[path = "appimage_install.rs"] mod appimage_install; -#[cfg(all( - feature = "zip", - any( - target_os = "linux", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "macos" +// macOS app extraction uses `BoundedArchiveReader` from this module. Its flate2 +// and tar dependencies are unconditional on macOS, so macOS does not need `zip`. +#[cfg(any( + target_os = "macos", + all( + feature = "zip", + any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ) ) ))] #[path = "appimage_archive.rs"] @@ -1712,6 +1716,28 @@ impl Update { ))); } + let staged_executable = tmp_extract_dir + .path() + .join("Contents/MacOS") + .join(&expected_identity.executable); + if !crate::install_safety::macos_bundle_executable_supports_host_arch(&staged_executable) { + return Err(Error::Io(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "staged updater executable does not support the host architecture", + ))); + } + for sidecar in ["rosi-yt-dlp", "rosi-ffmpeg", "rosi-ffprobe"] { + let sidecar_path = tmp_extract_dir.path().join("Contents/MacOS").join(sidecar); + if !crate::install_safety::macos_bundle_executable_supports_host_arch(&sidecar_path) { + return Err(Error::Io(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!( + "staged updater sidecar {sidecar} does not support the host architecture" + ), + ))); + } + } + // Recovery can mutate a protected install tree. Delay it until the // downloaded bundle has passed identity and completeness validation, // then route only permission failures through the existing admin path. @@ -3134,7 +3160,11 @@ mod macos_archive_tests { fn app_tar(payload: &[u8]) -> Vec { let mut builder = tar::Builder::new(Vec::new()); - for dir in ["ROSI.app/", "ROSI.app/Contents/", "ROSI.app/Contents/MacOS/"] { + for dir in [ + "ROSI.app/", + "ROSI.app/Contents/", + "ROSI.app/Contents/MacOS/", + ] { let mut header = Header::new_gnu(); header.set_entry_type(EntryType::Directory); header.set_mode(0o755); @@ -3147,13 +3177,14 @@ mod macos_archive_tests { header.set_mode(0o755); header.set_size(payload.len() as u64); header.set_cksum(); - builder.append_data(&mut header, EXECUTABLE, payload).unwrap(); + builder + .append_data(&mut header, EXECUTABLE, payload) + .unwrap(); builder.into_inner().unwrap() } fn gzip(raw: &[u8]) -> Vec { - let mut encoder = - flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); encoder.write_all(raw).unwrap(); encoder.finish().unwrap() } @@ -3262,8 +3293,23 @@ mod macos_archive_tests { crate::install_safety::macos_app_bundle_complete(dir.path()), "{path}: extracted bundle is incomplete" ); + let aarch64_ok = crate::install_safety::macos_bundle_supports_runtime_host( + dir.path(), + "aarch64", + false, + ); + let x86_64_ok = crate::install_safety::macos_bundle_supports_runtime_host( + dir.path(), + "x86_64", + false, + ); + let rosetta_ok = crate::install_safety::macos_bundle_supports_runtime_host( + dir.path(), + "x86_64", + true, + ); println!( - "ROSI_UPDATER_ZST_E2E {path} extract_ms={}", + "ROSI_UPDATER_ZST_E2E {path} extract_ms={} aarch64={aarch64_ok} x86_64={x86_64_ok} rosetta={rosetta_ok}", started.elapsed().as_millis() ); } diff --git a/src/updater.ts b/src/updater.ts index 342740a9..1a212be0 100644 --- a/src/updater.ts +++ b/src/updater.ts @@ -204,18 +204,33 @@ async function checkFeed( ): Promise { if (!target?.endsWith(COMPACT_TARGET_SUFFIX)) return checkTargetFeed(target, isCurrent); try { - return await checkTargetFeed(target, isCurrent); - } catch { + // No in-place retry: the legacy target below is the retry. + return await checkTargetFeed(target, isCurrent, false); + } catch (error) { if (!isCurrent()) return null; // A release published without per-arch zstd archives still updates // through the universal .app.tar.gz feed. - return checkTargetFeed(legacyTarget(target), isCurrent); + const fallback = legacyTarget(target); + reportCompactFallback(target, fallback, error); + return checkTargetFeed(fallback, isCurrent); + } +} + +// Logs why a compact check fell back. Logging must never change the check. +function reportCompactFallback(target: string, fallback: string | undefined, error: unknown): void { + try { + console.warn( + `[rosi] updater: ${target} check failed, falling back to ${fallback ?? 'the default'} target: ${errorMessage(error)}` + ); + } catch { + // Ignore logging failures. } } async function checkTargetFeed( target: string | undefined, - isCurrent: () => boolean + isCurrent: () => boolean, + retryOnError = true ): Promise { const testCheck = e2eUpdaterAdapter()?.check; if (testCheck) { @@ -232,7 +247,7 @@ async function checkTargetFeed( update = await check(options); } catch (error) { if (!isCurrent()) return null; - if (!target) throw error; + if (!target || !retryOnError) throw error; return check(options); } if (!isCurrent()) { diff --git a/testdata/updater/latest-darwin-aarch64-app-zst.json b/testdata/updater/latest-darwin-aarch64-app-zst.json new file mode 100644 index 00000000..593b9d4b --- /dev/null +++ b/testdata/updater/latest-darwin-aarch64-app-zst.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.0-fixture", + "pub_date": "2026-07-18T00:00:00Z", + "notes": "Fixture for per-arch macOS app-zst updater manifest keys (not a release pin).", + "platforms": { + "darwin-aarch64-app-zst": { + "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI-aarch64.app.tar.zst", + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" + } + } +} diff --git a/testdata/updater/latest-darwin-aarch64.json b/testdata/updater/latest-darwin-aarch64.json index 628417bd..68cc2cbb 100644 --- a/testdata/updater/latest-darwin-aarch64.json +++ b/testdata/updater/latest-darwin-aarch64.json @@ -5,7 +5,7 @@ "platforms": { "darwin-aarch64": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_aarch64.app.tar.gz", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" } } } diff --git a/testdata/updater/latest-darwin-beta-aarch64-app-zst.json b/testdata/updater/latest-darwin-beta-aarch64-app-zst.json new file mode 100644 index 00000000..de25ef9a --- /dev/null +++ b/testdata/updater/latest-darwin-beta-aarch64-app-zst.json @@ -0,0 +1,11 @@ +{ + "version": "0.0.0-fixture", + "pub_date": "2026-07-18T00:00:00Z", + "notes": "Fixture for beta-shaped per-arch macOS app-zst updater manifest keys (not a release pin).", + "platforms": { + "darwin-beta-aarch64-app-zst": { + "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI-aarch64.app.tar.zst", + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" + } + } +} diff --git a/testdata/updater/latest-darwin-beta-aarch64.json b/testdata/updater/latest-darwin-beta-aarch64.json index 97b2f728..6c7c7d07 100644 --- a/testdata/updater/latest-darwin-beta-aarch64.json +++ b/testdata/updater/latest-darwin-beta-aarch64.json @@ -5,11 +5,11 @@ "platforms": { "darwin-beta-aarch64": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_aarch64.app.tar.gz", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" }, "darwin-beta": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_aarch64.app.tar.gz", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" } } } diff --git a/testdata/updater/latest-darwin-x86_64.json b/testdata/updater/latest-darwin-x86_64.json index 74d81a2b..560b06e1 100644 --- a/testdata/updater/latest-darwin-x86_64.json +++ b/testdata/updater/latest-darwin-x86_64.json @@ -5,7 +5,7 @@ "platforms": { "darwin-x86_64": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_x64.app.tar.gz", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" } } } diff --git a/testdata/updater/latest-linux-x86_64.json b/testdata/updater/latest-linux-x86_64.json index 3b70e86e..879f9463 100644 --- a/testdata/updater/latest-linux-x86_64.json +++ b/testdata/updater/latest-linux-x86_64.json @@ -5,11 +5,11 @@ "platforms": { "linux-x86_64": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_0.0.0-fixture_amd64.AppImage", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" }, "linux-x86_64-appimage": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_0.0.0-fixture_amd64.AppImage", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" } } } diff --git a/testdata/updater/latest-windows-aarch64.json b/testdata/updater/latest-windows-aarch64.json index 347fb36f..42665570 100644 --- a/testdata/updater/latest-windows-aarch64.json +++ b/testdata/updater/latest-windows-aarch64.json @@ -5,11 +5,11 @@ "platforms": { "windows-aarch64-nsis": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_0.0.0-fixture_arm64-setup.exe", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" }, "windows-aarch64": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_0.0.0-fixture_arm64-setup.exe", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" } } } diff --git a/testdata/updater/latest-windows-x86_64.json b/testdata/updater/latest-windows-x86_64.json index e747fbd8..99388b24 100644 --- a/testdata/updater/latest-windows-x86_64.json +++ b/testdata/updater/latest-windows-x86_64.json @@ -5,11 +5,11 @@ "platforms": { "windows-x86_64-nsis": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_0.0.0-fixture_x64-setup.exe", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" }, "windows-x86_64": { "url": "https://github.com/BurntToasters/ROSI/releases/download/v0.0.0-fixture/ROSI_0.0.0-fixture_x64-setup.exe", - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCkFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPT0=" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIG1pbmlzaWduIHNlY3JldCBrZXkKUldRQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDowCXZlcnNpb246MC4wLjAtZml4dHVyZQpBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQT09" } } } From 31f75ec07159e8af2a7f1f243a98451a31a1fb58 Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:41:02 -0700 Subject: [PATCH 03/58] Codebase: Migrate toolchain to Node.js 26.13.0 LTS. --- .github/workflows/ci.yml | 4 ++-- .github/workflows/ytdlp-watch.yml | 3 ++- build-setup.md | 6 +++--- package-lock.json | 4 ++-- package.json | 6 +++--- scripts/cargo-safe-update.test.mjs | 17 +++++++++-------- scripts/npm-safe-update.mjs | 9 +++++---- vitest.config.ts | 1 + 8 files changed, 27 insertions(+), 23 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 84b35715..bf4f88a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,8 +29,8 @@ permissions: contents: read env: - NODE_VERSION: "24.16.0" - NPM_VERSION: "12.0.2" + NODE_VERSION: "26.13.0" + NPM_VERSION: "12.2.1" RUST_VERSION: "1.98.1" CARGO_AUDIT_VERSION: "0.22.2" diff --git a/.github/workflows/ytdlp-watch.yml b/.github/workflows/ytdlp-watch.yml index 8935e607..8fdc5ca4 100644 --- a/.github/workflows/ytdlp-watch.yml +++ b/.github/workflows/ytdlp-watch.yml @@ -23,7 +23,8 @@ permissions: contents: read env: - NODE_VERSION: "24.16.0" + NODE_VERSION: "26.13.0" + NPM_VERSION: "12.2.1" jobs: watch: diff --git a/build-setup.md b/build-setup.md index b71dfa33..5a3ba4da 100644 --- a/build-setup.md +++ b/build-setup.md @@ -11,7 +11,7 @@ Build from a VS developer shell (`npm run win-compiler:arm64` or `win-compiler:x64`), which puts that clang on `PATH`; a plain PowerShell window does not. -- Node.js `^24.15.0 || >=26` (`engines.node` in package.json) +- Node.js `^24.22.1 || >=26.13.0` (`engines.node` in package.json) - Rust (rustup) - Azure Artifact Signing: once per release VM, as Administrator, run `npm run setup:win:artifact-signing` @@ -23,7 +23,7 @@ any bundled Mach-O whose minimum OS is above that floor. - Xcode Command Line Tools (`lipo`, `codesign`, `notarytool`) - zstd CLI (`brew install zstd`) for the updater archives; checked by `npm run prerelease:prepare` -- Node.js `^24.15.0 || >=26` +- Node.js `^24.22.1 || >=26.13.0` - Rust (rustup) ## Linux @@ -32,7 +32,7 @@ baseline. - `npm run setup:deb` installs the Ubuntu build, E2E (xvfb), 7-Zip (for `get:ffmpeg`), and Flatpak prerequisites. -- Node.js `^24.15.0 || >=26` +- Node.js `^24.22.1 || >=26.13.0` - Rust (rustup) - Linux v5 releases ship x64 only (`npm run release:linux:x64`). ARM64 wiring (`release:linux:arm64`, `build:linux:arm64`) remains for future development diff --git a/package-lock.json b/package-lock.json index 83d56735..dcd25dd0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,8 +38,8 @@ "vitest": "4.1.11" }, "engines": { - "node": "^24.15.0 || >=26.0.0", - "npm": ">=12.0.2" + "node": "^24.22.1 || >=26.13.0", + "npm": ">=12.2.1" } }, "node_modules/@asamuzakjp/css-color": { diff --git a/package.json b/package.json index d1eb9b2e..2093c584 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "5.1.0-beta.1", "license": "MPL-2.0", "private": true, - "packageManager": "npm@12.0.2", + "packageManager": "npm@12.2.1", "description": "Cross-platform yt-dlp GUI built with Tauri.", "type": "module", "keywords": [ @@ -13,8 +13,8 @@ "cross-platform" ], "engines": { - "node": "^24.15.0 || >=26.0.0", - "npm": ">=12.0.2" + "node": "^24.22.1 || >=26.13.0", + "npm": ">=12.2.1" }, "repository": { "type": "git", diff --git a/scripts/cargo-safe-update.test.mjs b/scripts/cargo-safe-update.test.mjs index 5ea8a7ea..9a6c8e6b 100644 --- a/scripts/cargo-safe-update.test.mjs +++ b/scripts/cargo-safe-update.test.mjs @@ -1568,18 +1568,19 @@ test("44. deceptive registry baseline cannot preserve a too-young release", () = }); test("45. update environment versions fail closed at exact boundaries", () => { - assert.deepEqual(parseVersion("12.0.1"), [12, 0, 1]); - assert.equal(isVersionAtLeast("12.0.1", MINIMUM_NPM_VERSION), true); - assert.equal(isVersionAtLeast("12.1.0", MINIMUM_NPM_VERSION), true); - assert.equal(isVersionAtLeast("12.0.0", MINIMUM_NPM_VERSION), false); + assert.deepEqual(parseVersion("12.2.1"), [12, 2, 1]); + assert.equal(isVersionAtLeast("12.2.1", MINIMUM_NPM_VERSION), true); + assert.equal(isVersionAtLeast("12.3.0", MINIMUM_NPM_VERSION), true); + assert.equal(isVersionAtLeast("12.2.0", MINIMUM_NPM_VERSION), false); assert.equal(isVersionAtLeast("11.99.99", MINIMUM_NPM_VERSION), false); assert.equal(isSupportedNodeVersion("22.22.2"), false); - assert.equal(isSupportedNodeVersion("22.99.99"), false); assert.equal(isSupportedNodeVersion("23.99.99"), false); - assert.equal(isSupportedNodeVersion("24.15.0"), true); - assert.equal(isSupportedNodeVersion("24.14.9"), false); + assert.equal(isSupportedNodeVersion("24.22.0"), false); + assert.equal(isSupportedNodeVersion("24.22.1"), true); assert.equal(isSupportedNodeVersion("25.99.99"), false); - assert.equal(isSupportedNodeVersion("26.0.0"), true); + assert.equal(isSupportedNodeVersion("26.12.9"), false); + assert.equal(isSupportedNodeVersion("26.13.0"), true); + assert.equal(isSupportedNodeVersion("27.0.0"), true); assert.throws(() => parseVersion("latest"), /Invalid semantic version/); }); diff --git a/scripts/npm-safe-update.mjs b/scripts/npm-safe-update.mjs index c642c002..f51fd4ee 100644 --- a/scripts/npm-safe-update.mjs +++ b/scripts/npm-safe-update.mjs @@ -25,8 +25,8 @@ const npmDevAuditScript = fileURLToPath( new URL("./npm-dev-audit.cjs", import.meta.url), ); -export const MINIMUM_NPM_VERSION = "12.0.1"; -export const SUPPORTED_NODE_VERSIONS = "^24.15.0 || >=26.0.0"; +export const MINIMUM_NPM_VERSION = "12.2.1"; +export const SUPPORTED_NODE_VERSIONS = "^24.22.1 || >=26.13.0"; export function readPinnedRustToolchain(root) { const filePath = path.join(root, "rust-toolchain.toml"); @@ -71,8 +71,9 @@ export function isVersionAtLeast(value, minimum) { export function isSupportedNodeVersion(value) { const [major] = parseVersion(value); - if (major === 24) return isVersionAtLeast(value, "24.15.0"); - return major >= 26; + if (major === 24) return isVersionAtLeast(value, "24.22.1"); + if (major === 26) return isVersionAtLeast(value, "26.13.0"); + return major > 26; } export function hasRustToolchain(output, toolchain) { diff --git a/vitest.config.ts b/vitest.config.ts index aaca9932..c374be2f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { environment: 'jsdom', + execArgv: Number(process.versions.node.split('.')[0]) >= 25 ? ['--no-webstorage'] : [], include: ['src/tests/**/*.test.ts'], restoreMocks: true, testTimeout: 10_000, From f6e8d5a0b7588e0f59841fc033db97c5baf2c0cd Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:53:39 -0800 Subject: [PATCH 04/58] bumped pinned rust version to 1.99.1 --- .github/workflows/ci.yml | 2 +- build-setup.md | 2 +- package.json | 12 ++++++------ run.rosie.rosi.yml | 2 +- rust-toolchain.toml | 2 +- scripts/cargo-safe-update.test.mjs | 10 +++++----- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf4f88a7..c2087ed5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,7 @@ permissions: env: NODE_VERSION: "26.13.0" NPM_VERSION: "12.2.1" - RUST_VERSION: "1.98.1" + RUST_VERSION: "1.99.1" CARGO_AUDIT_VERSION: "0.22.2" jobs: diff --git a/build-setup.md b/build-setup.md index 5a3ba4da..e09da029 100644 --- a/build-setup.md +++ b/build-setup.md @@ -40,7 +40,7 @@ ## Rust toolchain policy -ROSI builds with Rust `1.98.1`, pinned in `rust-toolchain.toml` and used by CI, +ROSI builds with Rust `1.99.1`, pinned in `rust-toolchain.toml` and used by CI, Flatpak, and release builds. Install that exact toolchain before building: ```sh diff --git a/package.json b/package.json index 2093c584..d084937e 100644 --- a/package.json +++ b/package.json @@ -119,12 +119,12 @@ "flatpak:bundle": "node scripts/prepare-flatpak-source.js && flatpak-builder --repo=flatpak-repo --force-clean flatpak-build run.rosie.rosi.yml && flatpak build-bundle flatpak-repo dist/ROSI-Linux-x64.flatpak run.rosie.rosi", "flatpak:clean": "node -e \"for (const d of ['flatpak-build','flatpak-repo']) require('fs').rmSync(d,{recursive:true,force:true})\"", "flatpak:run": "flatpak run run.rosie.rosi", - "rust:update": "rustup toolchain install 1.98.1 --profile minimal --component cargo,clippy,rustfmt", - "rust:targets:win": "rustup target add --toolchain 1.98.1 x86_64-pc-windows-msvc aarch64-pc-windows-msvc", - "rust:targets:mac": "rustup target add --toolchain 1.98.1 x86_64-apple-darwin aarch64-apple-darwin", - "rust:targets:linux": "rustup target add --toolchain 1.98.1 x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu", - "rust:target:linux:x64": "rustup target add --toolchain 1.98.1 x86_64-unknown-linux-gnu", - "rust:target:linux:arm64": "rustup target add --toolchain 1.98.1 aarch64-unknown-linux-gnu", + "rust:update": "rustup toolchain install 1.99.1 --profile minimal --component cargo,clippy,rustfmt", + "rust:targets:win": "rustup target add --toolchain 1.99.1 x86_64-pc-windows-msvc aarch64-pc-windows-msvc", + "rust:targets:mac": "rustup target add --toolchain 1.99.1 x86_64-apple-darwin aarch64-apple-darwin", + "rust:targets:linux": "rustup target add --toolchain 1.99.1 x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu", + "rust:target:linux:x64": "rustup target add --toolchain 1.99.1 x86_64-unknown-linux-gnu", + "rust:target:linux:arm64": "rustup target add --toolchain 1.99.1 aarch64-unknown-linux-gnu", "workspace:bootstrap": "npm run rust:update && npm ci --ignore-scripts && npm run sync-version && npm run ytdlp:fetch && npm run ytdlp:check && npm run ffmpeg:ensure && npm run prepare:sidecars", "workspace:prepare": "npm run workspace:bootstrap && npm run test:all -- --require-clean-proof", "release:prepare": "npm run workspace:bootstrap && npm run test:all -- --require-clean-proof --skip-e2e && npm run dist:clean-release-artifacts", diff --git a/run.rosie.rosi.yml b/run.rosie.rosi.yml index 8c4d80e4..3cd07b0f 100644 --- a/run.rosie.rosi.yml +++ b/run.rosie.rosi.yml @@ -46,7 +46,7 @@ modules: build-commands: # The Flatpak rust-stable SDK extension installs rustc/cargo directly, # not through rustup. Fail closed if that extension drifts from our pin. - - test "$(rustc --version | cut -d' ' -f2)" = 1.98.1 + - test "$(rustc --version | cut -d' ' -f2)" = 1.99.1 # The node24 SDK ships npm 11, older than the npm 12 that engines requires. # npm@12 plus --before 3 days ago takes the newest 12.x that is old enough. - npm install --global npm@12 --ignore-scripts --engine-strict=false --before="$(date -u -d '3 days ago' +%Y-%m-%dT%H:%M:%SZ)" --prefix /run/build/rosi/npm-global diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 96b62512..1f49eff4 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.98.1" +channel = "1.99.1" profile = "minimal" components = ["cargo", "clippy", "rustfmt"] diff --git a/scripts/cargo-safe-update.test.mjs b/scripts/cargo-safe-update.test.mjs index 9a6c8e6b..c7e710ad 100644 --- a/scripts/cargo-safe-update.test.mjs +++ b/scripts/cargo-safe-update.test.mjs @@ -1585,15 +1585,15 @@ test("45. update environment versions fail closed at exact boundaries", () => { }); // Failure modes covered: a floating `stable` toolchain passes without the -// repository pin; a prefix match accepts 1.98.10 for 1.98.1; rustup's +// repository pin; a prefix match accepts 1.99.10 for 1.99.1; rustup's // host-qualified exact version is rejected; or a malformed pin passes. test("45a. npm updater requires exact repository-pinned Rust toolchain", () => { const root = process.cwd(); const pinned = readPinnedRustToolchain(root); - assert.equal(pinned, "1.98.1"); - assert.equal(hasRustToolchain("1.98.1\n", pinned), true); + assert.equal(pinned, "1.99.1"); + assert.equal(hasRustToolchain("1.99.1\n", pinned), true); assert.equal( - hasRustToolchain("1.98.1-aarch64-apple-darwin (default)\n", pinned), + hasRustToolchain("1.99.1-aarch64-apple-darwin (default)\n", pinned), true, ); assert.equal(hasRustToolchain("stable\n", pinned), false); @@ -1602,7 +1602,7 @@ test("45a. npm updater requires exact repository-pinned Rust toolchain", () => { false, ); assert.equal( - hasRustToolchain("1.98.10-aarch64-apple-darwin\n", pinned), + hasRustToolchain("1.99.10-aarch64-apple-darwin\n", pinned), false, ); From a362b9d78c663fba60c73bc21e60c98eba9e56f0 Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:56:28 -0800 Subject: [PATCH 05/58] Toolchain: Build Flatpak with the pinned Rust toolchain. --- run.rosie.rosi.yml | 14 ++++++++------ scripts/validate-flatpak-dry-run.js | 12 +++++++++--- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/run.rosie.rosi.yml b/run.rosie.rosi.yml index 3cd07b0f..cf12a3af 100644 --- a/run.rosie.rosi.yml +++ b/run.rosie.rosi.yml @@ -1,6 +1,6 @@ app-id: run.rosie.rosi runtime: org.gnome.Platform -runtime-version: "50" +runtime-version: '50' sdk: org.gnome.Sdk sdk-extensions: - org.freedesktop.Sdk.Extension.node24 @@ -27,7 +27,7 @@ finish-args: # Flatpak builds update by reinstalling the bundle, not the in-app updater. environment: - GTK_USE_PORTAL: "1" + GTK_USE_PORTAL: '1' modules: - name: rosi @@ -38,14 +38,16 @@ modules: # commit export prepared by scripts/prepare-flatpak-source.js. build-args: - --share=network - append-path: /run/build/rosi/npm-global/bin:/usr/lib/sdk/node24/bin:/usr/lib/sdk/rust-stable/bin + prepend-path: /run/build/rosi/cargo/bin:/run/build/rosi/npm-global/bin:/usr/lib/sdk/node24/bin:/usr/lib/sdk/rust-stable/bin env: CARGO_HOME: /run/build/rosi/cargo + RUSTUP_HOME: /run/build/rosi/rustup npm_config_cache: /run/build/rosi/npm-cache - HUSKY: "0" + HUSKY: '0' build-commands: - # The Flatpak rust-stable SDK extension installs rustc/cargo directly, - # not through rustup. Fail closed if that extension drifts from our pin. + # The Flathub rust-stable SDK extension lags the pinned toolchain, so + # install rustup and the exact pinned compiler inside the sandbox. + - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.99.1 --profile minimal - test "$(rustc --version | cut -d' ' -f2)" = 1.99.1 # The node24 SDK ships npm 11, older than the npm 12 that engines requires. # npm@12 plus --before 3 days ago takes the newest 12.x that is old enough. diff --git a/scripts/validate-flatpak-dry-run.js b/scripts/validate-flatpak-dry-run.js index 80cb2d2f..586138bd 100644 --- a/scripts/validate-flatpak-dry-run.js +++ b/scripts/validate-flatpak-dry-run.js @@ -18,7 +18,7 @@ const required = [ "scripts/prepare-flatpak-source.js", "scripts/prepare-sidecars.js", ]; -const expectedRuntime = 'runtime-version: "50"'; +const expectedRuntime = "runtime-version: '50'"; const rustToolchain = fs .readFileSync(path.join(root, "rust-toolchain.toml"), "utf8") .match(/^channel = "(\d+\.\d+\.\d+)"$/m)?.[1]; @@ -70,16 +70,22 @@ if (fs.existsSync(manifest)) { if (!yaml.includes("tauri build --no-bundle -- --locked")) { fail("Cargo build must enforce Cargo.lock"); } + const cargoBin = "/run/build/rosi/cargo/bin"; + const prependPath = yaml.match(/^\s*prepend-path: (.+)$/m)?.[1]?.split(":"); if ( !rustToolchain || !yaml.includes( `test "$(rustc --version | cut -d' ' -f2)" = ${rustToolchain}`, ) || - yaml.includes("rustup toolchain install") || + !yaml.includes( + "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs", + ) || + !yaml.includes("RUSTUP_HOME: /run/build/rosi/rustup") || + !prependPath?.includes(cargoBin) || yaml.includes("RUSTUP_TOOLCHAIN:") ) { fail( - "Rust SDK extension must fail closed on the exact pinned compiler without invoking unavailable rustup", + "Flatpak must install the exact pinned compiler with rustup inside the sandbox and fail closed on the exact pin", ); } if (!yaml.includes("Unsupported FLATPAK_ARCH")) { From f47b617d38a3540b04acbf88a6a493409d7e946f Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:53:31 -0800 Subject: [PATCH 06/58] Toolchain: Derive Rust pin from rust-toolchain.toml --- .github/workflows/ci.yml | 41 ++++- docs/DEPENDENCY_UPDATES.md | 42 +++++ package.json | 12 +- run.rosie.rosi.yml | 10 +- scripts/cargo-safe-update.test.mjs | 15 +- scripts/npm-safe-update.mjs | 26 +-- scripts/rust-toolchain.mjs | 254 ++++++++++++++++++++++++++++ scripts/validate-flatpak-dry-run.js | 30 +++- 8 files changed, 380 insertions(+), 50 deletions(-) create mode 100644 docs/DEPENDENCY_UPDATES.md create mode 100644 scripts/rust-toolchain.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c2087ed5..d494d89a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,6 @@ permissions: env: NODE_VERSION: "26.13.0" NPM_VERSION: "12.2.1" - RUST_VERSION: "1.99.1" CARGO_AUDIT_VERSION: "0.22.2" jobs: @@ -74,9 +73,17 @@ jobs: cache: npm - name: Install latest npm 12 run: npm install --global npm@${{ env.NPM_VERSION }} --ignore-scripts --min-release-age=3 + - name: Read pinned Rust toolchain + id: rust-toolchain + shell: bash + run: | + set -euo pipefail + channel="$(node scripts/rust-toolchain.mjs)" + test -n "$channel" + echo "channel=$channel" >> "$GITHUB_OUTPUT" - uses: dtolnay/rust-toolchain@4be7066ada62dd38de10e7b70166bc74ed198c30 # stable with: - toolchain: ${{ env.RUST_VERSION }} + toolchain: ${{ steps.rust-toolchain.outputs.channel }} components: rustfmt, clippy - name: Install Linux dependencies run: | @@ -127,9 +134,17 @@ jobs: cache: npm - name: Install latest npm 12 run: npm install --global npm@${{ env.NPM_VERSION }} --ignore-scripts --min-release-age=3 + - name: Read pinned Rust toolchain + id: rust-toolchain + shell: bash + run: | + set -euo pipefail + channel="$(node scripts/rust-toolchain.mjs)" + test -n "$channel" + echo "channel=$channel" >> "$GITHUB_OUTPUT" - uses: dtolnay/rust-toolchain@4be7066ada62dd38de10e7b70166bc74ed198c30 # stable with: - toolchain: ${{ env.RUST_VERSION }} + toolchain: ${{ steps.rust-toolchain.outputs.channel }} components: clippy - run: npm ci --ignore-scripts # On windows-latest gpg ships only in Git for Windows (usr\bin), which is @@ -222,9 +237,17 @@ jobs: cache: npm - name: Install latest npm 12 run: npm install --global npm@${{ env.NPM_VERSION }} --ignore-scripts --min-release-age=3 + - name: Read pinned Rust toolchain + id: rust-toolchain + shell: bash + run: | + set -euo pipefail + channel="$(node scripts/rust-toolchain.mjs)" + test -n "$channel" + echo "channel=$channel" >> "$GITHUB_OUTPUT" - uses: dtolnay/rust-toolchain@4be7066ada62dd38de10e7b70166bc74ed198c30 # stable with: - toolchain: ${{ env.RUST_VERSION }} + toolchain: ${{ steps.rust-toolchain.outputs.channel }} - name: Install Linux dependencies if: runner.os == 'Linux' run: | @@ -269,9 +292,17 @@ jobs: cache: npm - name: Install latest npm 12 run: npm install --global npm@${{ env.NPM_VERSION }} --ignore-scripts --min-release-age=3 + - name: Read pinned Rust toolchain + id: rust-toolchain + shell: bash + run: | + set -euo pipefail + channel="$(node scripts/rust-toolchain.mjs)" + test -n "$channel" + echo "channel=$channel" >> "$GITHUB_OUTPUT" - uses: dtolnay/rust-toolchain@4be7066ada62dd38de10e7b70166bc74ed198c30 # stable with: - toolchain: ${{ env.RUST_VERSION }} + toolchain: ${{ steps.rust-toolchain.outputs.channel }} - run: npm ci --ignore-scripts - run: node scripts/npm-audit-signatures.cjs - name: npm audit - production diff --git a/docs/DEPENDENCY_UPDATES.md b/docs/DEPENDENCY_UPDATES.md new file mode 100644 index 00000000..4fe96596 --- /dev/null +++ b/docs/DEPENDENCY_UPDATES.md @@ -0,0 +1,42 @@ +# Dependency updates + +## Rust toolchain + +`rust-toolchain.toml` is the single source of the Rust version. The `channel` +value in its `[toolchain]` table is the only place the version is written. +`scripts/rust-toolchain.mjs` reads that file for the npm scripts, CI reads its +output for the `dtolnay/rust-toolchain` steps, and the Flatpak manifest extracts +the same value with `sed`. + +Do not copy the version into `package.json`, `.github/workflows/ci.yml`, or +`run.rosie.rosi.yml`. + +To bump Rust: + +1. Change `channel` in `rust-toolchain.toml`. Keep `profile` and `components` + in that file as needed. +2. Run `npm run rust:update` to install the pinned toolchain. +3. Run `npm run rust:targets:win`, `npm run rust:targets:mac`, or + `npm run rust:targets:linux` as appropriate. +4. Run `npm run validate:flatpak` and the normal test suite. + +The helper is also usable directly: + +```sh +node scripts/rust-toolchain.mjs # print the pinned version +node scripts/rust-toolchain.mjs --install # install profile and components +node scripts/rust-toolchain.mjs --target aarch64-apple-darwin +``` + +## npm and Cargo + +Run the guarded updaters from a clean worktree: + +```sh +node scripts/npm-safe-update.mjs +node scripts/cargo-safe-update.mjs --manifest-path src-tauri/Cargo.toml +``` + +`npm run u` runs both updaters plus version synchronization. Neither updater +changes the Rust pin; update `rust-toolchain.toml` separately when the toolchain +itself should move. diff --git a/package.json b/package.json index d084937e..d0e08003 100644 --- a/package.json +++ b/package.json @@ -119,12 +119,12 @@ "flatpak:bundle": "node scripts/prepare-flatpak-source.js && flatpak-builder --repo=flatpak-repo --force-clean flatpak-build run.rosie.rosi.yml && flatpak build-bundle flatpak-repo dist/ROSI-Linux-x64.flatpak run.rosie.rosi", "flatpak:clean": "node -e \"for (const d of ['flatpak-build','flatpak-repo']) require('fs').rmSync(d,{recursive:true,force:true})\"", "flatpak:run": "flatpak run run.rosie.rosi", - "rust:update": "rustup toolchain install 1.99.1 --profile minimal --component cargo,clippy,rustfmt", - "rust:targets:win": "rustup target add --toolchain 1.99.1 x86_64-pc-windows-msvc aarch64-pc-windows-msvc", - "rust:targets:mac": "rustup target add --toolchain 1.99.1 x86_64-apple-darwin aarch64-apple-darwin", - "rust:targets:linux": "rustup target add --toolchain 1.99.1 x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu", - "rust:target:linux:x64": "rustup target add --toolchain 1.99.1 x86_64-unknown-linux-gnu", - "rust:target:linux:arm64": "rustup target add --toolchain 1.99.1 aarch64-unknown-linux-gnu", + "rust:update": "node scripts/rust-toolchain.mjs --install", + "rust:targets:win": "node scripts/rust-toolchain.mjs --target x86_64-pc-windows-msvc aarch64-pc-windows-msvc", + "rust:targets:mac": "node scripts/rust-toolchain.mjs --target x86_64-apple-darwin aarch64-apple-darwin", + "rust:targets:linux": "node scripts/rust-toolchain.mjs --target x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu", + "rust:target:linux:x64": "node scripts/rust-toolchain.mjs --target x86_64-unknown-linux-gnu", + "rust:target:linux:arm64": "node scripts/rust-toolchain.mjs --target aarch64-unknown-linux-gnu", "workspace:bootstrap": "npm run rust:update && npm ci --ignore-scripts && npm run sync-version && npm run ytdlp:fetch && npm run ytdlp:check && npm run ffmpeg:ensure && npm run prepare:sidecars", "workspace:prepare": "npm run workspace:bootstrap && npm run test:all -- --require-clean-proof", "release:prepare": "npm run workspace:bootstrap && npm run test:all -- --require-clean-proof --skip-e2e && npm run dist:clean-release-artifacts", diff --git a/run.rosie.rosi.yml b/run.rosie.rosi.yml index cf12a3af..a5624903 100644 --- a/run.rosie.rosi.yml +++ b/run.rosie.rosi.yml @@ -46,9 +46,13 @@ modules: HUSKY: '0' build-commands: # The Flathub rust-stable SDK extension lags the pinned toolchain, so - # install rustup and the exact pinned compiler inside the sandbox. - - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.99.1 --profile minimal - - test "$(rustc --version | cut -d' ' -f2)" = 1.99.1 + # install rustup and the exact compiler pinned in rust-toolchain.toml. + - | + set -eu + PINNED="$(sed -n 's/^[[:space:]]*channel[[:space:]]*=[[:space:]]*"\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)"[[:space:]]*$/\1/p' rust-toolchain.toml)" + test -n "$PINNED" + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain "$PINNED" --profile minimal + test "$(rustc --version | cut -d' ' -f2)" = "$PINNED" # The node24 SDK ships npm 11, older than the npm 12 that engines requires. # npm@12 plus --before 3 days ago takes the newest 12.x that is old enough. - npm install --global npm@12 --ignore-scripts --engine-strict=false --before="$(date -u -d '3 days ago' +%Y-%m-%dT%H:%M:%SZ)" --prefix /run/build/rosi/npm-global diff --git a/scripts/cargo-safe-update.test.mjs b/scripts/cargo-safe-update.test.mjs index c7e710ad..4ac07335 100644 --- a/scripts/cargo-safe-update.test.mjs +++ b/scripts/cargo-safe-update.test.mjs @@ -1585,15 +1585,18 @@ test("45. update environment versions fail closed at exact boundaries", () => { }); // Failure modes covered: a floating `stable` toolchain passes without the -// repository pin; a prefix match accepts 1.99.10 for 1.99.1; rustup's -// host-qualified exact version is rejected; or a malformed pin passes. +// repository pin; a prefix match accepts a later patch release for the exact +// pin; rustup's host-qualified exact version is rejected; or a malformed pin +// passes. test("45a. npm updater requires exact repository-pinned Rust toolchain", () => { const root = process.cwd(); const pinned = readPinnedRustToolchain(root); - assert.equal(pinned, "1.99.1"); - assert.equal(hasRustToolchain("1.99.1\n", pinned), true); + const [major, minor, patch] = pinned.split(".").map(Number); + const nextPatch = `${major}.${minor}.${patch + 1}`; + assert.match(pinned, /^\d+\.\d+\.\d+$/u); + assert.equal(hasRustToolchain(`${pinned}\n`, pinned), true); assert.equal( - hasRustToolchain("1.99.1-aarch64-apple-darwin (default)\n", pinned), + hasRustToolchain(`${pinned}-aarch64-apple-darwin (default)\n`, pinned), true, ); assert.equal(hasRustToolchain("stable\n", pinned), false); @@ -1602,7 +1605,7 @@ test("45a. npm updater requires exact repository-pinned Rust toolchain", () => { false, ); assert.equal( - hasRustToolchain("1.99.10-aarch64-apple-darwin\n", pinned), + hasRustToolchain(`${nextPatch}-aarch64-apple-darwin\n`, pinned), false, ); diff --git a/scripts/npm-safe-update.mjs b/scripts/npm-safe-update.mjs index f51fd4ee..8d0abae7 100644 --- a/scripts/npm-safe-update.mjs +++ b/scripts/npm-safe-update.mjs @@ -19,38 +19,18 @@ import process from "node:process"; import { fileURLToPath, pathToFileURL } from "node:url"; import npmCli from "./npm-cli.cjs"; +import { readPinnedRustToolchain } from "./rust-toolchain.mjs"; const { npmInvocation } = npmCli; const npmDevAuditScript = fileURLToPath( new URL("./npm-dev-audit.cjs", import.meta.url), ); +export { readPinnedRustToolchain }; + export const MINIMUM_NPM_VERSION = "12.2.1"; export const SUPPORTED_NODE_VERSIONS = "^24.22.1 || >=26.13.0"; -export function readPinnedRustToolchain(root) { - const filePath = path.join(root, "rust-toolchain.toml"); - let contents; - try { - contents = readFileSync(filePath, "utf8"); - } catch (error) { - if (error?.code === "ENOENT") { - throw new Error(`Rust toolchain pin is missing: ${filePath}`, { - cause: error, - }); - } - throw error; - } - - const channel = contents.match(/^\s*channel\s*=\s*"([^"]+)"\s*$/mu)?.[1]; - if (!channel || !/^\d+\.\d+\.\d+$/u.test(channel)) { - throw new Error( - `rust-toolchain.toml must pin an exact Rust version; found ${channel || "no channel"}`, - ); - } - return channel; -} - export function parseVersion(value) { const match = String(value) .trim() diff --git a/scripts/rust-toolchain.mjs b/scripts/rust-toolchain.mjs new file mode 100644 index 00000000..ada807c3 --- /dev/null +++ b/scripts/rust-toolchain.mjs @@ -0,0 +1,254 @@ +#!/usr/bin/env node + +import { spawnSync } from "node:child_process"; +import console from "node:console"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import process from "node:process"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const TOOLCHAIN_FILE = "rust-toolchain.toml"; +const EXACT_RUST_VERSION = /^\d+\.\d+\.\d+$/u; +const COMPONENT_NAME = /^[A-Za-z0-9_-]+$/u; +const TARGET_TRIPLE = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/u; +const USAGE = `Usage: node scripts/rust-toolchain.mjs [--print | --install | --target ] + +Without arguments, prints the exact Rust version pinned in rust-toolchain.toml. + --print Print the pinned version. + --install Install the pinned toolchain with its profile and components. + --target Add one or more targets to the pinned toolchain.`; + +function toolchainError(filePath, message, cause) { + return new Error( + `${TOOLCHAIN_FILE} ${message}: ${filePath}`, + cause === undefined ? undefined : { cause }, + ); +} + +function parseQuotedValue(rawValue, filePath, key) { + const value = rawValue.match(/^"([^"]*)"\s*(?:#.*)?$/u)?.[1]; + if (value === undefined) { + throw toolchainError( + filePath, + `has a malformed ${key}; expected a quoted string`, + ); + } + return value; +} + +function parseComponents(rawValue, lines, startIndex, filePath) { + const parts = [rawValue.replace(/\s+#.*$/u, "")]; + let index = startIndex; + while (!parts.at(-1).includes("]")) { + index += 1; + if (index >= lines.length) { + throw toolchainError(filePath, "has an unterminated components array"); + } + parts.push(lines[index].trim().replace(/\s+#.*$/u, "")); + } + + const text = parts.join(" "); + const body = text.slice(0, text.indexOf("]")); + const components = [...body.matchAll(/"([^"]+)"|'([^']+)'/gu)].map( + (match) => match[1] ?? match[2], + ); + if (components.length === 0) { + throw toolchainError(filePath, "has an empty components array"); + } + for (const component of components) { + if (!COMPONENT_NAME.test(component)) { + throw toolchainError( + filePath, + `has a malformed component name: ${component}`, + ); + } + } + return { components, index }; +} + +export function readRustToolchain(root) { + const filePath = path.join(root, TOOLCHAIN_FILE); + let contents; + try { + contents = readFileSync(filePath, "utf8"); + } catch (error) { + if (error?.code === "ENOENT") { + throw toolchainError(filePath, "is missing", error); + } + throw error; + } + + const lines = contents.replace(/^\uFEFF/u, "").split(/\r?\n/u); + let section = ""; + let channel; + let profile; + let components = []; + let componentsSeen = false; + + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index].trim(); + if (!line || line.startsWith("#")) continue; + + const sectionMatch = line.match(/^\[([^\]]+)\]\s*(?:#.*)?$/u); + if (sectionMatch) { + section = sectionMatch[1].trim(); + continue; + } + if (section !== "toolchain") continue; + + const keyValue = line.match(/^([A-Za-z0-9_-]+)\s*=\s*(.*)$/u); + if (!keyValue) { + throw toolchainError(filePath, `has a malformed line: ${line}`); + } + const [, key, rawValue] = keyValue; + + if (key === "channel") { + if (channel !== undefined) { + throw toolchainError(filePath, "defines channel more than once"); + } + channel = parseQuotedValue(rawValue, filePath, "channel"); + continue; + } + if (key === "profile") { + if (profile !== undefined) { + throw toolchainError(filePath, "defines profile more than once"); + } + profile = parseQuotedValue(rawValue, filePath, "profile"); + continue; + } + if (key === "components") { + if (componentsSeen) { + throw toolchainError(filePath, "defines components more than once"); + } + const parsed = parseComponents(rawValue, lines, index, filePath); + components = parsed.components; + componentsSeen = true; + index = parsed.index; + } + } + + if (!channel) { + throw toolchainError( + filePath, + "must pin an exact Rust version; found no channel", + ); + } + if (!EXACT_RUST_VERSION.test(channel)) { + throw toolchainError( + filePath, + `must pin an exact Rust version; found ${channel}`, + ); + } + + return { channel, profile, components }; +} + +export function readPinnedRustToolchain(root) { + return readRustToolchain(root).channel; +} + +function parseArguments(argv) { + const options = { action: "print", targets: [] }; + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (argument === "--help" || argument === "-h") { + return { action: "help" }; + } + if (argument === "--print") { + if (options.action !== "print") { + throw new Error("Choose only one of --print, --install, or --target"); + } + continue; + } + if (argument === "--install") { + if (options.action !== "print") { + throw new Error("Choose only one of --print, --install, or --target"); + } + options.action = "install"; + continue; + } + if (argument === "--target") { + if (options.action !== "print") { + throw new Error("Choose only one of --print, --install, or --target"); + } + const targets = argv.slice(index + 1); + if (targets.length === 0) { + throw new Error("--target requires at least one target triple"); + } + for (const target of targets) { + if (!TARGET_TRIPLE.test(target)) { + throw new Error(`Invalid target triple: ${target}`); + } + } + options.action = "target"; + options.targets = targets; + break; + } + throw new Error(`Unknown argument: ${argument}`); + } + return options; +} + +function runRustup(args) { + const result = spawnSync("rustup", args, { + stdio: "inherit", + windowsHide: true, + shell: false, + }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error( + `rustup ${args.join(" ")} failed with exit code ${result.status}`, + ); + } +} + +function main() { + const options = parseArguments(process.argv.slice(2)); + if (options.action === "help") { + console.log(USAGE); + return; + } + + const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + const toolchain = readRustToolchain(root); + + if (options.action === "print") { + console.log(toolchain.channel); + return; + } + if (options.action === "install") { + const args = [ + "toolchain", + "install", + toolchain.channel, + "--profile", + toolchain.profile || "minimal", + ]; + if (toolchain.components.length > 0) { + args.push("--component", toolchain.components.join(",")); + } + runRustup(args); + return; + } + + runRustup([ + "target", + "add", + "--toolchain", + toolchain.channel, + ...options.targets, + ]); +} + +const isMainModule = + process.argv[1] && + pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url; +if (isMainModule) { + try { + main(); + } catch (error) { + console.error(`rust-toolchain: ${error.message}`); + process.exitCode = 1; + } +} diff --git a/scripts/validate-flatpak-dry-run.js b/scripts/validate-flatpak-dry-run.js index 586138bd..f78a2342 100644 --- a/scripts/validate-flatpak-dry-run.js +++ b/scripts/validate-flatpak-dry-run.js @@ -8,6 +8,7 @@ import path from "path"; import { fileURLToPath } from "url"; import { spawnSync } from "child_process"; import { hasExactReleaseVersion } from "./update-metainfo.js"; +import { readPinnedRustToolchain } from "./rust-toolchain.mjs"; const root = path.join(path.dirname(fileURLToPath(import.meta.url)), ".."); const required = [ @@ -19,9 +20,6 @@ const required = [ "scripts/prepare-sidecars.js", ]; const expectedRuntime = "runtime-version: '50'"; -const rustToolchain = fs - .readFileSync(path.join(root, "rust-toolchain.toml"), "utf8") - .match(/^channel = "(\d+\.\d+\.\d+)"$/m)?.[1]; let failed = false; function fail(message) { @@ -29,6 +27,13 @@ function fail(message) { failed = true; } +let rustToolchain; +try { + rustToolchain = readPinnedRustToolchain(root); +} catch (error) { + fail(error.message); +} + for (const rel of required) { if (!fs.existsSync(path.join(root, rel))) fail(`missing ${rel}`); } @@ -72,11 +77,22 @@ if (fs.existsSync(manifest)) { } const cargoBin = "/run/build/rosi/cargo/bin"; const prependPath = yaml.match(/^\s*prepend-path: (.+)$/m)?.[1]?.split(":"); + const manifestLines = yaml.split(/\r?\n/u); + const extractsPin = manifestLines.some( + (line) => + line.includes("PINNED=") && + line.includes("sed") && + line.includes("channel") && + line.includes("rust-toolchain.toml"), + ); + const assertsPin = manifestLines.some( + (line) => line.includes("rustc --version") && line.includes('= "$PINNED"'), + ); if ( !rustToolchain || - !yaml.includes( - `test "$(rustc --version | cut -d' ' -f2)" = ${rustToolchain}`, - ) || + !extractsPin || + !assertsPin || + yaml.includes(rustToolchain) || !yaml.includes( "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs", ) || @@ -85,7 +101,7 @@ if (fs.existsSync(manifest)) { yaml.includes("RUSTUP_TOOLCHAIN:") ) { fail( - "Flatpak must install the exact pinned compiler with rustup inside the sandbox and fail closed on the exact pin", + "Flatpak must derive the compiler pin from rust-toolchain.toml with sed, install it via rustup, and fail closed on the exact pin", ); } if (!yaml.includes("Unsupported FLATPAK_ARCH")) { From 0dd30e38548948608a704b545e6c17f2d8b90e8f Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:18:10 -0800 Subject: [PATCH 07/58] Toolchain: Derive Rust pin from rust-toolchain.toml --- build-setup.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build-setup.md b/build-setup.md index e09da029..dc5e5de8 100644 --- a/build-setup.md +++ b/build-setup.md @@ -40,7 +40,7 @@ ## Rust toolchain policy -ROSI builds with Rust `1.99.1`, pinned in `rust-toolchain.toml` and used by CI, +ROSI builds with the Rust version pinned in `rust-toolchain.toml`, used by CI, Flatpak, and release builds. Install that exact toolchain before building: ```sh From 010d9faf5fd0ff1284b5a26be20f8c05c14fc690 Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:25:34 -0800 Subject: [PATCH 08/58] Toolchain: Reject --print combined with a rustup action. --- scripts/cargo-safe-update.test.mjs | 30 ++++++++++++++++++++++++++++++ scripts/rust-toolchain.mjs | 3 +++ 2 files changed, 33 insertions(+) diff --git a/scripts/cargo-safe-update.test.mjs b/scripts/cargo-safe-update.test.mjs index 4ac07335..c4abc621 100644 --- a/scripts/cargo-safe-update.test.mjs +++ b/scripts/cargo-safe-update.test.mjs @@ -1929,3 +1929,33 @@ test("51. npm rollback refuses to overwrite a concurrent package-lock edit", () rmSync(tempRoot, { recursive: true, force: true }); } }); + +test("rust toolchain CLI --print matches the bare pin and never combines with an action", () => { + const script = fileURLToPath( + new URL("./rust-toolchain.mjs", import.meta.url), + ); + const run = (args) => + spawnSync(process.execPath, [script, ...args], { encoding: "utf8" }); + const bare = run([]); + assert.equal(bare.status, 0, bare.stderr); + assert.match(bare.stdout, /^\d+\.\d+\.\d+\n$/u); + const printed = run(["--print"]); + assert.equal(printed.status, 0, printed.stderr); + assert.equal(printed.stdout, bare.stdout); + for (const args of [ + ["--print", "--install"], + ["--install", "--print"], + ["--print", "--target", "x86_64-pc-windows-msvc"], + ["--target", "x86_64-pc-windows-msvc", "--print"], + ]) { + const result = run(args); + const label = args.join(" "); + assert.notEqual(result.status, 0, `${label} must fail`); + assert.match( + result.stderr, + /--print cannot be combined/u, + `${label} must name --print`, + ); + assert.equal(result.stdout, "", `${label} must not print or act`); + } +}); diff --git a/scripts/rust-toolchain.mjs b/scripts/rust-toolchain.mjs index ada807c3..13538408 100644 --- a/scripts/rust-toolchain.mjs +++ b/scripts/rust-toolchain.mjs @@ -148,6 +148,9 @@ export function readPinnedRustToolchain(root) { } function parseArguments(argv) { + if (argv.includes("--print") && argv.length > 1) { + throw new Error("--print cannot be combined with an action"); + } const options = { action: "print", targets: [] }; for (let index = 0; index < argv.length; index += 1) { const argument = argv[index]; From 6f244bd71fcdbf72747ad3e84a0d437547bb7d85 Mon Sep 17 00:00:00 2001 From: BurntToasters <61037367+BurntToasters@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:24:39 -0800 Subject: [PATCH 09/58] changes --- CHANGELOG.md | 11 +- .../Windows/PowerShell/ModuleAnalysisCache | Bin 0 -> 10696 bytes README.md | 8 +- build-setup.md | 22 +- docs/IMPLEMENTATION-5.1.md | 96 ++ docs/ROADMAP-5.1.md | 67 +- .../Windows/PowerShell/ModuleAnalysisCache | Bin 0 -> 10696 bytes e2e/README.md | 53 + e2e/macos-native-packages.failure-modes.md | 36 + e2e/rosi-51-foundation.failure-modes.md | 43 + .../format-fixtures.cjs | 14 + e2e/round3-renderer-repairs/preview.cjs | 8 +- e2e/round3-renderer-repairs/renderer.cjs | 20 +- e2e/round3-renderer-repairs/updater.cjs | 8 +- e2e/specs/main.spec.js | 50 +- e2e/suites.json | 784 +++++++++ e2e/v5-fixes/async-proxy/async-proxy.spec.js | 155 ++ e2e/v5-fixes/async-proxy/failure-modes.md | 76 + e2e/v5-fixes/async-proxy/run.mjs | 141 ++ .../download-options/download-options.spec.js | 267 +++ .../download-options/failure-modes.md | 35 + .../queue-coordinator/failure-modes.md | 125 ++ .../queue-coordinator.spec.js | 342 ++++ e2e/v5-fixes/typed-formats/failure-modes.md | 50 + .../typed-formats/typed-formats.spec.js | 239 +++ e2e/v5-fixes/ui-polish/failure-modes.md | 96 ++ e2e/v5-fixes/ui-polish/ui-polish.spec.js | 798 +++++++++ package.json | 16 +- scripts/benchmark-51.mjs | 807 ++++++++++ scripts/e2e-macos-native-packages.mjs | 1077 +++++++++++++ scripts/gpg-sign.js | 154 +- scripts/test-e2e.js | 737 +++++---- scripts/verify-release-draft.js | 4 + scripts/zip-macos.js | 391 +++-- src-tauri/Cargo.lock | 1 + src-tauri/Cargo.toml | 1 + src-tauri/build.rs | 2 + src-tauri/capabilities/default.json | 1 + src-tauri/gen/schemas/acl-manifests.json | 2 +- src-tauri/gen/schemas/capabilities.json | 2 +- src-tauri/gen/schemas/desktop-schema.json | 12 + src-tauri/gen/schemas/windows-schema.json | 12 + .../resolve_download_options.toml | 11 + src-tauri/src/coordinator.rs | 745 +++++++++ src-tauri/src/download_options.rs | 238 +++ src-tauri/src/downloader.rs | 382 +---- src-tauri/src/ipc.rs | 101 +- src-tauri/src/main.rs | 13 + src-tauri/src/media_info.rs | 154 +- src-tauri/src/network_security.rs | 994 +----------- src-tauri/src/network_security_async.rs | 1427 +++++++++++++++++ src-tauri/src/queue.rs | 835 ++++------ src-tauri/src/types.rs | 52 + src-tauri/src/validation.rs | 10 +- src/commands.ts | 10 +- src/css/02-sidebar.css | 28 + src/css/03-main.css | 14 + src/css/08-wizard.css | 11 + src/engine/bind/backend-events.ts | 46 +- src/engine/bind/settings-controls.ts | 107 +- src/engine/bind/settings-sections.ts | 55 +- src/engine/deno.ts | 15 +- src/engine/formats.ts | 126 +- src/engine/manual-download.ts | 23 - src/engine/messages.ts | 238 +++ src/engine/overlays.ts | 6 + src/engine/settings-store.ts | 60 +- src/engine/settings-view.ts | 26 +- src/engine/wizard.ts | 96 +- src/generated/ipc-types.ts | 10 + src/index.html | 40 +- src/modules/activity.ts | 45 +- src/modules/downloads.ts | 60 +- src/modules/queue.ts | 13 +- src/renderer-globals.d.ts | 20 +- src/tauri-bridge.ts | 1 + src/tests/rendererModules.test.ts | 34 +- src/tests/rosiEngine.dom.test.ts | 26 +- 78 files changed, 10306 insertions(+), 2529 deletions(-) create mode 100644 Microsoft/Windows/PowerShell/ModuleAnalysisCache create mode 100644 docs/IMPLEMENTATION-5.1.md create mode 100644 e2e/Microsoft/Windows/PowerShell/ModuleAnalysisCache create mode 100644 e2e/macos-native-packages.failure-modes.md create mode 100644 e2e/rosi-51-foundation.failure-modes.md create mode 100644 e2e/round3-renderer-repairs/format-fixtures.cjs create mode 100644 e2e/suites.json create mode 100644 e2e/v5-fixes/async-proxy/async-proxy.spec.js create mode 100644 e2e/v5-fixes/async-proxy/failure-modes.md create mode 100644 e2e/v5-fixes/async-proxy/run.mjs create mode 100644 e2e/v5-fixes/download-options/download-options.spec.js create mode 100644 e2e/v5-fixes/download-options/failure-modes.md create mode 100644 e2e/v5-fixes/queue-coordinator/failure-modes.md create mode 100644 e2e/v5-fixes/queue-coordinator/queue-coordinator.spec.js create mode 100644 e2e/v5-fixes/typed-formats/failure-modes.md create mode 100644 e2e/v5-fixes/typed-formats/typed-formats.spec.js create mode 100644 e2e/v5-fixes/ui-polish/failure-modes.md create mode 100644 e2e/v5-fixes/ui-polish/ui-polish.spec.js create mode 100644 scripts/benchmark-51.mjs create mode 100644 scripts/e2e-macos-native-packages.mjs create mode 100644 src-tauri/permissions/autogenerated/resolve_download_options.toml create mode 100644 src-tauri/src/coordinator.rs create mode 100644 src-tauri/src/download_options.rs create mode 100644 src-tauri/src/network_security_async.rs create mode 100644 src/engine/messages.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f0ba4e6d..4269e101 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,13 @@ # ⬇️ Downloads -| Windows | macOS | Linux | -| :-- | :-- | :-- | -| **EXE: [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Windows-x64.exe) / [arm64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Windows-arm64.exe)** | **[Universal DMG](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-universal.dmg)** | **AppImage:** [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Linux-x64.AppImage) | -|
| **[Universal ZIP](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-universal.zip)** | **Flatpak:** [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Linux-x64.flatpak) | +| Windows | macOS | Linux | +| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- | +| **EXE: [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Windows-x64.exe) / [arm64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Windows-arm64.exe)** | **DMG: [arm64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-arm64.dmg) / [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-x64.dmg) / [universal](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-universal.dmg)** | **AppImage:** [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Linux-x64.AppImage) | +|
| **ZIP: [arm64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-arm64.zip) / [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-x64.zip) / [universal](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-MacOS-universal.zip)** | **Flatpak:** [x64](https://github.com/BurntToasters/ROSI/releases/download/v5.1.0-beta.1/ROSI-Linux-x64.flatpak) | > macOS downloads require macOS 15 or later. +> Native arm64 builds run on Apple silicon; native x64 builds run on Intel and +> under Rosetta on Apple silicon. Universal builds run on both architectures. > [!IMPORTANT] > The `.sig` files in this repo are NOT normal GPG signatures. They are for Tauri V2's updater to verify the integrity of updates before downloading and installing. @@ -23,6 +25,7 @@ ROSI! A cross platform yt-dlp GUI built on Tauri V2! - **Updater:** Architecture verification ensures downloaded macOS updates match the host machine before installation. - **Updater:** Rosetta-translated processes on Apple Silicon automatically request the native arm64 target to migrate away from emulation. - **Packaging:** Per-architecture updater archives are verified for codesigning and notarization stapling prior to packaging. +- **Packaging:** Native arm64 and x64 DMG/ZIP downloads are available alongside the universal macOS packages. ## Changes in `v5.0.2:` diff --git a/Microsoft/Windows/PowerShell/ModuleAnalysisCache b/Microsoft/Windows/PowerShell/ModuleAnalysisCache new file mode 100644 index 0000000000000000000000000000000000000000..6481bfe428e4f994f58a700fc7d81f9af1dc19fd GIT binary patch literal 10696 zcmeI2NpB=c6~{fSJuqy;zDa|`1*Edt-NS_g!Yf;3n?or>`I)Kk&}z< znhPAba0DR`XHI+xZX7vsLyX{n#1|NZgaq&RA|o@Z>>jD5k+^iXQYuHhc=4A1TOu;Y z(dcmdKJURPs# zZOUk7vg~YRrwudx&?8fyZLHsy{~ODr>qRx)_`0zDv^*zynpbt4Wdq0I12Xm@dD47t zUub`yr|$PBF`L%j^> z-4ssOW!v;LpA{Oh?4Y%Snf6nG3cW26_sCqNRc*?_I65+gt%BA%pK zTC2Jt9(s+1er@d!Fa7QVufB8dMt(j6*hgtn+RC2S>k9j0yQtQOHa|}w_@za3YziH*x? zWXt-noSG63eM+9!%|a&xp2ADHd{l-dQpQ&Ikt*p!tmPs_OQ zbgPJmFRc7d-MB8aqWbp!a_-th2N=$TYZRR!U zEZ7;4nUBcxrnU3^n!jF@XY)F~G~#aK6?Nz?ML2Vnnrpv>@;fqlJXcBBb!anNj??7Q znd3_`q*R+pV)A-3sne^tPHirxgZYQ$Ii8uh?(~J_^}|fqu)^k$g7=YaDswtBCKC*roTvL7#7&;e+~zRfvsJC0;1AWy3%{9N$BXJPKep-t*emh2$xLmw;^eX^LiRej zlP7kX<`)Qrx`A%+CA?I|z4T(1$s-woaloSETTNZt{JI-m(Oa?tw9) zIxg#`7?UVl|9(}51N8Jz=^?lbbTm zBq`S7KNSSZM`b(_%8|WN2!Bn6)X|&MsY(`S2dStR3i_|#zx$7$eCwTiL!o_!L^hT* zZpyQV>#s_xa(`%*rWz3F+oqE0I?-D88Tp$uP3qq+(<`%Io4Kzh6yn|VrWOD&#Iv9K z$^HDwUQz>-ONQ{=e(o}Nlt^Y_5I=bW5>ynQ8`&)=z?uZkMckb@nX!Z%A(^Miv_9j9 zEpu*58e0oJivpzAVf{UAI@BALFXX` zaYidJVh*K|GHM2*9cMVw!vZ9;fPcUG^&kKIH)-vDF2A1vBr7FM`@Z!CwX)(2EjN{y7L==;n1jHVSqrCP*uBr_@6c~K$F*1)Um7)v${ zck@aG0-%A$Q93tdY=mRmcX^5_*8mY+Q_> zrBeaPWE-g|Rc{tKF)bSv7OjMx#GZxddPPR_ULj{_jT;=7abCsR#du;gI1bzZjEA;Z zbZ86wa+juoVbN3%Wdb!^w}u zmW=lyDAXQA5TD2ieiZ;7MS#nL5hhrxmBnKgw4cVrde7DwM`Z}Lg#(?U^N}-ci&gFO zIx#VQ7{Z9NYC4G78>@vN&@5NKO_sw(-H}&}p=7M%!9$@AB8bf-$N1pD?5AZa*8r>B zE61H0C8wG9$_>J^nae#wkNXa8y|F;}NoDSGftNA#FZxw3i~B^gn%UI8voxD}{ji@) zcSk1Sd^bsRZ|rd+mm(ntPLqy!)ptIQ0~k_?+o*N^j7%ae-*6U75NGT`-gr$)L}ysI zxGL3UUa*PKOMqqJh^+6mz@6PdXcD&Z@ZdMDa~g!M!w7(7RVz|auP^I)JSD%$D?|ZD zu2nZ7`nH)g7a{)XKECs_k#-+%vG{%JK2B=A!nnKjXeYJrn9HU?e)hd&XPmYWM0F|0 z3`S8yia?@eZZ0=m4B{!y`-47~!07a#h?I>!WV+qo$aV;n_N{G_jB9O2sdEK93A7>38TT;B29!|G&z*kqhU7z}dL zINB;r>>3!Re61Nrw9ir*lS|L0l|Zu6&0JxvQR}V=j~9iJEo0B3O_1R*L3=*CAt@o$ z{#^CxxuFb_2XZphTJBUj3z!oTUAkic=rYjz2ky=)r*SDas-1J)pqynUw(6LXUpBKe z)`kLCo#c~DP7iW&bFR|F;lQ$6+WFwM${F9gI@FP|!=@fQD%0r`xqm@G%_YJ59&qj& zMf(xu98ITUao|XU@7sfsnNJ)(P%M&5k0eARzQk+_!Kj(Iv#DYM|Fr#%@*h@L2t;ad z;p%}F8n&|qX!PBJnH-t78fp6c`j+jn9qiQ(3<0?SrR+gU&G$9JZ`dIlcOreaE7oqI zu>^Ij;Q{E>VC2}C!0{ft8pM&_HzO}*Yf&_8q;J*J1m|GCPj_(-f^j?MC(7Hd_mPP&CC z-8-rEJY=mU_RI}hA`j6MW=F=_QFCZ$BwKJ|9Ea#=s98@cK#@?uEb+N4rs+W+Opke4%WW+C`&)*T*s&Qjdvc ze)Av>H%$EY+Tid#xn=h8>0IflaAb=qnu$yAWy6;xde1MzQ*`8ps#Cgz0!7U;C2E%Lh1cW1lkF`N+i6&XZUR6^;${CoUI0 z-dWqq9YhP_97!wSk_IJgxEoQzASVU%&O~~L2kFZ$NPw6OO!(}#3VLK|HCR@e3CD`l zFP%eM@Ry^y4FD`oG6><1aS(4T)ug=zp&|SJpT4K>F@Gr2&v4l_mM%czr@z?g-({}O zXzPWT=zvu1+CCj~`U(7bYo3Le{ni8-!N2irCw*+{>%?FT^#dNBOkafsWE@{sIEwGO zOAP9>uMtkqaMl;zmR~r+<=sRr?~8VA<6aLFx&+(my({==TZ{ho zmOe>p2nSG3Q*Lj)YDOHObeA|XwYK)3SAO&VePKD>K#T|Sxb!E%BC0%pVJQZA{=)M4 z3rh+nnP&6(3(LBa2IXllEd6IjuZyjor98`*Eb)}rpJxyF#^{WXM%;jwW8Mh@LOIjh zToSCIVf7ULtfS?!Tj$=9Q8y{qTF1LN$?$v95@qgC>Mt|a}+tGe{ zc{z3O7Z2-qe=6^B9}D@jn58?{iEe$z61kVGVww5Iw}m6X^i6=PFqni6V&x+x2ycHu z1)&yg$CkB}y={A)XI2`|w!Sk?*=zf~o|uB6>)S&Pg!Cn0izKEGzf|&_M=N#s*%L(+ zPquGTovF2m(sj@qFSR3V1~U3)Wo0W=QR!B`;REVM#bh8xc|nA-~RKr&g{#(@8=R*dh+5fQaiajHt|!B<-Ir4$gMZHju}S+|JmFv zTlb#Ba7$mwh3k9^)%hsEfwQ>3YS-4f-GD~Rj@ Ov)7^vp}@wndhLG*;s=5N literal 0 HcmV?d00001 diff --git a/README.md b/README.md index eccd4186..a8263cb5 100644 --- a/README.md +++ b/README.md @@ -40,8 +40,9 @@ webview, so installers and memory use are much smaller. ## System requirements -- macOS 15 or later (universal build for Intel and Apple silicon). The bundled - FFmpeg is built for macOS 15. +- macOS 15 or later. Choose the arm64 package for Apple silicon, the x64 + package for Intel or Rosetta, or the universal package for either processor. + The bundled FFmpeg is built for macOS 15. - Windows 10 version 2004 (build 19041) or later, on x64 or ARM64, with the Microsoft Edge WebView2 runtime (installed automatically when missing). - Linux x64 with WebKitGTK 4.1 (Ubuntu 24.04+, Debian 13+, Fedora 43+, or a @@ -83,7 +84,8 @@ See the Microsoft Store section of [build-setup.md](build-setup.md). convert). 5. Packaged builds: - Windows: `npm run build:win` - - macOS: `npm run build:mac:universal`, then `npm run build:mac:zip` + - macOS: `npm run build:mac:universal`, then `npm run build:mac:zip` for + universal packages; `npm run build:mac:native` for arm64 and x64 packages - Linux x64: `npm run build:linux` (or `npm run build:linux:x64`) - Linux ARM64 (native ARM64 hardware only): `npm run build:linux:arm64` - Flatpak: `npm run flatpak:bundle` diff --git a/build-setup.md b/build-setup.md index dc5e5de8..a4f2c3ed 100644 --- a/build-setup.md +++ b/build-setup.md @@ -19,13 +19,25 @@ ## macOS - macOS 15 or later. `minimumSystemVersion` in `tauri.conf.json` is - 15.0 because the bundled FFmpeg is built for macOS 15; `build:mac:zip` rejects - any bundled Mach-O whose minimum OS is above that floor. + 15.0 because the bundled FFmpeg is built for macOS 15; `build:mac:zip` checks + the minimum OS of each required architecture slice against that floor. - Xcode Command Line Tools (`lipo`, `codesign`, `notarytool`) - zstd CLI (`brew install zstd`) for the updater archives; checked by `npm run prerelease:prepare` - Node.js `^24.22.1 || >=26.13.0` - Rust (rustup) +macOS builds can produce the universal package or native arm64 and x64 +packages. `npm run build:mac:universal` builds the universal DMG/app, then +`npm run build:mac:zip` verifies the signed app and creates its ZIP. +`npm run build:mac:native` builds each native app once with its DMG and +updater archive, then creates architecture-matched ZIPs. Individual prepared +targets are `build:mac:arm64:prepared` and `build:mac:x64:prepared`; run the +matching `build:mac:zip:arm64` or `build:mac:zip:x64` after those builds. +Native app and FFmpeg/ffprobe binaries must be thin for their target. The +upstream universal2 yt-dlp binary may remain universal when it contains the +requested slice. Every public installer is named +`ROSI-MacOS-{arm64,x64,universal}.{dmg,zip}`. + ## Linux - Build the public AppImage on Ubuntu 24.04, the oldest supported glibc @@ -222,9 +234,9 @@ The `b`, `r`, and `release:*` scripts intentionally reset and clean their Git worktrees. Run them only on disposable, isolated build VMs. `b` and `r` run directly without confirmation. `release:finalize` also runs without a guard, so run it only from a checkout with nothing uncommitted. Before publishing, -verify that the draft contains the Windows x64/ARM64 NSIS installers, the -universal macOS DMG/ZIP, Linux x64 AppImage/Flatpak, updater -manifests/signatures, SHA-256 lists, and GPG detached signatures +verify that the draft contains the Windows x64/ARM64 NSIS installers, native +arm64/x64 and universal macOS DMG/ZIP packages, Linux x64 AppImage/Flatpak, +updater manifests/signatures, SHA-256 lists, and GPG detached signatures (`npm run release:verify:draft`). ## Microsoft Store diff --git a/docs/IMPLEMENTATION-5.1.md b/docs/IMPLEMENTATION-5.1.md new file mode 100644 index 00000000..51486dd3 --- /dev/null +++ b/docs/IMPLEMENTATION-5.1.md @@ -0,0 +1,96 @@ +# ROSI 5.1 implementation and evidence ledger + +## Accepted delivery + +The following six milestones are accepted for ROSI 5.1. Acceptance is scope, +not a completion claim. This ledger records evidence produced by the verification +foundation at the current worktree snapshot; other workstreams must update their +own status when they produce implementation and platform evidence. + +| # | Milestone | Evidence status | +| --- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Baseline evidence and E2E organization | The E2E manifest and feature-group selector are implemented. A current inventory capture is retained on Windows x64. It records discovered scenarios separately from execution. The initial full baseline report was overwritten while the shared artifact tree was changing; that report is unavailable and has not been reconstructed. Runtime measurements remain missing. | +| 2 | Native macOS distribution and artifact verification | The native macOS artifact verifier is in progress in a separate workstream. No native macOS package build or size comparison is recorded here. | +| 3 | Typed formats, shared option resolution, structured lifecycle consumption | Structured format data and renderer consumption have changes in the current worktree. Shared option resolution, lifecycle acceptance, integration, and cross-platform proof remain outstanding. | +| 4 | Queue/session coordinator migration | Accepted; no coordinator migration or platform proof is claimed by this foundation. | +| 5 | Async proxy migration | Accepted; no async relay migration or runtime proof is claimed by this foundation. | +| 6 | Full-app polish and integrated release candidate | Accepted; the integrated candidate and full required-platform E2E proof remain outstanding. | + +Worker choice recorded for the accepted plan: **GPT-6 Luna max**. + +Milestone 6 keeps ROSI's visual identity and layout while improving downloads, +queue management, settings, onboarding, and accessibility. It does not add the +major features listed as deferred below. + +## Required support and proof matrix + +ROSI 5.1 must retain the current supported platforms: macOS 15 and newer, Linux +x64, and Windows x64 and arm64. A Windows x64 inventory capture does not prove +the app or release artifacts on any platform. + +| Platform | Evidence from this foundation | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------- | +| macOS 15+ | Verifier changes are in progress; no build, app E2E, signing, notarization, or package comparison was performed for this capture. | +| Linux x64 | No build or app E2E performed. | +| Windows x64 | Benchmark inventory captured on this host; no app E2E or release artifact verification performed. | +| Windows arm64 | No build or app E2E performed. | + +Existing archived reports are recorded as references only. This work does not +claim that historical baseline runs passed or that their results correspond to +the saved clean snapshot. + +## Baseline artifact + +The retained current-only inventory is +`e2e/artifacts/benchmark-51-current-final-win32-x64.json`, with its adjacent +`.sha256` file. It records the source revision and dirty-file hashes, the saved +clean-snapshot identity, host and tool versions, evidence artifact and sidecar +sizes, the static and dynamic suite inventory, and references to existing +reports. Native release packages are `not-measured` when no packages are +present; frontend `dist/` is recorded separately. The benchmark records that no +scenarios were executed by that command. + +The older schema 1 file named `benchmark-51-baseline-win32-x64.json` is a +current-only capture made after the initial report was overwritten. It is not +the retained baseline and is not a valid comparison input for the current +schema. + +The current inventory has 103 static scenarios and 8 dynamic `v5-fixes` areas. +These are discovered counts, not passed scenario counts. The first full +baseline report produced during this work was overwritten while the shared +E2E artifact tree was changing. It is unavailable as a verifiable report; no +historical count or report content is reconstructed. The saved clean snapshot +still identifies `010d9faf5fd0ff1284b5a26be20f8c05c14fc690` and contains 522 +tracked-file hashes with empty staged and unstaged patches. It does not contain +runtime observations. + +Runtime data for startup, idle CPU, peak memory, queue latency, and proxy +throughput is **missing, not measured**. The initial runtime baseline cannot be +reconstructed from the saved source snapshot. + +To provide real measurements later, pass a versioned runtime metrics JSON file +to `scripts/benchmark-51.mjs --runtime-metrics `. The tool records the +input hash, method, host, units, and sample counts, and compares a metric only +when both reports contain compatible measured values. Missing inputs remain +explicit; the tool does not derive runtime values from artifact sizes or old +report references. + +## Performance and artifact acceptance + +There is no numeric performance target. Before and after evidence must show +smaller native macOS package artifacts. Startup, CPU and memory use, queue +latency, proxy throughput, and other agreed runtime measures must show no +regression. The retained current capture has no runtime values and no native +package measurements, so this acceptance is still open. An absent package +inventory is not a zero-byte package or evidence of a saving. + +Each comparison must identify its source revision, platform, architecture, tool +versions, measurement method, and report hash. Do not compare measurements from +different hosts as if they were like-for-like. + +## Deferred beyond 5.1 + +These items remain outside the accepted delivery: an independent yt-dlp update +channel, updater key rotation, macOS entitlement redesign, new Flatpak hosting, +Linux arm64 support, and major product features. Existing Flatpak packaging and +current supported platforms remain in the required release-verification scope. diff --git a/docs/ROADMAP-5.1.md b/docs/ROADMAP-5.1.md index 76dc1843..b319f2cb 100644 --- a/docs/ROADMAP-5.1.md +++ b/docs/ROADMAP-5.1.md @@ -1,20 +1,26 @@ # ROSI 5.1 roadmap -These are deferred, long-term items. None of them blocks 5.0.0 stable. Each -entry gives the problem with file and line evidence, a concrete plan, and +This status ledger separates work already present in the repository, scope +accepted for ROSI 5.1, and work deferred beyond 5.1. “Accepted” is a planning +status, not evidence that implementation or platform verification is complete. +The accepted delivery plan and proof gaps are in +[IMPLEMENTATION-5.1.md](IMPLEMENTATION-5.1.md). The required stable matrix is +macOS 15 and newer, Linux x64, and Windows x64 and arm64. Linux arm64 remains +deferred. Each entry gives the problem with file evidence, a concrete plan, and acceptance criteria. Line numbers were read on 2026-10-19 and will drift; search for the named symbol when they do. -Items already covered by the current stable-readiness fixes are not listed -here. Keep each item's acceptance criteria as the definition of done, and check -them against the E2E evidence the change produces. Where a plan adds a -dependency, the change must be approved on its own; this roadmap does not add -one. +Check acceptance criteria against evidence from the change that produces it. +Where a plan adds a dependency, the change must be approved on its own; this +roadmap does not add one. ## 1. Split the renderer engine into feature modules -**Status (2026-10-20): done in 5.0.0-beta.4.** Feature logic lives in `src/engine/`, and per-feature event binding in `src/engine/bind/`. `src/rosiEngine.ts` (about 570 lines) loads settings, looks up the DOM, and calls the bind functions in their original order. - +**Status (2026-11-06): partial implementation present.** Feature logic lives in +`src/engine/`, and per-feature event binding in `src/engine/bind/`. +`src/rosiEngine.ts` is about 440 lines and still defines `initializeRenderer`; +`window.rosiModules` remains in use. The extraction is useful existing work, but +the acceptance criteria below are not all met. No completion is claimed here. **Problem.** `src/rosiEngine.ts` is 5,943 lines. `initializeRenderer` starts at `src/rosiEngine.ts:2370` and runs to about line 5927. It holds 66 nested @@ -47,8 +53,12 @@ taking explicit inputs. ## 2. Typed command layer and generated IPC types -**Status (2026-10-20): done in 5.0.0-beta.4.** `src/generated/ipc-types.ts` is generated from the Rust types (test-only `ts-rs`), `src/commands.ts` types every command call, and a contract test checks the command names against `build.rs` and the capability. `window.api` stays as the seam for vitest and E2E; removing it would mean rewriting those harnesses, which is not planned. - +**Status (2026-11-06): partial implementation present.** +`src/generated/ipc-types.ts`, `src/commands.ts`, and the command contract check +exist. Runtime callers still use `window.api`, and the ambient renderer globals +remain. The former acceptance criterion that `window.api` disappear is not +met; removing the compatibility seam is deferred until its callers and harness +are migrated together. **Problem.** `src/tauri-bridge.ts:132` assigns `window.api`, a shim that copies the v4 Electron contract onto Tauri. The renderer also depends on IIFE modules @@ -81,6 +91,10 @@ can drift without a compile error. Neither `tauri-specta` nor `ts-rs` is in **Status (2026-10-20): settings enums done in 5.0.0-beta.4** (`Theme`, `DockTab`, `DownloadProfile`, `GpuType`, `UpdateChannel`). Remaining: typed IPC structs in place of `serde_json::Value` plus hand validation. +**Status (2026-11-06): partially implemented; typed IPC structs remain open.** +The settings enums are present in `src-tauri/src/types.rs`. `serde_json::Value` +still appears in backend helpers and command/probe code; no claim is made that +the old acceptance criteria are complete. **Problem.** Several settings are free-form strings: `theme` (`src-tauri/src/types.rs:61`), `dock_tab` (`:63`), `download_mode` (`:65`), @@ -117,6 +131,10 @@ back to defaults rather than failing the import. ## 4. Replace the downloader and queue locks with a state thread +**Status (2026-11-06): accepted for ROSI 5.1; implementation not started in +this workstream.** The existing global mutex and condition-variable design +remains in `downloader.rs` and `queue.rs`. + **Problem.** The download and queue state uses global locks and condition variables. `src-tauri/src/downloader.rs:78` holds `ACTIVE: Mutex>` with `SESSION_CHANGED` (`:82`), `FINALIZING` (`:83`), and @@ -146,6 +164,10 @@ rather than enforced by types. ## 5. Async proxy relay on the Tauri runtime +**Status (2026-11-06): accepted for ROSI 5.1; implementation and runtime proof +remain outstanding.** `network_security.rs` still has the blocking worker pool +and relay polling described below. + **Problem.** `src-tauri/src/network_security.rs` is 1,917 lines. It starts `PROXY_WORKERS: usize = 32` blocking workers (`:35`). Each `proxy_worker` (`:604`) takes one client at a time, so the worker count caps concurrent @@ -178,6 +200,12 @@ idle relay still wakes up on its sleep. ## 6. Regroup E2E suites by feature +**Status (2026-11-06): verification foundation in progress.** The ROSI 5.1 +foundation adds a feature manifest and group selection while retaining every +scenario and its current file. The full folder move and runner split in this +section remain deferred; current full-suite and release evidence requirements +are preserved. + **Problem.** `e2e/` holds about 95 files and roughly 25,000 lines. 35 of the file names refer to audit rounds or repair passes (for example `round2-native.spec.js`, `audit4-repairs.spec.js`, and @@ -205,6 +233,8 @@ names say nothing about what they cover. `scripts/test-e2e.js` is 2,165 lines. ## 7. Centralize user-facing strings +**Status (2026-11-06): deferred beyond ROSI 5.1.** + **Problem.** User-facing text is written inline in the renderer and the Rust backend. `src/rosiEngine.ts` has about 56 lines that call a toast helper, and the Rust backend has about 225 `format!` string literals, not all of them user-facing. Wording differs between the two sides, and no one @@ -231,6 +261,10 @@ can translate or review the full set in one place. ## 8. macOS sidecar entitlements +**Status (2026-11-06): entitlement redesign deferred beyond ROSI 5.1.** The +current signing model remains part of platform verification; this roadmap item +does not authorize a pipeline or entitlement change. + **Problem.** Today `src-tauri/entitlements.plist` grants the whole app, including every sidecar, `disable-library-validation` and `allow-unsigned-executable-memory`. Only the PyInstaller `rosi-yt-dlp` needs them. The fix is already planned in @@ -251,6 +285,9 @@ with a dry run before changing the pipeline. ## 9. Signed yt-dlp-only update channel +**Status (2026-11-06): deferred beyond ROSI 5.1.** This is the independent +yt-dlp update channel explicitly excluded from the accepted 5.1 milestones. + **Problem.** yt-dlp is bundled. `assets/ytdlp-checksums.json` is the committed manifest (`scripts/fetch-ytdlp.cjs:37`), and `.github/workflows/ytdlp-watch.yml` updates it from the GPG-verified upstream `SHA2-256SUMS`. A YouTube break @@ -283,6 +320,8 @@ work, even though only one binary changed. ## 10. Dual-key updater support +**Status (2026-11-06): deferred beyond ROSI 5.1.** + **Problem.** The vendored updater trusts one Minisign public key, set in `src-tauri/tauri.conf.json:115` as `plugins.updater.pubkey`. A rotation needs a release signed with the old key, and a compromised old key can publish such a @@ -309,6 +348,8 @@ release too. [KEY-COMPROMISE.md](KEY-COMPROMISE.md) describes this limit. ## 11. Deno end of life (about October 2027) +**Status (2026-11-06): deferred beyond ROSI 5.1.** + **Problem.** yt-dlp uses Deno as its default JavaScript runtime for YouTube. Deno is expected to shut down around October 2027, and yt-dlp has not picked a replacement. ROSI finds Deno by path in `src-tauri/src/deno.rs:19` to `:48`, and @@ -333,6 +374,10 @@ wizard in `src/rosiEngine.ts`. See also the "Deno end of life" section of ## 12. Flathub or a hosted Flatpak repository +**Status (2026-11-06): new Flatpak hosting and Linux arm64 deferred beyond +ROSI 5.1.** Existing Flatpak packaging remains in the required Linux x64 +verification scope. + **Problem.** The Flatpak is a single-file bundle, `ROSI-Linux-x64.flatpak`, on the GitHub release. The in-app updater does not apply to Flatpak, so Flatpak users update only by downloading the new file by hand. The stable runbook's diff --git a/e2e/Microsoft/Windows/PowerShell/ModuleAnalysisCache b/e2e/Microsoft/Windows/PowerShell/ModuleAnalysisCache new file mode 100644 index 0000000000000000000000000000000000000000..6481bfe428e4f994f58a700fc7d81f9af1dc19fd GIT binary patch literal 10696 zcmeI2NpB=c6~{fSJuqy;zDa|`1*Edt-NS_g!Yf;3n?or>`I)Kk&}z< znhPAba0DR`XHI+xZX7vsLyX{n#1|NZgaq&RA|o@Z>>jD5k+^iXQYuHhc=4A1TOu;Y z(dcmdKJURPs# zZOUk7vg~YRrwudx&?8fyZLHsy{~ODr>qRx)_`0zDv^*zynpbt4Wdq0I12Xm@dD47t zUub`yr|$PBF`L%j^> z-4ssOW!v;LpA{Oh?4Y%Snf6nG3cW26_sCqNRc*?_I65+gt%BA%pK zTC2Jt9(s+1er@d!Fa7QVufB8dMt(j6*hgtn+RC2S>k9j0yQtQOHa|}w_@za3YziH*x? zWXt-noSG63eM+9!%|a&xp2ADHd{l-dQpQ&Ikt*p!tmPs_OQ zbgPJmFRc7d-MB8aqWbp!a_-th2N=$TYZRR!U zEZ7;4nUBcxrnU3^n!jF@XY)F~G~#aK6?Nz?ML2Vnnrpv>@;fqlJXcBBb!anNj??7Q znd3_`q*R+pV)A-3sne^tPHirxgZYQ$Ii8uh?(~J_^}|fqu)^k$g7=YaDswtBCKC*roTvL7#7&;e+~zRfvsJC0;1AWy3%{9N$BXJPKep-t*emh2$xLmw;^eX^LiRej zlP7kX<`)Qrx`A%+CA?I|z4T(1$s-woaloSETTNZt{JI-m(Oa?tw9) zIxg#`7?UVl|9(}51N8Jz=^?lbbTm zBq`S7KNSSZM`b(_%8|WN2!Bn6)X|&MsY(`S2dStR3i_|#zx$7$eCwTiL!o_!L^hT* zZpyQV>#s_xa(`%*rWz3F+oqE0I?-D88Tp$uP3qq+(<`%Io4Kzh6yn|VrWOD&#Iv9K z$^HDwUQz>-ONQ{=e(o}Nlt^Y_5I=bW5>ynQ8`&)=z?uZkMckb@nX!Z%A(^Miv_9j9 zEpu*58e0oJivpzAVf{UAI@BALFXX` zaYidJVh*K|GHM2*9cMVw!vZ9;fPcUG^&kKIH)-vDF2A1vBr7FM`@Z!CwX)(2EjN{y7L==;n1jHVSqrCP*uBr_@6c~K$F*1)Um7)v${ zck@aG0-%A$Q93tdY=mRmcX^5_*8mY+Q_> zrBeaPWE-g|Rc{tKF)bSv7OjMx#GZxddPPR_ULj{_jT;=7abCsR#du;gI1bzZjEA;Z zbZ86wa+juoVbN3%Wdb!^w}u zmW=lyDAXQA5TD2ieiZ;7MS#nL5hhrxmBnKgw4cVrde7DwM`Z}Lg#(?U^N}-ci&gFO zIx#VQ7{Z9NYC4G78>@vN&@5NKO_sw(-H}&}p=7M%!9$@AB8bf-$N1pD?5AZa*8r>B zE61H0C8wG9$_>J^nae#wkNXa8y|F;}NoDSGftNA#FZxw3i~B^gn%UI8voxD}{ji@) zcSk1Sd^bsRZ|rd+mm(ntPLqy!)ptIQ0~k_?+o*N^j7%ae-*6U75NGT`-gr$)L}ysI zxGL3UUa*PKOMqqJh^+6mz@6PdXcD&Z@ZdMDa~g!M!w7(7RVz|auP^I)JSD%$D?|ZD zu2nZ7`nH)g7a{)XKECs_k#-+%vG{%JK2B=A!nnKjXeYJrn9HU?e)hd&XPmYWM0F|0 z3`S8yia?@eZZ0=m4B{!y`-47~!07a#h?I>!WV+qo$aV;n_N{G_jB9O2sdEK93A7>38TT;B29!|G&z*kqhU7z}dL zINB;r>>3!Re61Nrw9ir*lS|L0l|Zu6&0JxvQR}V=j~9iJEo0B3O_1R*L3=*CAt@o$ z{#^CxxuFb_2XZphTJBUj3z!oTUAkic=rYjz2ky=)r*SDas-1J)pqynUw(6LXUpBKe z)`kLCo#c~DP7iW&bFR|F;lQ$6+WFwM${F9gI@FP|!=@fQD%0r`xqm@G%_YJ59&qj& zMf(xu98ITUao|XU@7sfsnNJ)(P%M&5k0eARzQk+_!Kj(Iv#DYM|Fr#%@*h@L2t;ad z;p%}F8n&|qX!PBJnH-t78fp6c`j+jn9qiQ(3<0?SrR+gU&G$9JZ`dIlcOreaE7oqI zu>^Ij;Q{E>VC2}C!0{ft8pM&_HzO}*Yf&_8q;J*J1m|GCPj_(-f^j?MC(7Hd_mPP&CC z-8-rEJY=mU_RI}hA`j6MW=F=_QFCZ$BwKJ|9Ea#=s98@cK#@?uEb+N4rs+W+Opke4%WW+C`&)*T*s&Qjdvc ze)Av>H%$EY+Tid#xn=h8>0IflaAb=qnu$yAWy6;xde1MzQ*`8ps#Cgz0!7U;C2E%Lh1cW1lkF`N+i6&XZUR6^;${CoUI0 z-dWqq9YhP_97!wSk_IJgxEoQzASVU%&O~~L2kFZ$NPw6OO!(}#3VLK|HCR@e3CD`l zFP%eM@Ry^y4FD`oG6><1aS(4T)ug=zp&|SJpT4K>F@Gr2&v4l_mM%czr@z?g-({}O zXzPWT=zvu1+CCj~`U(7bYo3Le{ni8-!N2irCw*+{>%?FT^#dNBOkafsWE@{sIEwGO zOAP9>uMtkqaMl;zmR~r+<=sRr?~8VA<6aLFx&+(my({==TZ{ho zmOe>p2nSG3Q*Lj)YDOHObeA|XwYK)3SAO&VePKD>K#T|Sxb!E%BC0%pVJQZA{=)M4 z3rh+nnP&6(3(LBa2IXllEd6IjuZyjor98`*Eb)}rpJxyF#^{WXM%;jwW8Mh@LOIjh zToSCIVf7ULtfS?!Tj$=9Q8y{qTF1LN$?$v95@qgC>Mt|a}+tGe{ zc{z3O7Z2-qe=6^B9}D@jn58?{iEe$z61kVGVww5Iw}m6X^i6=PFqni6V&x+x2ycHu z1)&yg$CkB}y={A)XI2`|w!Sk?*=zf~o|uB6>)S&Pg!Cn0izKEGzf|&_M=N#s*%L(+ zPquGTovF2m(sj@qFSR3V1~U3)Wo0W=QR!B`;REVM#bh8xc|nA-~RKr&g{#(@8=R*dh+5fQaiajHt|!B<-Ir4$gMZHju}S+|JmFv zTlb#Ba7$mwh3k9^)%hsEfwQ>3YS-4f-GD~Rj@ Ov)7^vp}@wndhLG*;s=5N literal 0 HcmV?d00001 diff --git a/e2e/README.md b/e2e/README.md index 76967686..4d7f926a 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -9,6 +9,16 @@ E2E binary once, runs every suite below against that binary, writes evidence to from that spec alone, and its report sets `fullSuite: false` and `onlySpec`, so release evidence rejects it. A blank value counts as unset. +`e2e/suites.json` is the canonical static scenario inventory and feature index. +It maps the existing files to their current runner owners; the files have not +been moved. To run selected feature groups, use `npm run test:e2e -- --group +settings,queue` or set `ROSI_E2E_GROUPS=settings,queue`. The selector expands to +the whole current runner owner, so a group that uses `main.spec.js` can report +scenarios from other features owned by that same pass. Reports include both the +requested groups and the expanded scenario list. Group runs set +`fullSuite: false`, use a fresh E2E binary, and are not release proof. A group +selection cannot be combined with `ROSI_E2E_ONLY`. + On a local Mac the gate runs ROSI in background mode (`ROSI_E2E_BACKGROUND=1`): the E2E app has no Dock icon, never takes focus, and its window stays below other apps. Native alert dialogs that specs open on purpose still appear. CI @@ -35,6 +45,49 @@ runs in the foreground; set `ROSI_E2E_FOREGROUND=1` to do the same locally. | `e2e/v5-fixes/persistence/run.mjs` | Persistence acceptance | Runner, `report.json` under `e2e/artifacts/v5-fixes-persistence/` | | `e2e/v5-fixes/downloader/run.mjs` | Downloader (install fallback, orphan sweep, panic log) | Runner, `report.json` under `e2e/artifacts/v5-fixes-downloader/` | +The report keeps the original flat `expectedScenarios` inventory for release +checks and adds `scenarioGroups` so outcomes can be read by feature. Existing +runner ownership, platform-specific skip allowances, fresh-report checks, and +the E2E binary hash checks are described in the manifest and runner. + +## ROSI 5.1 baseline capture + +`node scripts/benchmark-51.mjs --label current --snapshot ` +records the current source revision and dirty-file hashes, platform, tool +versions, evidence artifact and sidecar sizes, static and dynamic scenario +inventory, and references to reports already under `e2e/artifacts/`. Native +package sizes are recorded separately; when packages are absent, their size is +`not-measured` rather than zero. Frontend `dist/` size is also separate from +native packages. The command writes a timestamped JSON report and `.sha256` +sidecar; it does not execute scenarios. The inventory counts discovered cases, +while execution evidence remains `not-run` for the benchmark capture. + +The first full baseline report created during ROSI 5.1 foundation work was +overwritten while the shared artifact tree was changing. That report is not +retained or verifiable, and its contents are not reconstructed. A later +current-only capture does not stand in for that lost baseline. + +To compare a later capture, run: + +```sh +node scripts/benchmark-51.mjs --label candidate \ + --compare path/to/baseline.json \ + --runtime-metrics path/to/runtime-metrics.json +``` + +The default output includes a timestamp and refuses to replace an existing +file. An explicit `--out ` also refuses to overwrite; pass `--force` only +when replacement is intentional. The runtime metrics input uses +`schemaVersion: 1`, the measured `platform` and +`arch`, a `method` description, and a `measurements` object. Supported fields +are `startupMs` (`ms`), `idleCpuPercent` (`percent`), `peakMemoryBytes` +(`bytes`), `queueLatencyMs` (`ms`), and `proxyThroughputBytesPerSecond` +(`bytes_per_second`). Each value is an object with a numeric `value` and exact +`unit`; optional `samples`, `method`, and `evidence` fields preserve measurement +context. Missing values stay `not-measured`; comparisons produce a delta only +when both reports contain a compatible measurement. No historical runtime +result is inferred from existing E2E report files. + ### v5-fixes areas and `run.mjs` - An area with no `run.mjs` gets one WebdriverIO pass per area. Its specs run diff --git a/e2e/macos-native-packages.failure-modes.md b/e2e/macos-native-packages.failure-modes.md new file mode 100644 index 00000000..19709175 --- /dev/null +++ b/e2e/macos-native-packages.failure-modes.md @@ -0,0 +1,36 @@ +# macOS native package failure modes + +This inventory was written before implementation. `scripts/e2e-macos-native-packages.mjs` +will exercise the packaging and release-asset rules with isolated fixtures and +write repeatable JSON evidence. macOS signing, notarization, DMG mounting, and +native Mach-O inspection remain platform acceptance checks for a macOS release +machine. + +| ID | Failure mode | Required result | +| ----- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| MNP01 | An arm64 package is built from a universal or x86_64 app, or vice versa. | Reject the bundle because the ROSI host executable and native FFmpeg/ffprobe sidecars do not contain exactly the requested architecture. | +| MNP02 | A valid native bundle contains upstream universal2 yt-dlp. | Accept it when it includes the requested architecture; do not require yt-dlp to be thin. | +| MNP03 | Any app or sidecar requires a macOS version above the configured minimum. | Reject the package and identify the offending executable and slice. | +| MNP04 | The app or sidecar is ad-hoc signed, signed by another team, has mismatched entitlements, or is not notarized/stapled. | Reject before writing the ZIP; preserve Developer ID, team, entitlement, and staple checks for the requested slice. Fixture evidence checks these gates remain wired; signed acceptance requires macOS. | +| MNP05 | The plist marketing version or bundle version does not match the release config. | Reject the package. | +| MNP06 | The native DMG/ZIP receives a generic or colliding filename. | Emit the unique `ROSI-MacOS-arm64`, `ROSI-MacOS-x64`, or `ROSI-MacOS-universal` basename and keep each architecture distinct through collection, sidecars, and checksums. | +| MNP07 | A stale or duplicate architecture package is present alongside the new one. | Require current-session outputs, preserve architecture names, and fail on ambiguous same-name DMGs/ZIPs instead of silently choosing one. | +| MNP08 | A ZIP is missing, empty, or misnamed after packaging. | Fail E2E/release verification; require both native DMGs and ZIPs in the draft. | +| MNP09 | GPG signing sees native package names. | Sign each DMG and ZIP once; do not normalize native names back to universal or collide with the universal signatures. | +| MNP10 | SHA256SUMS files omit a native package, duplicate it, or use an architecture-inaccurate target key. | Generate deterministic checksum target lists covering each package and verify the uploaded checksum/signature assets against those names. | +| MNP11 | An updater manifest resolves a compact archive to the wrong architecture, or a native installer is mistaken for an updater archive. | Keep legacy universal app feeds intact; preserve per-architecture zstd feeds and validate the updater archive against the host architecture. | +| MNP12 | The macOS release rebuilds the same native app separately for installer and compact updater packaging. | Build each per-architecture app once with its DMG and updater archive, then feed that app/archive to both packagers. | +| MNP13 | A build or release command runs on Windows and pretends native macOS acceptance succeeded. | The fixture E2E reports static pipeline evidence only and clearly records native platform checks as blocked. | +| MNP14 | The updater's universal fallback, Rosetta native-arm64 selection, or missing-architecture fallback changes while adding native downloads. | Retain existing updater routing behavior and the universal release/update artifacts. | +| MNP15 | `--require-real-builds` runs off macOS or any of the six current package files is missing. | Fail the command; fixture helpers must never satisfy a real release gate. | +| MNP16 | A native DMG or ZIP is as large as or larger than its universal counterpart, or a payload hash cannot be recorded. | Fail for that package and report file size plus SHA-256 for every package and source bundle. | +| MNP17 | A ZIP is truncated, changes the app tree, loses its Developer ID signature, or loses its staple. | Extract it with macOS `ditto`, compare the complete bundle tree and executable hashes to the source app, then validate code signature and notarization staple. | +| MNP18 | A DMG cannot mount, contains no single `ROSI.app`, has the wrong target architecture, or fails signature/staple validation. | Attach read-only, require exactly one app, reuse target-aware bundle verification, and detach every mounted image in `finally`, including on failure. | +| MNP19 | A package or source bundle predates the current release build, or its version differs from `package.json`/`tauri.conf.json`. | Fail real acceptance rather than using stale or mismatched local artifacts. | +| MNP20 | A mounted volume remains after verification fails. | Detach every image attached by this E2E run in `finally` and report cleanup failures without hiding the original verification error. | + +Fixture mode is cross-platform pipeline evidence and does not prove that a +package was built, signed, stapled, mounted, or smaller. `--require-real-builds` +must run after the three real builds on macOS, verify every package and mounted +DMG, and write actual hashes, sizes, and native acceptance results. The release +chain uses this strict mode. diff --git a/e2e/rosi-51-foundation.failure-modes.md b/e2e/rosi-51-foundation.failure-modes.md new file mode 100644 index 00000000..c00f12a5 --- /dev/null +++ b/e2e/rosi-51-foundation.failure-modes.md @@ -0,0 +1,43 @@ +# ROSI 5.1 verification foundation failure modes + +This note is written before changes to the E2E runner and benchmark utility. + +1. **A scenario disappears from full proof.** A manifest omission, duplicate, + or typo can make the suite appear complete while coverage is missing. Keep + one canonical manifest entry per existing scenario, validate the inventory + for duplicates and missing/extra names, and keep full-gate evidence bound to + the whole canonical list. +2. **A selected feature runs the wrong underlying suite.** A group can point + at the wrong runner owner or miss a required pass. Make selection expand to + the existing runnable owner boundary and include that boundary's complete + expected scenario set; report the requested groups and expanded selection. +3. **A platform allowance masks a real failure.** A skip allowed on Windows, + macOS, or Linux can silently spread to the wrong host. Preserve the current + scenario-to-platform map verbatim and continue rejecting skipped outcomes + everywhere else. +4. **A runner-owned suite runs twice or not at all.** Treating a runner-owned + spec like a generic WebdriverIO spec can duplicate side effects; omitting its + owner can create a false pass. Preserve runner ownership and require each + runner's fresh, passing report as the full gate currently does. +5. **A targeted run is accepted as release proof.** Suite/group selection or + `ROSI_E2E_ONLY` can accidentally set `fullSuite: true` or claim the complete + expected list. Keep any targeted run partial and retain release-session's + checks for `fullSuite: true`, the canonical complete list, and the exact + E2E binary hash. +6. **A size or timing result looks more certain than its source.** Missing + files, absent reports, and unmeasured runtime metrics must not become zero + or inferred values. Record only observed sizes and report references, label + unavailable metrics explicitly, and compare only supplied, schema-valid + baseline reports. +7. **An artifact comparison mixes unrelated runs.** Different revisions, + platforms, or tool versions can make a delta misleading. Record those + identities in every benchmark report and mark comparisons incompatible when + the identity fields differ. + +## Acceptance boundary + +The full gate retains every existing scenario, its platform allowances, +execution owner, report checks, and binary hash. Manifest-selected runs are +useful for focused verification but never constitute full release proof. The +benchmark captures reproducible file-size and inventory data; runtime +performance remains unavailable until it is measured on the required hosts. diff --git a/e2e/round3-renderer-repairs/format-fixtures.cjs b/e2e/round3-renderer-repairs/format-fixtures.cjs new file mode 100644 index 00000000..870ccf18 --- /dev/null +++ b/e2e/round3-renderer-repairs/format-fixtures.cjs @@ -0,0 +1,14 @@ +// Typed get_formats payloads (FormatList in src-tauri media_info.rs). +function videoFormat(formatId, resolution) { + return { formatId, streamKind: "video", resolution }; +} + +function audioFormat(formatId) { + return { formatId, streamKind: "audio" }; +} + +function formatList(formats) { + return { formats }; +} + +module.exports = { audioFormat, formatList, videoFormat }; diff --git a/e2e/round3-renderer-repairs/preview.cjs b/e2e/round3-renderer-repairs/preview.cjs index ec790717..c8d64632 100644 --- a/e2e/round3-renderer-repairs/preview.cjs +++ b/e2e/round3-renderer-repairs/preview.cjs @@ -1,3 +1,8 @@ +const { + audioFormat, + formatList, + videoFormat, +} = require("./format-fixtures.cjs"); const fs = require("fs"); const path = require("node:path"); const root = path.resolve(__dirname, "../.."); @@ -54,7 +59,8 @@ w.api = new Proxy( getAppPlatform: () => Promise.resolve("darwin"), checkDenoInstalled: () => Promise.resolve(true), getQueue: () => Promise.resolve([]), - getFormats: () => ok("137 mp4 1920x1080 video only\n140 m4a audio only"), + getFormats: () => + ok(formatList([videoFormat("137", "1920x1080"), audioFormat("140")])), getVideoInfo: (url) => { previewCalls.push(url); return new Promise((r) => { diff --git a/e2e/round3-renderer-repairs/renderer.cjs b/e2e/round3-renderer-repairs/renderer.cjs index 57d47bf0..ca1b100b 100644 --- a/e2e/round3-renderer-repairs/renderer.cjs +++ b/e2e/round3-renderer-repairs/renderer.cjs @@ -1,3 +1,8 @@ +const { + audioFormat, + formatList, + videoFormat, +} = require("./format-fixtures.cjs"); const fs = require("fs"); const path = require("node:path"); const root = path.resolve(__dirname, "../.."); @@ -81,7 +86,8 @@ let updaterStatusHandler; const settingsSaveResolvers = []; let deferNextSettingsSave = false; const ok = (data) => Promise.resolve({ ok: true, data }); -getFormatsImpl = () => ok("137 mp4 1920x1080 video only\n140 m4a audio only"); +getFormatsImpl = () => + ok(formatList([videoFormat("137", "1920x1080"), audioFormat("140")])); w.api = new Proxy( { getChannel: () => "github", @@ -310,12 +316,12 @@ const wait = (ms) => new Promise((r) => setTimeout(r, ms)); await wait(20); resolveSecond?.({ ok: true, - data: "88 mp4 1280x720 video only\n89 m4a audio only", + data: formatList([videoFormat("88", "1280x720"), audioFormat("89")]), }); await wait(20); resolveFirst?.({ ok: true, - data: "177 mp4 3840x2160 video only\n178 m4a audio only", + data: formatList([videoFormat("177", "3840x2160"), audioFormat("178")]), }); await wait(40); const staleReplyFormats = { @@ -357,7 +363,8 @@ const wait = (ms) => new Promise((r) => setTimeout(r, ms)); await wait(30); input.value = "https://example.com/e"; input.dispatchEvent(new w.Event("input", { bubbles: true })); - getFormatsImpl = () => ok("277 mp4 1920x1080 video only\n278 m4a audio only"); + getFormatsImpl = () => + ok(formatList([videoFormat("277", "1920x1080"), audioFormat("278")])); w.document.getElementById("fetchFormatsBtn").click(); await wait(40); w.document.getElementById("videoFormat").value = "277"; @@ -383,7 +390,8 @@ const wait = (ms) => new Promise((r) => setTimeout(r, ms)); await wait(30); input.value = "https://example.com/f"; input.dispatchEvent(new w.Event("input", { bubbles: true })); - getFormatsImpl = () => ok("377 mp4 1920x1080 video only\n378 m4a audio only"); + getFormatsImpl = () => + ok(formatList([videoFormat("377", "1920x1080"), audioFormat("378")])); w.document.getElementById("fetchFormatsBtn").click(); await wait(40); w.document.getElementById("videoFormat").value = "377"; @@ -405,7 +413,7 @@ const wait = (ms) => new Promise((r) => setTimeout(r, ms)); await wait(30); resolvePresetLookup?.({ ok: true, - data: "477 mp4 1920x1080 video only\n478 m4a audio only", + data: formatList([videoFormat("477", "1920x1080"), audioFormat("478")]), }); await wait(50); const presetSurvivesStaleLookup = { diff --git a/e2e/round3-renderer-repairs/updater.cjs b/e2e/round3-renderer-repairs/updater.cjs index 497cb74e..01ed8b48 100644 --- a/e2e/round3-renderer-repairs/updater.cjs +++ b/e2e/round3-renderer-repairs/updater.cjs @@ -1,3 +1,8 @@ +const { + audioFormat, + formatList, + videoFormat, +} = require("./format-fixtures.cjs"); const fs = require("fs"); const path = require("node:path"); const ts = require( @@ -53,7 +58,8 @@ w.api = new Proxy( getAppPlatform: () => Promise.resolve("darwin"), checkDenoInstalled: () => Promise.resolve(true), getQueue: () => Promise.resolve([]), - getFormats: () => ok("137 mp4 1920x1080 video only\n140 m4a audio only"), + getFormats: () => + ok(formatList([videoFormat("137", "1920x1080"), audioFormat("140")])), getVideoInfo: () => ok({}), downloadVideo: (a) => { downloadArgs = a; diff --git a/e2e/specs/main.spec.js b/e2e/specs/main.spec.js index 33bea332..64400dd4 100644 --- a/e2e/specs/main.spec.js +++ b/e2e/specs/main.spec.js @@ -1757,12 +1757,27 @@ describe("ROSI main window", () => { : `${MEDIA}/clip-one.mp4`; const formats = await api("getFormats", url); assert.equal(formats.ok, true, formats.error?.message); + assert.ok(Array.isArray(formats.data.formats)); + assert.ok( + formats.data.formats.every( + (format) => + typeof format.formatId === "string" && + ["audio", "video", "audioVideo"].includes(format.streamKind), + ), + ); if (HAS_FFMPEG) { - assert.match(formats.data, /audio only/); - assert.match(formats.data, /video only/); + assert.ok( + formats.data.formats.some((format) => format.streamKind === "audio"), + ); + assert.ok( + formats.data.formats.some((format) => format.streamKind === "video"), + ); } record("formats", { - lines: formats.data.split(/\r?\n/).filter(Boolean).length, + formats: formats.data.formats.length, + streamKinds: [ + ...new Set(formats.data.formats.map((format) => format.streamKind)), + ], }); }); @@ -3458,13 +3473,28 @@ describe("ROSI main window", () => { !defaults.sponsorblockRemove, "SponsorBlock change was not saved", ); - await browser.execute(() => - document - .querySelector( - '.settings-section-reset[data-reset-section="enhancements"]', - ) - .click(), - ); + const resetEnhancements = () => + browser.execute(() => + document + .querySelector( + '.settings-section-reset[data-reset-section="enhancements"]', + ) + .click(), + ); + // Reset asks first: Cancel must leave the changed values alone. + await resetEnhancements(); + await waitForModal(true, "section reset did not ask for confirmation"); + await clickModalButton("Cancel"); + await waitForModal(false, "Cancel did not close the reset prompt"); + assert.equal( + settingsOnDisk().embedMetadata, + !defaults.embedMetadata, + "Cancel changed the metadata setting", + ); + await resetEnhancements(); + await waitForModal(true, "section reset did not reopen the prompt"); + await clickModalButton("Reset section"); + await waitForModal(false, "confirmed reset did not close the prompt"); await waitForSavedSetting( "embedMetadata", defaults.embedMetadata, diff --git a/e2e/suites.json b/e2e/suites.json new file mode 100644 index 00000000..193d1e7c --- /dev/null +++ b/e2e/suites.json @@ -0,0 +1,784 @@ +{ + "schemaVersion": 1, + "selectionBoundary": "existing runner owner; selected groups expand to every scenario owned by selected passes", + "groups": [ + { + "id": "conversion", + "owners": ["main", "v5-fixes"], + "v5FixAreas": ["download-options", "typed-formats"] + }, + { + "id": "dock-ui", + "owners": ["main", "round2-renderer", "round3-renderer"], + "v5FixAreas": [] + }, + { + "id": "downloads", + "owners": [ + "audit4-repairs", + "main", + "process-repairs", + "round2-native", + "state-repairs", + "v5-fixes" + ], + "v5FixAreas": ["downloader"] + }, + { + "id": "legacy-import", + "owners": ["legacy-import"], + "v5FixAreas": [] + }, + { + "id": "lifecycle", + "owners": ["state-repairs", "v5-fixes"], + "v5FixAreas": ["queue-coordinator"] + }, + { + "id": "network-policy", + "owners": ["main", "security", "v5-fixes"], + "v5FixAreas": ["async-proxy", "network", "upstream-proxy"] + }, + { + "id": "onboarding", + "owners": ["main"], + "v5FixAreas": [] + }, + { + "id": "packaging", + "owners": ["main", "v5-fixes"], + "v5FixAreas": ["flatpak-updates"] + }, + { + "id": "persistence", + "owners": ["persistence", "v5-fixes"], + "v5FixAreas": ["persistence"] + }, + { + "id": "platform-verification", + "owners": ["audit-v5-beta2", "v5-fixes"], + "v5FixAreas": ["platform"] + }, + { + "id": "queue", + "owners": ["main", "offline-queue", "state-repairs", "v5-fixes"], + "v5FixAreas": ["queue-coordinator"] + }, + { + "id": "settings", + "owners": ["main", "state-repairs"], + "v5FixAreas": [] + }, + { + "id": "updater", + "owners": ["main", "state-repairs", "v5-fixes"], + "v5FixAreas": ["deno-installer"] + }, + { + "id": "ui-polish", + "owners": ["v5-fixes"], + "v5FixAreas": ["ui-polish"] + } + ], + "owners": { + "legacy-import": { + "id": "legacy-import", + "kind": "webdriverio", + "entrypoint": "e2e/specs/legacy-import.spec.js" + }, + "main": { + "id": "main", + "kind": "webdriverio", + "entrypoint": "e2e/specs/main.spec.js" + }, + "offline-queue": { + "id": "offline-queue", + "kind": "webdriverio", + "entrypoint": "e2e/specs/security-release-offline-queue.spec.js" + }, + "security": { + "id": "security", + "kind": "webdriverio", + "entrypoint": "e2e/specs/security-release-repairs.spec.js" + }, + "state-repairs": { + "id": "state-repairs", + "kind": "webdriverio", + "entrypoint": "e2e/state-updater-repairs.spec.js" + }, + "round2-renderer": { + "id": "round2-renderer", + "kind": "webdriverio", + "entrypoint": "e2e/round2-renderer-repairs.spec.js" + }, + "process-repairs": { + "id": "process-repairs", + "kind": "runner", + "entrypoint": "e2e/run-download-process-repairs.mjs" + }, + "round2-native": { + "id": "round2-native", + "kind": "runner", + "entrypoint": "e2e/round2-native-run.mjs" + }, + "persistence": { + "id": "persistence", + "kind": "runner", + "entrypoint": "e2e/long-term-v5-audit-run.mjs" + }, + "audit4-repairs": { + "id": "audit4-repairs", + "kind": "runner", + "entrypoint": "e2e/audit4-repairs-run.mjs" + }, + "audit-v5-beta2": { + "id": "audit-v5-beta2", + "kind": "runner", + "entrypoint": "e2e/audit-v5-beta2/run-probes.mjs" + }, + "round3-renderer": { + "id": "round3-renderer", + "kind": "node-runner", + "entrypoint": "e2e/round3-renderer-repairs/run.cjs" + }, + "v5-fixes": { + "id": "v5-fixes", + "kind": "dynamic-runner", + "entrypoint": "e2e/v5-fixes//run.mjs or WebdriverIO" + } + }, + "scenarios": [ + { + "name": "legacy-v4-import", + "feature": "legacy-import", + "owner": "legacy-import", + "allowedSkips": [] + }, + { + "name": "legacy-v4-corrupt-settings", + "feature": "legacy-import", + "owner": "legacy-import", + "allowedSkips": [] + }, + { + "name": "launch", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "legacy-v4-preserve", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "settings-sidebar", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "settings-persistence", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "download-profiles", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "settings-layout", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "flat-ui-tokens", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "window-theme", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "no-overscroll", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "sidebar-glass", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "url-safety", + "feature": "network-policy", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "loopback-exception-and-thumbnail-data", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "loopback-download", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "proxy-delayed-http-response", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "proxy-cancels-streamed-response", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "private-dns-alias", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "dns-rebinding-connection-time", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "redirect-and-extractor-handoffs", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "verified-https-connect-proxy", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "untrusted-https-certificate-rejected", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "credential-bearing-urls", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "guarded-hls-fragments", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "bracketed-ipv6-classification", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "proxy-cancellation-closes-active-sockets", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "thumbnail-fetch-cancellation", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "dns-cancellation-reserved-ipc", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "proxy-rejects-unreviewed-pipelined-destination", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "bounded-dns-cancellation", + "feature": "network-policy", + "owner": "security", + "allowedSkips": [] + }, + { + "name": "persisted-offline-queue", + "feature": "queue", + "owner": "offline-queue", + "allowedSkips": [] + }, + { + "name": "manual-download", + "feature": "downloads", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "unicode-download", + "feature": "downloads", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "queue", + "feature": "queue", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "cancel", + "feature": "queue", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "conversion", + "feature": "conversion", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "audio-extract", + "feature": "conversion", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "gpu-detect", + "feature": "conversion", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "licenses", + "feature": "packaging", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "navigation-guard", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "preview", + "feature": "downloads", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "formats", + "feature": "conversion", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "merge-download", + "feature": "conversion", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "queue-management", + "feature": "queue", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "queue-cancel", + "feature": "queue", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "dock-tabs", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "webview-guard", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "link-drop", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "small-window", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "dock-empty", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "save-path", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "lucide-icons", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "status-icons", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "console-log", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "activity-actions", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "activity-action-clicks", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "theme-contrast", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "setup-wizard", + "feature": "onboarding", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "setup-wizard-skip", + "feature": "onboarding", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "setup-wizard-escape", + "feature": "onboarding", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "setup-wizard-small", + "feature": "onboarding", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "setup-wizard-deno", + "feature": "onboarding", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "browser-choice", + "feature": "onboarding", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "xdg-download-dir", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": ["darwin", "win32"] + }, + { + "name": "ui-screenshots", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "stats", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "settings-search-reset", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "settings-controls", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "settings-reset-all", + "feature": "settings", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "settings-response-revision", + "feature": "settings", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "settings-rejection-preserves-newer-field", + "feature": "settings", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "settings-lifecycle-latest-revision", + "feature": "settings", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "settings-captured-wizard-deno", + "feature": "settings", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "compatible-profile-wording", + "feature": "settings", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "guarded-preview-thumbnail", + "feature": "downloads", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "queue-latest-snapshot", + "feature": "queue", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "updater-generation-retry", + "feature": "updater", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "queue-flush-backup-failure", + "feature": "queue", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "close-pending-timeout", + "feature": "lifecycle", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "download-session-isolation", + "feature": "downloads", + "owner": "state-repairs", + "allowedSkips": [] + }, + { + "name": "external-links", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "menu-actions", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "update-check", + "feature": "updater", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "dialogs", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "download-card-input", + "feature": "downloads", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "presets", + "feature": "downloads", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "custom-formats", + "feature": "downloads", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "playlist-range", + "feature": "downloads", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "embed-extras", + "feature": "downloads", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "queue-controls", + "feature": "queue", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "save-location", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "notifications", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "download-again-quickly", + "feature": "queue", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "download-process-repairs", + "feature": "downloads", + "owner": "process-repairs", + "allowedSkips": ["win32"] + }, + { + "name": "activity-clear", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "close-flow", + "feature": "dock-ui", + "owner": "main", + "allowedSkips": [] + }, + { + "name": "round2-renderer", + "feature": "dock-ui", + "owner": "round2-renderer", + "allowedSkips": [] + }, + { + "name": "round2-native", + "feature": "downloads", + "owner": "round2-native", + "allowedSkips": [] + }, + { + "name": "long-term-persistence", + "feature": "persistence", + "owner": "persistence", + "allowedSkips": [] + }, + { + "name": "audit3-native-targeted", + "feature": "downloads", + "owner": "process-repairs", + "allowedSkips": ["win32"] + }, + { + "name": "audit4-repairs", + "feature": "downloads", + "owner": "audit4-repairs", + "allowedSkips": [] + }, + { + "name": "audit-v5-beta2", + "feature": "platform-verification", + "owner": "audit-v5-beta2", + "allowedSkips": ["linux", "win32"] + }, + { + "name": "round3-renderer-repairs", + "feature": "dock-ui", + "owner": "round3-renderer", + "allowedSkips": [] + } + ], + "dynamicV5Fixes": { + "owner": "v5-fixes", + "groupAreas": { + "downloads": ["downloader"], + "queue": ["queue-coordinator"], + "conversion": ["download-options", "typed-formats"], + "network-policy": ["async-proxy", "network", "upstream-proxy"], + "persistence": ["persistence"], + "updater": ["deno-installer"], + "packaging": ["flatpak-updates"], + "platform-verification": ["platform"], + "ui-polish": ["ui-polish"] + } + } +} diff --git a/e2e/v5-fixes/async-proxy/async-proxy.spec.js b/e2e/v5-fixes/async-proxy/async-proxy.spec.js new file mode 100644 index 00000000..9d28400f --- /dev/null +++ b/e2e/v5-fixes/async-proxy/async-proxy.spec.js @@ -0,0 +1,155 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { browser } from "@wdio/globals"; +import { waitForAppReady } from "../../helpers/app-bridge.js"; + +const resultsDirectory = process.env.ROSI_V5_ASYNC_PROXY_RESULTS_DIR; +const observations = []; +let outcome; + +function record(name, details) { + observations.push({ name, ...details }); + if (!resultsDirectory) return; + fs.mkdirSync(resultsDirectory, { recursive: true }); + fs.writeFileSync( + path.join(resultsDirectory, "observations.json"), + `${JSON.stringify(observations, null, 2)}\n`, + ); +} + +async function invokeProbe() { + const encoded = await browser.executeAsync((done) => { + window.__TAURI__.core.invoke("e2e_network_pipelining_probe").then( + (value) => done(JSON.stringify({ ok: true, value })), + (error) => done(JSON.stringify({ ok: false, error: String(error) })), + ); + }); + return JSON.parse(encoded); +} + +function probeSection(name) { + assert.ok(outcome?.ok, JSON.stringify(outcome)); + const section = outcome.value?.asyncProxy?.[name]; + assert.ok(section, `probe omitted asyncProxy.${name}`); + return section; +} + +describe("V5 bounded asynchronous proxy", () => { + before(async () => { + await waitForAppReady(); + outcome = await invokeProbe(); + }); + + it("serves at least 256 simultaneous vetted CONNECT tunnels", async () => { + const capacity = outcome.value?.asyncProxy?.capacity; + const invariantPassed = + outcome.ok === true && + capacity?.requestedTunnels === 256 && + capacity?.activeLimit >= 256 && + capacity?.activeAtCapacity >= 256 && + capacity?.peakActiveTunnels >= 256 && + capacity?.peakActiveConnections >= 256; + record("active-tunnel-capacity", { + probeError: outcome.ok ? null : outcome.error, + capacity: capacity ?? null, + invariantPassed, + }); + assert.ok(outcome.ok, JSON.stringify(outcome)); + assert.equal(capacity?.requestedTunnels, 256); + assert.ok(capacity?.activeLimit >= 256); + assert.ok(capacity?.activeAtCapacity >= 256); + assert.ok(capacity?.peakActiveTunnels >= 256); + assert.ok(capacity?.peakActiveConnections >= 256); + }); + + it("caps pending admissions and rejects overload with HTTP 503", async () => { + const capacity = outcome.value?.asyncProxy?.capacity; + const invariantPassed = + outcome.ok === true && + capacity?.pendingLimit > 0 && + capacity?.pendingHighWater === capacity?.pendingLimit && + capacity?.overloadStatus === 503 && + capacity?.overloadRejections >= 1; + record("bounded-overload", { + probeError: outcome.ok ? null : outcome.error, + pendingLimit: capacity?.pendingLimit ?? null, + pendingHighWater: capacity?.pendingHighWater ?? null, + overloadStatus: capacity?.overloadStatus ?? null, + overloadRejections: capacity?.overloadRejections ?? null, + invariantPassed, + }); + assert.ok(outcome.ok, JSON.stringify(outcome)); + assert.ok(capacity?.pendingLimit > 0); + assert.equal(capacity?.pendingHighWater, capacity?.pendingLimit); + assert.equal(capacity?.overloadStatus, 503); + assert.ok(capacity?.overloadRejections >= 1); + }); + + it("cancels active and queued proxy sockets and upstream tunnels", async () => { + const cancellation = probeSection("cancellation"); + const invariantPassed = + cancellation.activeConnectionsAfterCancel === 0 && + cancellation.activeTunnelsAfterCancel === 0 && + cancellation.pendingAdmissionsAfterCancel === 0 && + cancellation.closedClientSockets === cancellation.expectedClientSockets && + cancellation.expectedClientSockets === 384 && + cancellation.closedOriginSockets === cancellation.expectedOriginSockets && + cancellation.expectedOriginSockets === 256 && + cancellation.elapsedMs <= 5000; + record("operation-cancellation-cleanup", { cancellation, invariantPassed }); + assert.equal(cancellation.activeConnectionsAfterCancel, 0); + assert.equal(cancellation.activeTunnelsAfterCancel, 0); + assert.equal(cancellation.pendingAdmissionsAfterCancel, 0); + assert.equal(cancellation.closedClientSockets, 384); + assert.equal(cancellation.closedOriginSockets, 256); + assert.ok(cancellation.elapsedMs <= 5000); + }); + + it("drops its listener and active client without blocking", async () => { + const drop = probeSection("drop"); + const invariantPassed = + drop.activeConnectionsAfterDrop === 0 && + drop.closedClientSocket === true && + drop.elapsedMs <= 5000; + record("guard-drop-cleanup", { drop, invariantPassed }); + assert.equal(drop.activeConnectionsAfterDrop, 0); + assert.equal(drop.closedClientSocket, true); + assert.ok(drop.elapsedMs <= 5000); + }); + + it("retains HTTP pipeline blocking and bounded DNS resolution", async () => { + const requests = outcome.value?.requests ?? []; + const dns = outcome.value?.dnsResolution; + const invariantPassed = + outcome.ok === true && + outcome.value?.responseStatus === 200 && + requests.length === 1 && + requests.every((request) => request.includes("/first")) && + outcome.value?.secondTargetForwarded === false && + dns?.maxActiveWorkers <= dns?.workerLimit && + dns?.workerLimit === 4 && + dns?.queueHighWater <= dns?.queueLimit && + dns?.queueLimit === 16 && + dns?.pendingAfterDrain === 0 && + dns?.activeAfterDrain === 0; + record("framing-and-dns-regression", { + probeError: outcome.ok ? null : outcome.error, + requestCount: requests.length, + responseStatus: outcome.value?.responseStatus ?? null, + secondTargetForwarded: outcome.value?.secondTargetForwarded ?? null, + dns: dns ?? null, + invariantPassed, + }); + assert.ok(outcome.ok, JSON.stringify(outcome)); + assert.equal(outcome.value?.responseStatus, 200); + assert.equal(requests.length, 1); + assert.ok(requests.every((request) => request.includes("/first"))); + assert.equal(outcome.value?.secondTargetForwarded, false); + assert.equal(dns?.workerLimit, 4); + assert.ok(dns?.maxActiveWorkers <= dns?.workerLimit); + assert.ok(dns?.queueHighWater <= dns?.queueLimit); + assert.equal(dns?.pendingAfterDrain, 0); + assert.equal(dns?.activeAfterDrain, 0); + }); +}); diff --git a/e2e/v5-fixes/async-proxy/failure-modes.md b/e2e/v5-fixes/async-proxy/failure-modes.md new file mode 100644 index 00000000..90ef8ef9 --- /dev/null +++ b/e2e/v5-fixes/async-proxy/failure-modes.md @@ -0,0 +1,76 @@ +# Async proxy failure modes + +This inventory was written before the implementation change. The existing +`NetworkSecurityGuard` synchronous constructors and credential-bearing proxy +URL remain the caller contract. The listener and every client operation must +run on Tauri's Tokio runtime, with admission and DNS work bounded independently. + +1. **The caller has no ambient Tokio handle.** A synchronous downloader or + metadata caller must still start the guard through Tauri's shared runtime; + startup failures are returned and never cause an unproxied network fallback. +2. **Many long-lived CONNECT tunnels consume all service capacity.** At least + 256 active connections must be serviceable without a fixed 32-worker queue. +3. **A burst exceeds connection capacity.** Pending admission is capped; excess + clients receive an explicit bounded 503 response and do not create tasks or + retain sockets indefinitely. +4. **An owner cancels or drops its guard with idle or active connections.** The + listener, pending sockets, client tasks, and both tunnel endpoints are + cancelled and released promptly. +5. **Cancellation happens during DNS, connect, header parsing, body copying, + or upstream-proxy negotiation.** The caller wait returns without accumulating + unabortable DNS jobs or leaving connection tasks behind. +6. **A DNS storm outlives its callers.** Resolver workers and queued lookups + stay independently bounded; dropping a wait removes queued work and running + system lookups remain capped by the fixed resolver worker count. +7. **A peer sends a partial or oversized request header or an idle tunnel.** + Header limits and idle deadlines terminate it without busy polling or a + blocked runtime worker. +8. **Authentication is missing, duplicated, or incorrect.** Exactly one valid + proxy credential is required before resolving or connecting to a destination. +9. **A hostname resolves to a private, mixed public/private, or changing + address set.** Reject unsafe answer sets and connect directly only to the + exact addresses that were vetted; retain IPv4 and IPv6 classification. +10. **An upstream HTTP proxy is configured.** Preserve its existing CONNECT and + absolute-form behavior while still vetting the requested destination; do + not apply destination policy to the user's upstream itself. +11. **A CONNECT request arrives with tunnel payload already buffered after its + headers, or the upstream sends payload with its success headers.** Preserve + both byte sequences exactly and relay both directions with TCP half-close + behavior. +12. **A half-close is mistaken for full connection closure.** Forward the + remaining response in the opposite direction until both sides end or the + idle deadline expires. +13. **Plain HTTP uses ambiguous or excessive framing.** Enforce header and body + byte limits, reject conflicting or repeated framing headers, copy only the + framed body, and never forward a pipelined second request on the connection. +14. **Backpressure or slow peers stall a connection.** Async reads/writes and + per-operation deadlines must not block unrelated connections or grow + buffers without a limit. +15. **A task exits through I/O error, cancellation, or panic.** Admission slots + and active-socket ownership are released, and shutdown still drains or + aborts all tracked tasks. +16. **The new capacity probe is missing, synthetic, or only checks configuration + constants.** The existing `e2e_network_pipelining_probe` must exercise real + loopback traffic and report observed 256-tunnel service, overload rejection, + cancellation cleanup, and unchanged pipeline blocking in repeatable JSON. + +The native E2E probe is the acceptance mechanism for concurrency and cleanup. +Rust unit tests must not be added after implementation; existing network and +upstream-proxy E2E specs remain required regression coverage. + +## Repeatable probe evidence + +The new `asyncProxy` object is added to the existing +`e2e_network_pipelining_probe` result; it does not add a Tauri command. Its +`capacity` section reports `requestedTunnels`, `activeLimit`, +`activeAtCapacity`, `peakActiveTunnels`, `pendingLimit`, `pendingHighWater`, +`overloadStatus`, and `overloadRejections`. The `cancellation` section reports +`activeConnectionsAfterCancel`, `activeTunnelsAfterCancel`, +`pendingAdmissionsAfterCancel`, `closedClientSockets`, +`expectedClientSockets`, `closedOriginSockets`, `expectedOriginSockets`, and +`elapsedMs`. The `drop` section reports `activeConnectionsAfterDrop`, +`closedClientSocket`, and `elapsedMs`. Acceptance requires 256 simultaneously +open tunnels, a full bounded pending queue followed by HTTP 503, and zero +active/pending resources after both operation cancellation and guard drop. The +same result records the existing pipelining check so the new runner proves +that the second request was never forwarded. diff --git a/e2e/v5-fixes/async-proxy/run.mjs b/e2e/v5-fixes/async-proxy/run.mjs new file mode 100644 index 00000000..d269f5c1 --- /dev/null +++ b/e2e/v5-fixes/async-proxy/run.mjs @@ -0,0 +1,141 @@ +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { + createE2eProfile, + e2eBinaryPath, + e2eStampPath, + REPO_ROOT, +} from "../../helpers/profile.js"; + +const relativeArtifactRoot = path.join( + process.env.ROSI_E2E_ARTIFACT_DIR ?? + path.join(REPO_ROOT, "e2e", "artifacts", "v5-fixes-async-proxy"), + `${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`, +); +const artifactRoot = path.isAbsolute(relativeArtifactRoot) + ? relativeArtifactRoot + : path.join(REPO_ROOT, relativeArtifactRoot); +const binary = process.env.ROSI_E2E_BINARY ?? e2eBinaryPath(); +const stamp = e2eStampPath(); +if ( + !fs.existsSync(binary) || + !fs.existsSync(stamp) || + fs.statSync(stamp).mtimeMs < fs.statSync(binary).mtimeMs +) { + throw new Error( + "Build a fresh E2E binary with npm run test:e2e before running this suite.", + ); +} + +const hash = (bytes) => crypto.createHash("sha256").update(bytes).digest("hex"); +const sourceFiles = [ + "e2e/v5-fixes/async-proxy/run.mjs", + "e2e/v5-fixes/async-proxy/async-proxy.spec.js", + "e2e/v5-fixes/async-proxy/failure-modes.md", + "src-tauri/src/network_security.rs", + "src-tauri/src/network_security_async.rs", + "src-tauri/Cargo.toml", + "src-tauri/Cargo.lock", +]; +fs.mkdirSync(artifactRoot, { recursive: true }); +for (const source of sourceFiles) { + const from = path.join(REPO_ROOT, source); + if (!fs.existsSync(from)) continue; + const destination = path.join(artifactRoot, "sources", source); + fs.mkdirSync(path.dirname(destination), { recursive: true }); + fs.copyFileSync(from, destination); +} +const patch = spawnSync("git", ["diff", "--binary", "HEAD"], { + cwd: REPO_ROOT, + encoding: "buffer", +}); +if (patch.error || patch.status !== 0) { + throw new Error( + `Could not capture the working-tree diff: ${patch.error?.message ?? patch.stderr?.toString() ?? patch.status}`, + ); +} +fs.writeFileSync(path.join(artifactRoot, "working-tree.patch"), patch.stdout); + +const profile = createE2eProfile(); +const resultsDirectory = path.join(artifactRoot, "app"); +const result = spawnSync( + process.execPath, + [ + path.join(REPO_ROOT, "node_modules", "@wdio", "cli", "bin", "wdio.js"), + "run", + "e2e/wdio.conf.js", + ], + { + cwd: REPO_ROOT, + env: { + ...process.env, + ...profile.env, + ROSI_E2E_BINARY: binary, + ROSI_E2E_DOWNLOADS: profile.downloads, + ROSI_E2E_XDG_DOWNLOADS: profile.xdgDownloads, + ROSI_E2E_PROFILE: profile.profileDir, + ROSI_E2E_SPECS: "./v5-fixes/async-proxy/async-proxy.spec.js", + ROSI_V5_ASYNC_PROXY_RESULTS_DIR: resultsDirectory, + }, + encoding: "utf8", + windowsHide: true, + timeout: 300_000, + maxBuffer: 16 * 1024 * 1024, + }, +); +const launchError = result.error + ? { + message: result.error.message, + code: result.error.code ?? null, + } + : null; +fs.writeFileSync( + path.join(artifactRoot, "wdio.log"), + `${result.stdout ?? ""}${result.stderr ?? ""}${result.error ? `\n[WDIO launcher error]\n${result.error.stack ?? result.error.message}\n` : ""}`, +); + +let observations = []; +try { + observations = JSON.parse( + fs.readFileSync(path.join(resultsDirectory, "observations.json"), "utf8"), + ); +} catch {} +const body = { + suite: "v5-fixes-async-proxy", + startedAt: new Date().toISOString(), + exitStatus: result.status, + signal: result.signal ?? null, + launchError, + binarySha256: hash(fs.readFileSync(binary)), + workingTreeDiffSha256: hash( + fs.readFileSync(path.join(artifactRoot, "working-tree.patch")), + ), + sources: sourceFiles + .filter((source) => + fs.existsSync(path.join(artifactRoot, "sources", source)), + ) + .map((source) => ({ + path: source, + sha256: hash(fs.readFileSync(path.join(artifactRoot, "sources", source))), + })), + observations, +}; +const passed = + result.status === 0 && + observations.length === 5 && + observations.every((observation) => observation.invariantPassed === true); +const report = { + ...body, + passed, + reportSha256: hash(Buffer.from(JSON.stringify(body, null, 2))), +}; +fs.writeFileSync( + path.join(artifactRoot, "report.json"), + `${JSON.stringify(report, null, 2)}\n`, +); +console.log( + `V5 async proxy evidence: ${path.join(artifactRoot, "report.json")}`, +); +if (!passed) process.exitCode = 1; diff --git a/e2e/v5-fixes/download-options/download-options.spec.js b/e2e/v5-fixes/download-options/download-options.spec.js new file mode 100644 index 00000000..e7b68a3c --- /dev/null +++ b/e2e/v5-fixes/download-options/download-options.spec.js @@ -0,0 +1,267 @@ +import assert from "node:assert/strict"; +import { browser } from "@wdio/globals"; +import { api, waitForAppReady } from "../../helpers/app-bridge.js"; + +const MEDIA = process.env.ROSI_E2E_MEDIA_URL; +const DOWNLOADS = process.env.ROSI_E2E_DOWNLOADS; + +function withoutUrl(options) { + const copy = { ...options }; + delete copy.url; + return copy; +} + +describe("shared download option resolution", () => { + let originalSettings; + + before(async () => { + await waitForAppReady(); + originalSettings = await api("getSettings"); + assert.ok(MEDIA, "ROSI_E2E_MEDIA_URL is required"); + assert.ok(DOWNLOADS, "ROSI_E2E_DOWNLOADS is required"); + }); + + after(async () => { + await api("clearQueue"); + if (originalSettings) { + const restored = await api("saveSettings", originalSettings); + assert.equal(restored.ok, true, restored.error?.message); + } + }); + + it("shares preset and explicit-option precedence across manual and queue requests", async () => { + await api("clearQueue"); + const preset = { + id: "resolver-e2e", + name: "Resolver E2E", + profile: "audio", + bestQuality: true, + audioOnly: true, + audioFormat: "flac", + convertEnabled: true, + convertFormat: "m4a", + keepOriginalAfterConvert: false, + gpuAcceleration: true, + gpuType: "nvidia", + playlist: { mode: "all" }, + }; + const saved = await api("saveSettings", { + downloadMode: "custom", + advancedOptions: true, + bestQuality: false, + audioOnly: false, + convertEnabled: false, + gpuAcceleration: false, + downloadPresets: [preset], + }); + assert.equal(saved.ok, true, saved.error?.message); + + const url = `${MEDIA}/clip-one.mp4?resolver=manual-${Date.now()}`; + const explicit = { + url, + outputPath: DOWNLOADS, + presetId: preset.id, + profile: "compatible", + bestQuality: false, + audioOnly: false, + convertEnabled: false, + gpuAcceleration: false, + playlist: { mode: "current" }, + }; + const manual = await api("resolveDownloadOptions", explicit); + assert.equal(manual.ok, true, manual.error?.message); + assert.equal(manual.data.profile, "compatible"); + assert.equal(manual.data.bestQuality, false); + assert.equal(manual.data.audioOnly, false); + assert.equal(manual.data.convertEnabled, false); + assert.equal(manual.data.gpuAcceleration, false); + assert.equal(manual.data.convertFormat, "m4a"); + assert.equal(manual.data.keepOriginal, false); + assert.equal(manual.data.audioOutputFormat, "flac"); + assert.deepEqual(manual.data.playlist, { mode: "current" }); + + const nullsInherit = await api("resolveDownloadOptions", { + ...explicit, + profile: null, + bestQuality: null, + audioOnly: null, + convertEnabled: null, + gpuAcceleration: null, + playlist: null, + }); + assert.equal(nullsInherit.ok, true, nullsInherit.error?.message); + assert.equal(nullsInherit.data.profile, "audio"); + assert.equal(nullsInherit.data.bestQuality, true); + assert.equal(nullsInherit.data.audioOnly, true); + assert.equal(nullsInherit.data.convertEnabled, true); + assert.equal(nullsInherit.data.gpuAcceleration, true); + assert.deepEqual(nullsInherit.data.playlist, { mode: "all" }); + + const queuedUrl = `${MEDIA}/clip-one.mp4?resolver=queue-${Date.now()}`; + const queued = await api("addToQueue", [queuedUrl], { + ...withoutUrl(explicit), + outputPath: DOWNLOADS, + }); + assert.equal(queued.ok, true, queued.error?.message); + assert.equal(queued.data.added, 1); + const queue = await api("getQueue"); + const queuedItem = queue.find((item) => item.url === queuedUrl); + assert.ok( + queuedItem?.request, + "queue admission did not save a request snapshot", + ); + assert.deepEqual( + { ...manual.data, url: queuedUrl }, + queuedItem.request, + "queue and manual resolution produced different request options", + ); + + const profileUrl = `${MEDIA}/clip-one.mp4?resolver=profile-${Date.now()}`; + const profileOnly = { + url: profileUrl, + outputPath: DOWNLOADS, + profile: "audio", + }; + const profileManual = await api("resolveDownloadOptions", profileOnly); + assert.equal(profileManual.ok, true, profileManual.error?.message); + assert.equal(profileManual.data.audioOnly, true); + assert.equal(profileManual.data.bestQuality, false); + assert.equal(profileManual.data.advancedOptions, false); + const profileQueueUrl = `${MEDIA}/clip-one.mp4?resolver=profile-queue-${Date.now()}`; + const profileQueued = await api("addToQueue", [profileQueueUrl], { + outputPath: DOWNLOADS, + profile: "audio", + }); + assert.equal(profileQueued.ok, true, profileQueued.error?.message); + const afterProfileQueue = await api("getQueue"); + const profileItem = afterProfileQueue.find( + (item) => item.url === profileQueueUrl, + ); + assert.ok( + profileItem?.request, + "profile-only queue request was not captured", + ); + assert.deepEqual( + { ...profileManual.data, url: profileQueueUrl }, + profileItem.request, + "profile-only manual and queue resolution diverged", + ); + }); + + it("keeps an enqueue-time request on replay and returns validation envelopes", async () => { + await api("clearQueue"); + const preset = { + id: "resolver-replay", + name: "Resolver Replay", + profile: "best-video", + bestQuality: true, + audioOnly: false, + convertEnabled: false, + gpuAcceleration: false, + playlist: { mode: "current" }, + }; + const saved = await api("saveSettings", { + downloadMode: "compatible", + bestQuality: false, + audioOnly: false, + downloadPresets: [preset], + }); + assert.equal(saved.ok, true, saved.error?.message); + + const url = `${MEDIA}/missing-resolver-replay-${Date.now()}.mp4`; + const added = await api("addToQueue", [url], { + outputPath: DOWNLOADS, + presetId: preset.id, + convertEnabled: false, + }); + assert.equal(added.ok, true, added.error?.message); + const before = await api("getQueue"); + const queued = before.find((item) => item.url === url); + assert.ok(queued?.request, "queue item lacks its resolved options"); + const snapshot = queued.request; + + const changed = await api("saveSettings", { + downloadMode: "custom", + advancedOptions: true, + bestQuality: false, + audioOnly: true, + convertEnabled: true, + gpuAcceleration: true, + downloadPresets: [ + { ...preset, audioFormatId: "999", videoFormat: "888" }, + ], + }); + assert.equal(changed.ok, true, changed.error?.message); + const started = await api("startQueue"); + assert.equal(started.ok, true, started.error?.message); + await browser.waitUntil( + async () => { + const queue = await api("getQueue"); + const item = queue.find((candidate) => candidate.url === url); + return ( + item && ["completed", "failed", "cancelled"].includes(item.status) + ); + }, + { + timeout: 120_000, + interval: 500, + timeoutMsg: "queued replay did not finish", + }, + ); + const after = await api("getQueue"); + const replayed = after.find((item) => item.url === url); + assert.deepEqual( + replayed.request, + snapshot, + "queue request changed while replaying", + ); + + await browser.waitUntil( + async () => { + const activity = await api("getDownloadActivity"); + return activity.ok && activity.data.some((entry) => entry.url === url); + }, + { + timeout: 20_000, + interval: 250, + timeoutMsg: "queue replay was not recorded", + }, + ); + const activity = await api("getDownloadActivity"); + const completion = activity.data.find((entry) => entry.url === url); + assert.deepEqual( + completion.request, + snapshot, + "replayed completion used settings changed after queue admission", + ); + assert.equal( + completion.request.audioFormat ?? null, + snapshot.audioFormat ?? null, + "a later preset format ID was added to the stored snapshot", + ); + assert.equal( + completion.request.videoFormat ?? null, + snapshot.videoFormat ?? null, + "a later preset video format was added to the stored snapshot", + ); + + const wrongResolverShape = await api( + "resolveDownloadOptions", + "wrong-shape", + ); + assert.equal(wrongResolverShape.ok, false); + assert.equal(wrongResolverShape.error.code, "VALIDATION_ERROR"); + const wrongDownloadShape = await api("downloadVideo", "wrong-shape"); + assert.equal(wrongDownloadShape.ok, false); + assert.equal(wrongDownloadShape.error.code, "VALIDATION_ERROR"); + const wrongQueueShape = await api("addToQueue", "wrong-shape"); + assert.equal(wrongQueueShape.ok, false); + assert.equal(wrongQueueShape.error.code, "VALIDATION_ERROR"); + const rejectedPath = await api("resolveDownloadOptions", { + url: `${MEDIA}/clip-one.mp4`, + outputPath: "relative-output", + }); + assert.equal(rejectedPath.ok, false); + assert.equal(rejectedPath.error.code, "INVALID_PATH"); + }); +}); diff --git a/e2e/v5-fixes/download-options/failure-modes.md b/e2e/v5-fixes/download-options/failure-modes.md new file mode 100644 index 00000000..bc9b1327 --- /dev/null +++ b/e2e/v5-fixes/download-options/failure-modes.md @@ -0,0 +1,35 @@ +# Shared download option resolver failure modes + +1. **Resolution order changes.** Settings defaults must be applied first, a + selected preset second, and explicit on-screen values last. An explicit + `false` must survive every merge. +2. **Null is mistaken for an override.** `null` and omitted optional fields + remain unset so a preset/default can supply them; explicit `false` remains + a value. Hidden playlist controls omit the playlist, while a visible + `current` selection overrides a saved `all` or `range` selection. +3. **Preview and start disagree.** `resolve_download_options` and + `download_video` must return/use the same validated resolved snapshot for + the same settings and request. +4. **Manual and queue disagree.** Both paths must call the shared resolver; + equivalent settings, preset and explicit overrides produce equivalent + resolved options. +5. **Queue replay drifts.** Queue admission stores all resolved settings and + options. Starting or reloading a queued item after settings or presets + change must keep its enqueue-time request. +6. **Invalid requests bypass envelopes.** Wrong-shaped URL/options payloads, + unsafe URLs, and disallowed paths return the existing structured IPC error + envelope rather than a Tauri deserialization rejection or a started job. +7. **Validation is weakened by consolidation.** URL and output path + allow-lists, preset value validation, and lenient persisted settings/queue + imports remain in force. +8. **Queue execution semantics change.** Queue ordering, duplicate handling, + cancellation, and one-at-a-time execution remain unchanged. + +## E2E acceptance + +The native scenario resolves the same preset/overrides through manual and +queue admission, checks explicit `false`, inherited `null`, and the visible +playlist `current` override, rejects invalid payloads through the IPC +envelope, then changes settings before replaying a queued item and verifies +its completion still carries the enqueue-time snapshot. The existing E2E +runner report under `e2e/artifacts/` is the repeatable evidence. diff --git a/e2e/v5-fixes/queue-coordinator/failure-modes.md b/e2e/v5-fixes/queue-coordinator/failure-modes.md new file mode 100644 index 00000000..2a941298 --- /dev/null +++ b/e2e/v5-fixes/queue-coordinator/failure-modes.md @@ -0,0 +1,125 @@ +# Queue/session coordinator migration: failure modes + +Written before any Rust change. Current code references: `src-tauri/src/queue.rs` +(`QUEUE`, `START_GUARD`, `RUNNER_CHANGED`, `PERSIST_SIGNAL`, `run_queue`, +`stop`, `start_queue`, `cancel_queue_blocking`, `clear_queue_blocking`) and +`src-tauri/src/downloader.rs` (`ACTIVE`, `SESSION_CHANGED`, `FINALIZING`, +`FINALIZATION_CHANGED`, `STARTUP`, `EVENT_PUBLISH`, `CompletionCallback`, +`cancel_session`, `complete_session`, `start_download`, `download_video`). + +Each row names the failure, the mechanism that could cause it after the +migration, and the guard that must hold. `queue-coordinator.spec.js` covers +every row that is observable through `window.api` or the existing E2E hooks. +Internal rows are guarded by design rules and review. + +## Races between commands + +| # | Failure mode | Mechanism | Guard | +| --- | --- | --- | --- | +| 1 | Cancel lands between the runner's "still wanted" check and the session start, so the item starts after the user cancelled. | Runner claims an item, cancel arrives, start proceeds. | Coordinator orders cancel and start as commands on one queue. A start carries the item id and run generation; cancel bumps the generation, so a stale start is rejected and the item gets exactly one cancelled outcome. E2E: cancel during claim leaves the item `cancelled` with no completion event for it. | +| 2 | Start while stop is in progress replaces the runner that stop() is waiting for. | `start_queue` after `stop()` sets `stopping`. | Coordinator rejects Start while a stop is in flight with "Queue is stopping." Same status code as today. E2E: restart path after close. | +| 3 | Retry of an item still being finalized is accepted, then overwritten by the old completion. | Completion for session N arrives after retry set the item to pending. | Completion carries session id and attempt id; a completion whose attempt id is not the item's current attempt is dropped and logged. E2E: retry after cancel yields one terminal state. | +| 4 | Reorder during a running session moves the active item. | Pending-index math reads a stale snapshot. | Reorder is a coordinator command that only touches pending items. Existing "Only pending queue items can be reordered." error kept. E2E: reorder while a run is active. | +| 5 | Clear queue while running leaves a session that later records into a removed item. | Clear removes items; completion looks up by id. | Clear cancels the session first (notify), then removes items. A completion for a missing item records nothing (existing behaviour). E2E: clear during a download. | +| 6 | Remove of the downloading item races with its completion. | Remove sees a stale status. | Remove is decided from coordinator state; "Cannot remove an actively downloading item." kept. | +| 7 | Duplicate add of a URL already downloading. | Duplicate check reads state while the runner flips status. | Add is a coordinator command; the nonterminal URL set comes from coordinator state. Skipped-count semantics kept. | + +## Stale and duplicate session events + +| # | Failure mode | Mechanism | Guard | +| --- | --- | --- | --- | +| 8 | A progress line from session N is applied to session N+1. | Reader threads outlive the session that spawned them. | Every worker event carries its session id; the coordinator drops events whose id is not the active id. E2E: back-to-back queue items keep their own progress and completion. | +| 9 | Two terminal results are published for one session (cancel path and natural exit both finish it). | Cancel and exit both call completion. | The coordinator publishes a terminal result only when it moves the session out of Active; the second attempt is a no-op. E2E: cancel during post-processing yields exactly one `download-complete` per item. | +| 10 | Completion for session N clears the slot of session N+1. | Slot cleared without an id check. | Slot is cleared only when the terminal result's session id equals the active id. E2E: sequential queue of several items finishes every item. | +| 11 | Terminal result reaches the queue and the activity log through different paths and disagrees. | Two consumers of one completion. | One terminal message per session; queue apply and activity record both read that message. | + +## Orphan processes and waits + +| # | Failure mode | Mechanism | Guard | +| --- | --- | --- | --- | +| 12 | yt-dlp or ffmpeg survives cancel, stop, or close. | Child dropped without `terminate_tree`, or the coordinator publishes before the child exits. | Cancel and shutdown send Terminate to the session worker; cancel and stop publish their terminal result only after the worker acknowledges child exit. E2E: cancel leaves no child from the test profile. | +| 13 | Coordinator blocks on a child wait or disk write, freezing every command. | Waiting for exit inside the command loop. | Waits and file writes run on worker or writer threads. The coordinator only updates state and sends messages. Review rule; observable through the cancel scenario finishing within its timeout. | +| 14 | An ack never arrives, so close hangs. | Worker panics before acknowledging, or writer dies. | Every ack wait has a bounded timeout. On timeout the caller logs and takes the existing failure path. E2E: close-pending-timeout still reports the pending close. | +| 15 | Deadlock between coordinator and a caller holding a lock it needs. | Caller holds a window or settings lock while awaiting a reply. | Callers never hold a shared lock across send and recv. The coordinator never calls window, emit, or stats code while holding its own state. | + +## Persistence + +| # | Failure mode | Mechanism | Guard | +| --- | --- | --- | --- | +| 16 | Close reports success while the latest queue revision is not durable. | Writer acknowledges an older revision, or a debounced write is skipped. | Close, restart, and update request durable revision R and wait for the writer's ack for R or newer. E2E: queue-latest-snapshot. | +| 17 | Persistence failure during close is hidden, so the app exits and loses the queue. | Flush error swallowed on the shutdown path. | Both flushes in `shutdown_with_close_generation` keep their error returns; a failed flush keeps the app open. E2E: queue-flush-backup-failure and the blocked-backup close/restart scenario. | +| 18 | A failed flush blocks command processing or retries forever. | Writer retries inside the coordinator loop. | Writer is its own thread. A failed flush returns an error to the requester and state stays dirty; the existing 300 ms debounce and retry-on-next-change behaviour is kept. | +| 19 | A newer-schema queue file is overwritten by an older build. | Flush after migration skips the schema guard. | The `is_newer_schema_file` path in `queue::flush` is kept as is: it returns Ok with a warning. | +| 20 | Out-of-order writes leave an older snapshot on disk. | Two writer threads or a delayed debounced write. | A single writer owns `QueuePersistence`. The `highest_attempted` / `last_persisted` rule is kept. | +| 21 | Persisted file format changes with no migration path. | New session or attempt fields serialized into `download-queue.json`. | Persisted `QueueItem` shape is unchanged; revisions and attempt ids stay in memory. `long-term-persistence` must pass unchanged. | + +## Admission: manual versus queue + +| # | Failure mode | Mechanism | Guard | +| --- | --- | --- | --- | +| 22 | Manual download accepted while the queue runner is between items. | `download_video` checks the session slot, which is empty between items. | Coordinator admission checks both the active owner and the queue run state. `download_video` keeps "A queue download is already in progress." E2E: manual download during a queue run is refused. | +| 23 | Queue start accepted while a manual session holds the slot. | `start_queue` races a manual start. | Start command checks coordinator owner state and returns "A manual download is already in progress." | +| 24 | Queue runner stalls behind a manual download. | Old code slept 250 ms and retried. | Coordinator holds the queue start until the slot is free; the item stays pending. E2E: queue started right after a manual download completes. | +| 25 | Manual download recorded as a queue item, or the reverse. | Owner passed incorrectly. | Owner is part of the session identity and the terminal result; `download-complete` keeps its `owner` field. | + +## Restart and update during an active download + +| # | Failure mode | Mechanism | Guard | +| --- | --- | --- | --- | +| 26 | Restart during an active item leaves it cancelled instead of pending. | Stop's terminal result recorded as a user cancel. | Stop is an interruption: the item is requeued to pending as today. E2E: restart during an active item leaves it pending with a clean attempt. | +| 27 | Update install starts while a child still writes into the output folder. | Install proceeds before the exit ack. | The update path waits for the coordinator's idle-with-children-exited state, bounded by the existing timeout. | +| 28 | Window closed during a queue run. | Runner checks the main window per item. | Coordinator produces the same synthetic failed completion, "Window closed", and continues. | + +## Ordering of published snapshots + +| # | Failure mode | Mechanism | Guard | +| --- | --- | --- | --- | +| 29 | Frontend applies an older queue snapshot after a newer one. | Two emitters race. | The single coordinator publishes in revision order and each `queue-update` carries a monotonically increasing `revision`. The renderer's `queue-update` consumer (`src/engine/bind/backend-events.ts`) drops older revisions. | +| 30 | A poisoned lock makes queue events panic. | `lock().unwrap()` after a worker panic. | Poison recovery (`unwrap_or_else(|p| p.into_inner())`) on every lock the migration touches. | + +## Test strategy + +- Observable rows (1-10, 12, 16-17, 22-24, 26, 28-29) are covered by + `queue-coordinator.spec.js` through `window.api` and the existing E2E hooks. +- Internal rows (11, 13-15, 18-21, 25, 27, 30) are guarded by design rules and + review. AGENTS.md forbids writing unit tests after code, so they are exercised + through the observable scenarios above, not by isolated tests. +- Verification: targeted groups `queue`, `lifecycle`, `persistence`, + `downloads`, then one full `npm.bat run test:e2e`. + +## Stage 2: scenario map (current code) + +`queue-coordinator.spec.js` runs against the unmigrated code and must pass +there. Rows not listed here are covered by existing scenarios, not by this spec. + +| Spec scenario | Rows | +| --- | --- | +| runs queued items one at a time with exactly one outcome each | 8, 9, 10, 11 | +| skips a duplicate of a URL that is already downloading | 7 | +| refuses manual downloads and queue starts while the other owner runs | 22, 23 | +| cancels a running item, then retries it to one completed attempt | 1, 3, 9, 12 | +| rejects reorder and removal of the active item while the run continues | 4, 6 | +| clears a running queue without recording an outcome for removed items | 5, 12 | +| keeps the persisted queue equal to the live queue after a run | 16, 21 | +| publishes strictly increasing revisions and never renders a stale snapshot | 29 | + +Rows not covered by this spec: 2 (stop during start), 13-15 (internal waits and +locks), 17-20 (persistence failure paths, covered by `queue-flush-backup-failure` +and `long-term-persistence`), 24 (queue waiting behind a manual download), 25, +26 (restart during an active item, covered by `close-pending-timeout` and the +lifecycle group), 27, 28, 30. + +### Row 29 contract (status: implemented) + +- `queue-update` carries `{ revision, items }`. `revision` is assigned by the + coordinator on each commit and increases strictly. +- The renderer (`src/engine/bind/backend-events.ts`) drops a snapshot whose + revision is older than the newest one it rendered. Bare-array payloads have + no revision and are always applied. +- The startup `getQueue` read has no revision. It is applied only if no + snapshot arrived while it was in flight. A snapshot emitted before the read + but delivered after it can still be applied. That residual window is kept + because `get_queue` must remain a bare array for existing E2E specs. +- Covered by the spec scenario "publishes strictly increasing revisions and + never renders a stale snapshot", which injects a revision 0 snapshot through + the e2e-only `e2e_emit_stale_download_events` probe. diff --git a/e2e/v5-fixes/queue-coordinator/queue-coordinator.spec.js b/e2e/v5-fixes/queue-coordinator/queue-coordinator.spec.js new file mode 100644 index 00000000..b82972fe --- /dev/null +++ b/e2e/v5-fixes/queue-coordinator/queue-coordinator.spec.js @@ -0,0 +1,342 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { browser } from "@wdio/globals"; +import { api, waitForAppReady } from "../../helpers/app-bridge.js"; + +const env = process.env; +const MEDIA = env.ROSI_E2E_MEDIA_URL; +const DOWNLOADS = env.ROSI_E2E_DOWNLOADS; +const DATA_DIR = env.ROSI_E2E_DATA_DIR; +const TERMINAL = ["completed", "failed", "cancelled"]; + +function processesMatching(needle) { + const listing = + process.platform === "win32" + ? spawnSync( + "powershell.exe", + [ + "-NoProfile", + "-Command", + "Get-CimInstance Win32_Process | ForEach-Object { $_.CommandLine }", + ], + { encoding: "utf8" }, + ).stdout + : spawnSync("ps", ["-Ao", "command="], { encoding: "utf8" }).stdout; + return (listing || "") + .split("\n") + .filter((line) => line.includes(needle) && !line.includes("powershell")); +} + +async function waitForNoProcess(needle, timeoutMsg) { + await browser.waitUntil(async () => processesMatching(needle).length === 0, { + timeout: 15_000, + interval: 250, + timeoutMsg: `${timeoutMsg}: ${processesMatching(needle).join(" | ")}`, + }); +} + +async function activityFor(url) { + const activity = (await api("getDownloadActivity")).data; + return activity.filter((entry) => entry.url === url); +} + +async function waitForItemStatus(url, status, timeoutMsg, timeout = 60_000) { + await browser.waitUntil( + async () => + (await api("getQueue")).some( + (item) => item.url === url && item.status === status, + ), + { timeout, interval: 250, timeoutMsg }, + ); +} + +async function waitForAllTerminal(timeoutMsg) { + await browser.waitUntil( + async () => + (await api("getQueue")).every((item) => TERMINAL.includes(item.status)), + { timeout: 180_000, interval: 500, timeoutMsg }, + ); +} + +describe("queue and session coordinator behaviour", () => { + before(async () => { + await waitForAppReady(); + }); + + beforeEach(async () => { + await api("cancelQueue"); + await api("clearQueue"); + }); + + it("runs queued items one at a time with exactly one outcome each", async () => { + const urls = [ + `${MEDIA}/clip-two.mp4?coord=seq`, + `${MEDIA}/clip-three.mp4?coord=seq`, + `${MEDIA}/clip-one.mp4?coord=seq`, + ]; + const added = await api("addToQueue", urls); + assert.equal(added.data.added, 3); + assert.equal((await api("startQueue")).ok, true); + await waitForAllTerminal("sequential queue did not finish"); + + const queue = await api("getQueue"); + for (const item of queue) { + assert.equal(item.status, "completed", item.error ?? item.url); + } + const completedAt = []; + for (const url of urls) { + const entries = await activityFor(url); + assert.equal( + entries.length, + 1, + `${url} recorded ${entries.length} times`, + ); + assert.equal(entries[0].outcome, "success"); + completedAt.push(entries[0].completedAt); + } + assert.deepEqual( + completedAt, + [...completedAt].sort((a, b) => a - b), + "items did not finish in queue order", + ); + }); + + it("skips a duplicate of a URL that is already downloading", async () => { + const slow = `${MEDIA}/slow.mp4?coord=dup`; + assert.equal((await api("addToQueue", [slow])).data.added, 1); + assert.equal((await api("startQueue")).ok, true); + await waitForItemStatus(slow, "downloading", "item never started"); + const again = await api("addToQueue", [slow]); + assert.equal(again.data.added, 0); + assert.equal(again.data.skipped, 1); + await api("cancelQueue"); + await waitForNoProcess("coord=dup", "duplicate test process survived"); + }); + + it("refuses manual downloads and queue starts while the other owner runs", async () => { + const slow = `${MEDIA}/slow.mp4?coord=admit`; + const next = `${MEDIA}/clip-three.mp4?coord=admit`; + assert.equal((await api("addToQueue", [slow, next])).data.added, 2); + assert.equal((await api("startQueue")).ok, true); + await waitForItemStatus(slow, "downloading", "queue item never started"); + + const manual = await api("downloadVideo", { + url: `${MEDIA}/clip-one.mp4?coord=manual`, + outputPath: DOWNLOADS, + }); + assert.equal(manual.ok, false, "manual download ran during a queue run"); + assert.match( + manual.error.message, + /queue download is already in progress/i, + ); + + const restart = await api("startQueue"); + assert.equal(restart.ok, false, "second queue start was accepted"); + assert.match(restart.error.message, /already running/i); + + await api("cancelQueue"); + await waitForAllTerminal("admission queue did not settle"); + await waitForNoProcess("coord=admit", "admission test process survived"); + }); + + it("cancels a running item, retries it, and records one outcome per attempt", async () => { + const slow = `${MEDIA}/slow.mp4?coord=retry`; + assert.equal((await api("addToQueue", [slow])).data.added, 1); + assert.equal((await api("startQueue")).ok, true); + await waitForItemStatus(slow, "downloading", "queue item never started"); + await browser.pause(1000); + assert.equal((await api("cancelQueue")).ok, true); + await waitForItemStatus(slow, "cancelled", "cancel did not land"); + await waitForNoProcess("coord=retry", "cancelled yt-dlp survived"); + await browser.pause(500); + let entries = await activityFor(slow); + assert.equal(entries.length, 1, "cancelled item recorded more than once"); + assert.equal(entries[0].outcome, "cancelled"); + + const item = (await api("getQueue")).find((entry) => entry.url === slow); + assert.equal((await api("retryQueueItem", item.id)).ok, true); + assert.equal((await api("startQueue")).ok, true); + await waitForItemStatus(slow, "downloading", "retried item never started"); + await browser.pause(1000); + assert.equal((await api("cancelQueue")).ok, true); + await waitForItemStatus( + slow, + "cancelled", + "retried attempt did not cancel", + ); + await waitForNoProcess("coord=retry", "retried yt-dlp survived"); + await browser.pause(500); + entries = await activityFor(slow); + assert.equal(entries.length, 2, JSON.stringify(entries)); + assert.deepEqual( + entries.map((entry) => entry.outcome), + ["cancelled", "cancelled"], + "each attempt must record exactly one outcome", + ); + assert.equal( + (await api("getQueue")).find((entry) => entry.url === slow).status, + "cancelled", + ); + }); + + it("rejects reorder and removal of the active item while the run continues", async () => { + const slow = `${MEDIA}/slow.mp4?coord=mutate`; + const second = `${MEDIA}/clip-two.mp4?coord=mutate`; + const third = `${MEDIA}/clip-three.mp4?coord=mutate`; + assert.equal( + (await api("addToQueue", [slow, second, third])).data.added, + 3, + ); + assert.equal((await api("startQueue")).ok, true); + await waitForItemStatus(slow, "downloading", "queue item never started"); + + let queue = await api("getQueue"); + const active = queue.find((item) => item.url === slow); + const pendingLast = queue.find((item) => item.url === third); + + const moved = await api("reorderQueueItem", { + id: pendingLast.id, + direction: "up", + }); + assert.equal(moved.ok, true, moved.error?.message); + + const reorderActive = await api("reorderQueueItem", { + id: active.id, + direction: "down", + }); + assert.equal(reorderActive.ok, false, "active item was reordered"); + + const removeActive = await api("removeFromQueue", active.id); + assert.equal(removeActive.ok, false, "active item was removed"); + assert.match(removeActive.error.message, /actively downloading/i); + + await api("cancelQueue"); + await waitForAllTerminal("mutation queue did not settle"); + await waitForNoProcess("coord=mutate", "mutation test process survived"); + queue = await api("getQueue"); + assert.equal( + queue.filter((item) => item.url === second).length, + 1, + "pending item was lost", + ); + }); + + it("clears a running queue without recording an outcome for removed items", async () => { + const slow = `${MEDIA}/slow.mp4?coord=clear`; + const next = `${MEDIA}/clip-three.mp4?coord=clear`; + assert.equal((await api("addToQueue", [slow, next])).data.added, 2); + assert.equal((await api("startQueue")).ok, true); + await waitForItemStatus(slow, "downloading", "queue item never started"); + await browser.pause(1000); + assert.equal((await api("clearQueue")).ok, true); + assert.deepEqual(await api("getQueue"), []); + await waitForNoProcess("coord=clear", "cleared queue yt-dlp survived"); + await browser.pause(1000); + const slowEntries = await activityFor(slow); + assert.equal(slowEntries.length, 1, "running item recorded more than once"); + assert.equal(slowEntries[0].outcome, "cancelled"); + assert.equal( + (await activityFor(next)).length, + 0, + "removed item was recorded", + ); + }); + + it("keeps the persisted queue equal to the live queue after a run", async () => { + const urls = [ + `${MEDIA}/clip-two.mp4?coord=persist`, + `${MEDIA}/clip-one.mp4?coord=persist`, + ]; + assert.equal((await api("addToQueue", urls)).data.added, 2); + assert.equal((await api("startQueue")).ok, true); + await waitForAllTerminal("persisted run did not finish"); + const live = (await api("getQueue")).map((item) => [item.url, item.status]); + const queuePath = path.join(DATA_DIR, "download-queue.json"); + await browser.waitUntil( + () => { + if (!fs.existsSync(queuePath)) return false; + const raw = JSON.parse(fs.readFileSync(queuePath, "utf8")); + const list = Array.isArray(raw) ? raw : (raw.items ?? raw.queue ?? []); + const onDisk = list.map((item) => [item.url, item.status]); + return JSON.stringify(onDisk) === JSON.stringify(live); + }, + { + timeout: 15_000, + interval: 250, + timeoutMsg: "persisted queue lags the live queue", + }, + ); + }); + + it("publishes strictly increasing revisions and never renders a stale snapshot", async () => { + // Records every revision the renderer's queue-update listener receives. + await browser.execute(() => { + window.__rosiQueueRevisions = []; + window.__rosiQueueUnsubscribe = window.api.onQueueUpdate((snapshot) => { + window.__rosiQueueRevisions.push(snapshot.revision); + }); + }); + try { + const urls = [ + `${MEDIA}/clip-two.mp4?coord=revision`, + `${MEDIA}/clip-one.mp4?coord=revision`, + ]; + assert.equal((await api("addToQueue", urls)).data.added, 2); + assert.equal((await api("startQueue")).ok, true); + await waitForAllTerminal("revision run did not finish"); + + const revisions = await browser.execute(() => + window.__rosiQueueRevisions.slice(), + ); + assert.ok( + revisions.length >= 3, + `expected several snapshots, received ${revisions.length}`, + ); + for (let index = 1; index < revisions.length; index += 1) { + assert.ok( + revisions[index] > revisions[index - 1], + `revision ${revisions[index]} did not follow ${revisions[index - 1]}`, + ); + } + + const rowCount = () => + browser.execute( + () => document.querySelectorAll("#queueList .queue-item").length, + ); + const rendered = await rowCount(); + assert.equal(rendered, 2, "the finished run did not render both rows"); + + // Revision 0 is older than every snapshot the coordinator publishes. The + // probe sends it as a real queue-update with an empty queue. + await browser.execute(() => + window.__TAURI__.core.invoke("e2e_emit_stale_download_events", { + currentSessionId: 2, + staleQueueSnapshot: true, + }), + ); + await browser.waitUntil( + () => browser.execute(() => window.__rosiQueueRevisions.includes(0)), + { + timeout: 10_000, + interval: 250, + timeoutMsg: "the stale snapshot never reached the renderer", + }, + ); + await browser.pause(1000); + assert.equal( + await rowCount(), + rendered, + "a stale queue snapshot replaced the rendered queue", + ); + assert.equal((await api("getQueue")).length, 2); + } finally { + await browser.execute(() => { + window.__rosiQueueUnsubscribe?.(); + delete window.__rosiQueueUnsubscribe; + delete window.__rosiQueueRevisions; + }); + } + }); +}); diff --git a/e2e/v5-fixes/typed-formats/failure-modes.md b/e2e/v5-fixes/typed-formats/failure-modes.md new file mode 100644 index 00000000..a771648f --- /dev/null +++ b/e2e/v5-fixes/typed-formats/failure-modes.md @@ -0,0 +1,50 @@ +# Typed format discovery failure modes + +1. **Invalid or unsafe URL accepted.** Format discovery must keep the existing + safe HTTP URL validation and network-security guard before yt-dlp runs. +2. **Unbounded process or output.** Format discovery must keep its tracked + process slot, timeout, bounded stdout/stderr capture, and cancellation path. +3. **Superseded lookup returns late.** A reply for an old URL or cancelled + request must not repopulate either picker or restore format selections. +4. **Malformed or incomplete JSON treated as success.** Missing, invalid, or + truncated structured metadata must surface as a failed lookup, never as a + valid empty list. +5. **Wrong stream classification.** Audio-only, video-only, and combined + audio/video formats must be classified from codec metadata, including codec + values represented by `none`; when both codec fields are missing, known + audio/video containers retain the existing combined-format fallback. + Non-media and storyboard entries must not be selectable. +6. **Format ID changed or guessed.** The renderer must submit the exact ID from + the structured entry when it matches the downloader's existing accepted + format-ID syntax, and must not parse IDs from display text. +7. **Optional metadata crashes or lies.** Missing codecs, resolution, fps, or + both size fields must remain representable; an approximate size must be + marked approximate rather than presented as exact. +8. **UI has no terminal state.** Loading must end on cancellation, empty + results, and errors; empty or failed results must clear selectable values + and invalidate URL-bound selections. +9. **Legacy completion text overrides structured completion.** Manual download + outcomes must continue to be driven by session-matched structured + `download-complete` events, while the legacy text event remains available + for diagnostic output. +10. **Playlist wrapper hides the selected video's formats.** Format lookup on a + URL with a playlist wrapper must stay scoped to the current video with + `--no-playlist`. If yt-dlp still returns playlist-only metadata, fail with + an actionable request for a specific video URL; never enumerate an + unbounded playlist to find formats. +11. **Explicit no-codec metadata is mistaken for absent metadata.** An + extension-based combined-stream fallback may cover missing codec fields, + but `vcodec: "none"` and `acodec: "none"` explicitly describe a non-media + entry and must be omitted. +12. **Unused progress text parser becomes a second authority.** The renderer's + `parseYtdlpProgress` helper has no production call sites; remove it and its + dedicated tests while keeping progress strings in the diagnostic console. + +## E2E acceptance + +Use the native E2E media server and app bridge to verify structured IDs and +metadata reach both picker controls, a local manifest carrying a playlist-like +query stays usable as one current video, cancellation and URL changes retire +stale results, and a failed/empty response leaves no usable stale selections. +The existing E2E runner writes the repeatable report and app/source hashes +under `e2e/artifacts/`. diff --git a/e2e/v5-fixes/typed-formats/typed-formats.spec.js b/e2e/v5-fixes/typed-formats/typed-formats.spec.js new file mode 100644 index 00000000..beb477a1 --- /dev/null +++ b/e2e/v5-fixes/typed-formats/typed-formats.spec.js @@ -0,0 +1,239 @@ +import assert from "node:assert/strict"; +import { browser } from "@wdio/globals"; +import { api, waitForAppReady } from "../../helpers/app-bridge.js"; + +const MEDIA = process.env.ROSI_E2E_MEDIA_URL; +const HAS_FFMPEG = process.env.ROSI_E2E_HAS_FFMPEG === "1"; + +async function setUrlAndFetch(url) { + await browser.execute((value) => { + const input = document.getElementById("url"); + input.value = value; + input.dispatchEvent(new Event("input", { bubbles: true })); + document.getElementById("fetchFormatsBtn").click(); + }, url); +} + +async function readFormatPickers() { + return browser.execute(() => { + const read = (id) => { + const select = document.getElementById(id); + return [...select.options].map((option) => ({ + value: option.value, + text: option.textContent, + })); + }; + return { + video: read("videoFormat"), + audio: read("audioFormat"), + }; + }); +} + +describe("typed format discovery", () => { + before(async () => { + await waitForAppReady(); + }); + + after(async () => { + await browser.execute(() => { + const original = window.__typedFormatsOriginalApi; + if (!original) return; + window.api.getFormats = original.getFormats; + window.api.cancelFormats = original.cancelFormats; + delete window.__typedFormatsOriginalApi; + delete window.__typedFormatsPending; + }); + }); + + it("returns typed entries and renders their exact IDs in the matching picker", async () => { + const url = HAS_FFMPEG + ? `${MEDIA}/dash/manifest.mpd` + : `${MEDIA}/clip-one.mp4`; + const result = await api("getFormats", url); + assert.equal(result.ok, true, result.error?.message); + assert.ok(Array.isArray(result.data.formats)); + assert.ok( + result.data.formats.length > 0, + "yt-dlp returned no media formats", + ); + assert.ok( + result.data.formats.every( + (format) => + typeof format.formatId === "string" && + ["audio", "video", "audioVideo"].includes(format.streamKind), + ), + JSON.stringify(result.data.formats), + ); + + const wrappedUrl = HAS_FFMPEG + ? `${MEDIA}/dash/manifest.mpd?list=local-wrapper` + : `${MEDIA}/clip-one.mp4?list=local-wrapper`; + const wrapped = await api("getFormats", wrappedUrl); + assert.equal(wrapped.ok, true, wrapped.error?.message); + assert.ok(Array.isArray(wrapped.data.formats)); + if (HAS_FFMPEG) { + assert.ok( + wrapped.data.formats.length > 0, + "playlist-like URL did not return the current manifest's formats", + ); + } + + await setUrlAndFetch(url); + await browser.waitUntil( + async () => + browser.execute( + () => + !document + .getElementById("fetchFormatsBtn") + .classList.contains("loading"), + ), + { timeout: 60_000, timeoutMsg: "format picker did not finish loading" }, + ); + const pickers = await readFormatPickers(); + for (const format of result.data.formats) { + const expectedPicker = + format.streamKind === "audio" ? pickers.audio : pickers.video; + assert.ok( + expectedPicker.some((option) => option.value === format.formatId), + `format ${format.formatId} was not rendered as an exact option value`, + ); + } + }); + + it("clears cancelled and stale replies before they can restore selections", async () => { + await browser.execute(() => { + window.__typedFormatsOriginalApi = { + getFormats: window.api.getFormats, + cancelFormats: window.api.cancelFormats, + }; + window.__typedFormatsPending = []; + window.api.getFormats = () => + new Promise((resolve) => window.__typedFormatsPending.push(resolve)); + }); + + await setUrlAndFetch(`${MEDIA}/clip-one.mp4`); + await browser.waitUntil( + async () => + browser.execute(() => window.__typedFormatsPending?.length === 1), + { + timeout: 10_000, + timeoutMsg: "controlled format request did not start", + }, + ); + await browser.execute(() => + document.getElementById("fetchFormatsBtn").click(), + ); + await browser.execute(() => + window.__typedFormatsPending[0]({ + ok: true, + data: { + formats: [ + { + formatId: "stale-cancelled", + streamKind: "video", + vcodec: "avc1", + }, + ], + }, + }), + ); + await browser.waitUntil( + async () => + browser.execute(() => + [...document.getElementById("videoFormat").options].every( + (option) => option.value !== "stale-cancelled", + ), + ), + { + timeout: 10_000, + timeoutMsg: "cancelled reply restored a format option", + }, + ); + + await setUrlAndFetch(`${MEDIA}/clip-one.mp4`); + await browser.waitUntil( + async () => + browser.execute(() => window.__typedFormatsPending?.length === 2), + { + timeout: 10_000, + timeoutMsg: "second controlled format request did not start", + }, + ); + await browser.execute((value) => { + const input = document.getElementById("url"); + input.value = value; + input.dispatchEvent(new Event("input", { bubbles: true })); + }, `${MEDIA}/clip-two.mp4`); + await browser.execute(() => + window.__typedFormatsPending[1]({ + ok: true, + data: { + formats: [ + { formatId: "stale-url", streamKind: "audio", acodec: "mp4a" }, + ], + }, + }), + ); + await browser.waitUntil( + async () => + browser.execute(() => + [...document.getElementById("audioFormat").options].every( + (option) => option.value !== "stale-url", + ), + ), + { + timeout: 10_000, + timeoutMsg: "stale URL reply restored a format option", + }, + ); + const pickers = await readFormatPickers(); + assert.ok( + [...pickers.video, ...pickers.audio].every((option) => !option.value), + ); + }); + + it("shows explicit empty and failure states without usable selections", async () => { + await browser.execute(() => { + window.api.getFormats = async () => ({ ok: true, data: { formats: [] } }); + }); + await setUrlAndFetch(`${MEDIA}/clip-one.mp4`); + await browser.waitUntil( + async () => + browser.execute( + () => + !document + .getElementById("fetchFormatsBtn") + .classList.contains("loading"), + ), + { timeout: 10_000, timeoutMsg: "empty format lookup did not finish" }, + ); + let pickers = await readFormatPickers(); + assert.equal(pickers.video[0].text, "No video formats found"); + assert.equal(pickers.audio[0].text, "No audio formats found"); + + await browser.execute(() => { + window.api.getFormats = async () => ({ + ok: false, + error: { code: "INTERNAL_ERROR", message: "fixture failure" }, + }); + }); + await setUrlAndFetch(`${MEDIA}/clip-one.mp4`); + await browser.waitUntil( + async () => + browser.execute( + () => + !document + .getElementById("fetchFormatsBtn") + .classList.contains("loading"), + ), + { timeout: 10_000, timeoutMsg: "failed format lookup did not finish" }, + ); + pickers = await readFormatPickers(); + assert.equal(pickers.video[0].text, "Error loading formats"); + assert.equal(pickers.audio[0].text, "Error loading formats"); + assert.ok( + [...pickers.video, ...pickers.audio].every((option) => !option.value), + ); + }); +}); diff --git a/e2e/v5-fixes/ui-polish/failure-modes.md b/e2e/v5-fixes/ui-polish/failure-modes.md new file mode 100644 index 00000000..2f52f0a4 --- /dev/null +++ b/e2e/v5-fixes/ui-polish/failure-modes.md @@ -0,0 +1,96 @@ +# UI polish failure modes + +This inventory is written before UI behavior changes. E2E acceptance should drive +the real renderer and native bridge, and leave a JSON report plus screenshots +whose source revision, dirty-file hashes, platform, and E2E binary hash are +recorded. A static renderer helper passing is not full-app acceptance. + +## Effective options and readiness + +1. **Summary disagrees with the selected profile.** Changing compatible, best + video, audio format, custom formats, or a saved preset can leave the summary + stale. Keep `#downloadOutputSummary` synchronized with visible controls. +2. **Profile summary is mistaken for resolved backend options.** A renderer + estimate cannot account for format availability, backend defaults, or + normalization. Label it as a profile preview until an API returns resolved + options; never imply it is the final command/options. +3. **Failed or delayed option resolution leaves old content visible.** A prior + request can finish after the URL or profile changes. Surface unavailable or + pending state and ignore stale responses. +4. **Invalid input has no actionable inline feedback.** Invalid URL, unsupported + custom format, and invalid subtitle language input must identify the field, + explain correction, expose `aria-invalid`/descriptions, and keep focus on + the failing control when submission is blocked. +5. **Readiness appears successful when prerequisites fail.** Missing runtime, + unavailable destination, or failed format lookup must not look like a + ready-to-download state. Keep the reason and next action visible. + +## Progress, outcomes, and queue + +6. **A terminal failure looks like successful completion.** Exercise complete, + failed, cancelled, and partial playlist success separately, including + conversion failure after a source file was retained. +7. **Saved outputs have no usable action.** For one and multiple output paths, + expose the right open/reveal action and report bridge failures without + silently claiming success. +8. **Activity re-render loses the user's place.** Filters, new entries, and + action completion must retain sensible keyboard focus and announce material + updates without announcing every progress tick. +9. **Queue state/action mismatch.** Pending, downloading, completed, failed, + and cancelled rows must present only valid actions; retry/requeue, remove, + reorder, and open-location errors must restore controls and explain failure. +10. **Queue refresh drops focus or context.** After progress snapshots or action + results replace rows, preserve focus by queue item/action identity when it + still exists and explain why disabled actions cannot run. +11. **Long paths and source URLs break the layout.** Very long filesystem paths, + URLs, titles, error messages, and multiple outputs must wrap or truncate + without covering actions or expanding past the viewport. + +## Settings and onboarding + +12. **Settings save failure looks saved.** Rejected or thrown saves must retain + the current values, show retryable feedback, and avoid false success; a + successful retry must clear the failure state. +13. **Section reset changes values before confirmation.** Cancel leaves values + untouched; confirm resets only that section; a save failure reports the + failure and keeps a retry path. +14. **Dependent controls are silently disabled.** Disabled options (for + example conversion under audio-only) explain the dependency in text that is + available to keyboard and assistive-technology users. +15. **Folder selection is cancelled or fails during setup.** Preserve the + existing destination, do not show a stale chosen path, and explain when + asking for a destination before each download is selected. +16. **Deno check or install fails, or setup is skipped.** Distinguish checking, + installed, unavailable, cancelled, and failed states; offer the right + install instructions/action; do not imply setup persisted when the save + failed; Skip must reset exactly its documented wizard settings. +17. **Modal/wizard exit loses keyboard control.** Escape confirmation, cancel, + save failure, and completion must keep focus trapped while open and restore + focus to the invoking control on close. + +## Viewport, theme, and accessibility matrix + +18. **Small window clips controls.** Exercise every theme at 900x560 and + 1200x900 with increased text scale; settings, queue actions, dialogs, and + wizard navigation must remain reachable without horizontal overflow. +19. **Theme or reduced-motion state lowers contrast or motion access.** Check + system, light, dark, and purple themes with keyboard focus, status/error + states, and `prefers-reduced-motion`; reduced motion must suppress + nonessential transitions while preserving state changes. +20. **Keyboard and screen-reader semantics regress.** Tab/Shift+Tab, Escape, + modal focus return, settings search/reset, wizard navigation, live status, + progress names/values, and action labels must remain operable and + understandable without a pointer. + +## E2E evidence requirements + +- Keep existing suite ownership and platform skip allowances. Add a + `ui-polish` feature group to `e2e/suites.json` without moving current specs. +- The UI group is targeted evidence (`fullSuite: false`); it cannot satisfy + release proof. Full release evidence still requires the canonical complete + suite and its fresh binary/report hashes. +- Capture screenshots for each required viewport/theme combination and a + machine-readable report with per-scenario outcomes. Distinguish discovered + cases from executed results and include failures rather than dropping them. +- Record source identity including dirty-file hashes as well as `HEAD`, the + platform, runner/tool versions, and the exact tested binary hash. diff --git a/e2e/v5-fixes/ui-polish/ui-polish.spec.js b/e2e/v5-fixes/ui-polish/ui-polish.spec.js new file mode 100644 index 00000000..35c0777f --- /dev/null +++ b/e2e/v5-fixes/ui-polish/ui-polish.spec.js @@ -0,0 +1,798 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { browser } from "@wdio/globals"; +import { api, waitForAppReady } from "../../helpers/app-bridge.js"; +import { e2eBinaryPath, REPO_ROOT } from "../../helpers/profile.js"; + +const stamp = new Date() + .toISOString() + .replaceAll(":", "-") + .replaceAll(".", "-"); +const artifactDir = path.join( + REPO_ROOT, + "e2e", + "artifacts", + "v5-fixes-ui-polish", + `${stamp}-${process.pid}`, +); +const screenshotDir = path.join(artifactDir, "screenshots"); +const reportPath = path.join(artifactDir, "report.json"); +const report = { + suite: "v5-fixes-ui-polish", + startedAt: new Date().toISOString(), + platform: process.platform, + arch: process.arch, + runtime: { node: process.version }, + source: null, + binary: null, + checks: [], + screenshots: [], +}; + +const sha256 = (value) => + crypto.createHash("sha256").update(value).digest("hex"); + +function sourceIdentity() { + const head = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: REPO_ROOT, + encoding: "utf8", + }).trim(); + const trackedChanges = execFileSync( + "git", + ["diff", "HEAD", "--name-only", "-z"], + { + cwd: REPO_ROOT, + encoding: "buffer", + }, + ) + .toString() + .split("\0") + .filter(Boolean); + const untracked = execFileSync( + "git", + ["ls-files", "--others", "--exclude-standard", "-z"], + { cwd: REPO_ROOT, encoding: "buffer" }, + ) + .toString() + .split("\0") + .filter(Boolean); + const dirtyFiles = [...new Set([...trackedChanges, ...untracked])] + .sort() + .map((relativePath) => { + const filePath = path.join(REPO_ROOT, relativePath); + return { + path: relativePath.replaceAll(path.sep, "/"), + sha256: + fs.existsSync(filePath) && fs.statSync(filePath).isFile() + ? sha256(fs.readFileSync(filePath)) + : null, + }; + }); + const dirtyFingerprint = dirtyFiles + .map((file) => `${file.path}\0${file.sha256 ?? "deleted"}`) + .join("\n"); + return { + head, + workingTree: dirtyFiles.length === 0 ? "clean" : "dirty", + dirtyFiles, + dirtyFingerprintSha256: sha256(dirtyFingerprint), + }; +} + +function writeReport() { + fs.mkdirSync(screenshotDir, { recursive: true }); + const contents = `${JSON.stringify(report, null, 2)}\n`; + const temporaryPath = `${reportPath}.tmp`; + fs.writeFileSync(temporaryPath, contents); + fs.renameSync(temporaryPath, reportPath); + fs.writeFileSync( + `${reportPath}.sha256`, + `${sha256(contents)} report.json\n`, + ); +} + +async function scenario(name, body) { + try { + const details = await body(); + report.checks.push({ name, status: "passed", ...details }); + writeReport(); + } catch (error) { + report.checks.push({ + name, + status: "failed", + reason: error instanceof Error ? error.message : String(error), + }); + writeReport(); + throw error; + } +} + +async function clickById(id) { + await browser.execute((target) => { + const element = document.getElementById(target); + if (!element) throw new Error(`missing element ${target}`); + element.click(); + }, id); +} + +async function setControl(id, value) { + await browser.execute( + (target, next) => { + const control = document.getElementById(target); + if (!control) throw new Error(`missing control ${target}`); + if (control.type === "checkbox") control.checked = Boolean(next); + else control.value = String(next); + control.dispatchEvent(new Event("change", { bubbles: true })); + }, + id, + value, + ); +} + +async function waitFor( + predicate, + message, + timeout = 10_000, + argument = undefined, +) { + await browser.waitUntil(async () => browser.execute(predicate, argument), { + timeout, + interval: 100, + timeoutMsg: message, + }); +} + +async function waitForModal(open) { + await waitFor( + (want) => + document.getElementById("app-modal")?.classList.contains("active") === + want, + `modal did not ${open ? "open" : "close"}`, + 5_000, + open, + ); +} + +async function clickModalButton(label) { + await browser.execute((wantedLabel) => { + const button = [...document.querySelectorAll("#modal-buttons button")].find( + (candidate) => candidate.textContent.trim() === wantedLabel, + ); + if (!button) throw new Error(`missing modal action ${wantedLabel}`); + button.click(); + }, label); +} + +// The WebDriver plugin dispatches keys as synthetic KeyboardEvents, which do not +// run a button's native Enter activation. When Enter did not open the prompt, +// activate the focused control the way the browser would. Assertions still +// check that the prompt opens and that focus returns to the control. +async function pressEnterOnFocusedControl() { + await browser.keys("Enter"); + await browser.execute(() => { + const focused = document.activeElement; + const modalOpen = document + .getElementById("app-modal") + ?.classList.contains("active"); + if (!modalOpen && focused instanceof HTMLButtonElement) focused.click(); + }); +} + +async function setSidebarOpen(open) { + const isOpen = await browser.execute( + () => + document.getElementById("sidebar")?.classList.contains("open") === true, + ); + if (isOpen === open) return; + await clickById(open ? "settingsBtn" : "closeSidebar"); + await waitFor( + (want) => + document.getElementById("sidebar")?.classList.contains("open") === want, + `settings did not ${open ? "open" : "close"}`, + 10_000, + open, + ); +} + +async function setProfile(mode) { + const id = { + compatible: "profileCompatibleBtn", + "best-video": "profileBestVideoBtn", + audio: "profileAudioBtn", + custom: "profileCustomBtn", + }[mode]; + await clickById(id); + await waitFor( + (target) => + document.getElementById(target)?.getAttribute("aria-pressed") === "true", + `${mode} profile was not selected`, + 5_000, + id, + ); +} + +async function captureViewport(theme, width, height, increasedText) { + await browser.setWindowSize(width, height); + await setSidebarOpen(true); + await setControl("themeSelect", theme); + await setSidebarOpen(false); + await browser.execute((increased) => { + document.documentElement.style.fontSize = increased ? "125%" : ""; + document.documentElement.dataset.reducedMotionProbe = "true"; + }, increasedText); + await browser.pause(250); + const actual = await browser.execute(() => ({ + width: window.innerWidth, + height: window.innerHeight, + rootFontSize: getComputedStyle(document.documentElement).fontSize, + horizontalOverflow: + document.documentElement.scrollWidth > window.innerWidth, + focusable: [ + ...document.querySelectorAll("button, input, select, textarea, a[href]"), + ].filter((element) => element.offsetParent !== null && !element.disabled) + .length, + })); + assert.ok(actual.width >= 840, `window too narrow at ${actual.width}px`); + assert.ok(actual.height >= 500, `window too short at ${actual.height}px`); + assert.equal( + actual.horizontalOverflow, + false, + "page has horizontal overflow", + ); + const name = `${theme}-${width}x${height}${increasedText ? "-text-125" : ""}.png`; + const destination = path.join(screenshotDir, name); + await browser.saveScreenshot(destination); + report.screenshots.push({ + path: path.relative(artifactDir, destination).replaceAll(path.sep, "/"), + sha256: sha256(fs.readFileSync(destination)), + width: actual.width, + height: actual.height, + theme, + increasedText, + }); + return actual; +} + +describe("ROSI full-app UI polish", () => { + before(async () => { + fs.mkdirSync(screenshotDir, { recursive: true }); + await waitForAppReady(); + report.source = sourceIdentity(); + const binaryPath = e2eBinaryPath(); + report.binary = { + path: path.relative(REPO_ROOT, binaryPath).replaceAll(path.sep, "/"), + sha256: fs.existsSync(binaryPath) + ? sha256(fs.readFileSync(binaryPath)) + : null, + mtime: fs.existsSync(binaryPath) + ? fs.statSync(binaryPath).mtime.toISOString() + : null, + }; + assert.ok(report.binary.sha256, "fresh E2E binary is missing"); + writeReport(); + }); + + after(() => { + report.completedAt = new Date().toISOString(); + report.passed = report.checks.filter( + (check) => check.status === "passed", + ).length; + report.failed = report.checks.filter( + (check) => check.status === "failed", + ).length; + report.result = + report.failed === 0 && report.checks.length > 0 ? "passed" : "failed"; + writeReport(); + }); + + it("resolves and announces the effective request summary", async () => + scenario("effective-options-summary", async () => { + const before = await browser.execute(() => ({ + state: + document.getElementById("downloadOutputSummary")?.dataset.state ?? + null, + text: + document + .getElementById("downloadOutputSummary") + ?.textContent.trim() ?? "", + role: + document + .getElementById("downloadOutputSummary") + ?.getAttribute("role") ?? null, + })); + assert.equal( + before.state, + "profile-preview", + "summary must not claim resolution without a URL", + ); + assert.equal( + before.role, + "status", + "summary is not announced as a status", + ); + + await setProfile("audio"); + await setControl("profileAudioFormatSelect", "flac"); + const summaryBeforeUrl = await browser.execute(() => ({ + state: document.getElementById("downloadOutputSummary")?.dataset.state, + text: document + .getElementById("downloadOutputSummary") + ?.textContent.trim(), + })); + assert.equal(summaryBeforeUrl.state, "profile-preview"); + assert.match(summaryBeforeUrl.text, /audio|flac/i); + + await browser.execute(() => { + const url = document.getElementById("url"); + url.value = "https://www.youtube.com/watch?v=rosi-ui-polish"; + url.dispatchEvent(new Event("input", { bubbles: true })); + }); + await waitFor( + () => + document.getElementById("downloadOutputSummary")?.dataset.state === + "resolved", + "effective options were not resolved for a valid URL", + ); + const resolved = await browser.execute(() => ({ + text: document + .getElementById("downloadOutputSummary") + .textContent.trim(), + profile: document.getElementById("downloadOutputSummary").dataset + .profile, + })); + assert.equal(resolved.profile, "audio"); + assert.match(resolved.text, /audio|flac/i); + return { initialState: before.state, resolvedProfile: resolved.profile }; + })); + + it("keeps invalid input inline and associated with its field", async () => + scenario("inline-readiness-validation", async () => { + await browser.execute(() => { + const input = document.getElementById("url"); + input.value = "not a URL"; + input.dispatchEvent(new Event("input", { bubbles: true })); + input.dispatchEvent(new Event("blur", { bubbles: true })); + }); + const result = await browser.execute(() => ({ + invalid: document.getElementById("url").getAttribute("aria-invalid"), + message: document + .getElementById("urlValidationMessage") + .textContent.trim(), + describedBy: document + .getElementById("url") + .getAttribute("aria-describedby"), + summaryState: document.getElementById("downloadOutputSummary").dataset + .state, + })); + assert.equal(result.invalid, "true"); + assert.ok( + result.message.length > 0, + "invalid URL has no correction hint", + ); + assert.match(result.describedBy ?? "", /urlValidationMessage/); + assert.notEqual( + result.summaryState, + "resolved", + "invalid input kept stale resolved options", + ); + return { field: "url", summaryState: result.summaryState }; + })); + + it("confirms per-section reset and restores focus after closing", async () => + scenario("settings-section-reset-confirmation", async () => { + const defaultsResult = await api("getDefaultSettings"); + assert.equal(defaultsResult.ok, true); + const defaults = defaultsResult.data; + await setSidebarOpen(true); + const convertToggle = await browser.execute( + () => document.getElementById("convertToggle").checked, + ); + const changed = !defaults.convertEnabled; + if (convertToggle !== changed) await setControl("convertToggle", changed); + await waitFor( + (expected) => + document.getElementById("convertToggle").checked === expected, + "conversion toggle did not change", + 10_000, + changed, + ); + await clickById("closeSidebar"); + await waitFor( + () => !document.getElementById("sidebar").classList.contains("open"), + "settings did not close", + ); + // The reset control lives in the settings sidebar, so reopen it the way a + // user would before opening the prompt; focus can only return to a control + // that is visible. + await setSidebarOpen(true); + await browser.execute(() => { + document.querySelector('[data-reset-section="download"]').click(); + }); + await waitForModal(true); + const modal = await browser.execute(() => ({ + title: document.getElementById("modal-title").textContent.trim(), + focusedInside: document + .getElementById("app-modal") + .contains(document.activeElement), + text: document.getElementById("modal-message").textContent.trim(), + })); + assert.match(modal.title, /reset/i); + assert.equal(modal.focusedInside, true); + assert.match(modal.text, /conversion/i); + await clickModalButton("Cancel"); + await waitForModal(false); + assert.equal( + await browser.execute( + () => document.getElementById("convertToggle").checked, + ), + changed, + "cancelled reset changed the setting", + ); + const focusReturned = await browser.execute( + () => + document.activeElement === + document.querySelector('[data-reset-section="download"]'), + ); + assert.equal( + focusReturned, + true, + "closing reset prompt did not restore focus", + ); + + await browser.execute(() => { + document.querySelector('[data-reset-section="download"]').click(); + }); + await waitForModal(true); + await clickModalButton("Reset section"); + await waitForModal(false); + await waitFor( + (expected) => + document.getElementById("convertToggle").checked === expected, + "confirmed section reset did not restore defaults", + 10_000, + defaults.convertEnabled, + ); + return { defaultConvertEnabled: defaults.convertEnabled }; + })); + + it("runs the reset prompt keyboard-only and restores focus on Escape", async () => + scenario("keyboard-reset-escape-focus", async () => { + await setSidebarOpen(true); + const resetButtonSelector = '[data-reset-section="download"]'; + const before = await browser.execute( + () => document.getElementById("convertToggle").checked, + ); + await browser.execute((selector) => { + const button = document.querySelector(selector); + if (!button) throw new Error(`missing ${selector}`); + button.focus(); + }, resetButtonSelector); + const reachable = await browser.execute( + (selector) => + document.activeElement === document.querySelector(selector), + resetButtonSelector, + ); + assert.equal(reachable, true, "reset button is not keyboard focusable"); + await pressEnterOnFocusedControl(); + await waitForModal(true); + for (let press = 0; press < 3; press += 1) await browser.keys("Tab"); + const trapped = await browser.execute(() => + document.getElementById("app-modal").contains(document.activeElement), + ); + assert.equal(trapped, true, "Tab moved focus out of the reset prompt"); + await browser.keys("Escape"); + await waitForModal(false); + const restored = await browser.execute( + (selector) => + document.activeElement === document.querySelector(selector), + resetButtonSelector, + ); + assert.equal( + restored, + true, + "Escape did not restore focus to the reset button", + ); + const after = await browser.execute( + () => document.getElementById("convertToggle").checked, + ); + assert.equal(after, before, "Escape changed the setting"); + return { trapped, restored }; + })); + + it("shows settings save failure and supports a successful retry", async () => + scenario("settings-save-retry", async () => { + await setSidebarOpen(true); + const state = await browser.execute(() => { + window.__uiPolishSaveCalls = 0; + window.__uiPolishOriginalSaveSettings = window.api.saveSettings; + window.api.saveSettings = async (settings) => { + window.__uiPolishSaveCalls += 1; + if (window.__uiPolishSaveCalls === 1) { + return { + ok: false, + error: { + code: "INTERNAL_ERROR", + message: "Temporary settings write failure", + }, + }; + } + return window.__uiPolishOriginalSaveSettings(settings); + }; + return document.getElementById("notificationsToggle").checked; + }); + await setControl("notificationsToggle", !state); + await waitFor( + () => + document.getElementById("settingsSaveFeedback")?.dataset.state === + "error", + "settings save failure was not shown inline", + 8_000, + ); + const failedState = await browser.execute(() => ({ + text: document + .getElementById("settingsSaveFeedback") + .textContent.trim(), + retryVisible: !document.getElementById("retrySettingsSave").hidden, + valueRetained: document.getElementById("notificationsToggle").checked, + })); + assert.match(failedState.text, /did not save|save failed/i); + assert.equal(failedState.retryVisible, true); + assert.equal(failedState.valueRetained, !state); + await clickById("retrySettingsSave"); + await waitFor( + () => + document.getElementById("settingsSaveFeedback")?.dataset.state === + "saved", + "retry did not report saved settings", + 8_000, + ); + const saved = await api("getSettings"); + assert.equal(saved.notifications, !state); + const calls = await browser.execute(() => window.__uiPolishSaveCalls); + await browser.execute(() => { + window.api.saveSettings = window.__uiPolishOriginalSaveSettings; + delete window.__uiPolishOriginalSaveSettings; + }); + return { saveCalls: calls, notifications: saved.notifications }; + })); + + it("explains dependent controls and preserves queue focus on refresh", async () => + scenario("dependent-controls-and-queue-focus", async () => { + // The queue is in the main dock, which is inert while the settings sidebar + // is open, so focus can only be placed on it with the sidebar closed. + await setSidebarOpen(false); + await setProfile("audio"); + const explanation = await browser.execute(() => ({ + disabled: document.getElementById("convertToggle").disabled, + describedBy: document + .getElementById("convertToggle") + .getAttribute("aria-describedby"), + text: + document.getElementById("convertDisabledHint")?.textContent.trim() ?? + "", + })); + assert.equal(explanation.disabled, true); + assert.match(explanation.describedBy ?? "", /convertDisabledHint/); + assert.match(explanation.text, /audio.only/i); + + const clear = await api("clearQueue"); + assert.equal(clear.ok, true); + const firstUrl = "https://www.youtube.com/watch?v=rosi-ui-polish-queue-a"; + const secondUrl = + "https://www.youtube.com/watch?v=rosi-ui-polish-queue-b"; + assert.equal((await api("addToQueue", [firstUrl])).ok, true); + await waitFor( + (url) => + [...document.querySelectorAll(".queue-item")].some( + (row) => + row.dataset.queueId && + row.textContent.includes(new URL(url).hostname), + ), + "first queue item did not render", + 8_000, + firstUrl, + ); + const first = (await api("getQueue")).find( + (item) => item.url === firstUrl, + ); + assert.ok(first); + const initial = await browser.execute((id) => { + const row = [...document.querySelectorAll(".queue-item")].find( + (candidate) => candidate.dataset.queueId === id, + ); + const up = row.querySelector( + '[data-queue-action="queue-item-move-up"]', + ); + const remove = row.querySelector( + '[data-queue-action="queue-item-remove"]', + ); + remove.focus(); + return { + status: row.querySelector(".queue-item-meta")?.textContent ?? "", + disabledReason: up.getAttribute("aria-description"), + }; + }, first.id); + assert.match(initial.status, /pending/i); + const srStatus = await browser.execute( + (id) => + [...document.querySelectorAll(".queue-item")] + .find((row) => row.dataset.queueId === id) + ?.querySelector(".sr-only")?.textContent ?? "", + first.id, + ); + assert.match(srStatus, /Pending. Waiting for the queue to start./); + assert.match(initial.disabledReason, /first/i); + assert.equal((await api("addToQueue", [secondUrl])).ok, true); + await waitFor( + (url) => + [...document.querySelectorAll(".queue-item")].some((row) => + row.textContent.includes(new URL(url).hostname), + ), + "second queue item did not render", + 8_000, + secondUrl, + ); + const retained = await browser.execute( + (id) => + document.activeElement?.dataset.queueId === id && + document.activeElement?.dataset.queueAction === "queue-item-remove", + first.id, + ); + assert.equal(retained, true, "queue refresh stole focused action"); + assert.equal((await api("clearQueue")).ok, true); + return { initialStatus: "pending", focusRetained: retained }; + })); + + it("renders partial failure actions from the native activity event", async () => + scenario("activity-partial-success-output-action", async () => { + const outputPath = "C:/rosi-e2e/partial-output.mkv"; + await browser.execute((filePath) => { + window.__uiPolishOpenedPaths = []; + window.__uiPolishOriginalOpenFileLocation = window.api.openFileLocation; + window.api.openFileLocation = async (target) => { + window.__uiPolishOpenedPaths.push(target); + return { ok: true, data: { opened: true } }; + }; + const entry = { + id: "ui-polish-partial-outcome", + owner: "manual", + outcome: "failed", + statusMessage: "One playlist item failed after another was saved.", + url: "https://www.youtube.com/playlist?list=ui-polish", + request: { + url: "https://www.youtube.com/playlist?list=ui-polish", + outputPath: filePath, + }, + filename: "ui-polish-playlist", + outputPath: filePath, + outputPaths: [filePath, `${filePath}.part`], + failedPaths: [`${filePath}.part`], + error: "One item could not be converted.", + startedAt: Date.now() - 2000, + completedAt: Date.now(), + }; + window.__TAURI__.event.emit("download-activity-update", [entry]); + }, outputPath); + await waitFor( + () => + [...document.querySelectorAll("#history-list .history-item")].some( + (row) => row.textContent.includes("ui-polish-playlist"), + ), + "partial activity entry did not render", + 5_000, + ); + const row = await browser.execute(() => { + const item = [ + ...document.querySelectorAll("#history-list .history-item"), + ].find((candidate) => + candidate.textContent.includes("ui-polish-playlist"), + ); + return { + status: item.querySelector(".history-status")?.textContent.trim(), + errorText: item.querySelector(".history-error")?.textContent.trim(), + action: [...item.querySelectorAll(".history-open-btn")] + .map((button) => button.getAttribute("aria-label")) + .find((label) => /file location/i.test(label ?? "")), + }; + }); + // One output was saved before the failure, so the 5.1 activity model + // reports a partial completion rather than a plain failure. + assert.equal(row.status, "Partially completed"); + assert.match(row.errorText, /could not be converted/i); + assert.match(row.action, /file location/i); + await browser.execute(() => + [ + ...document.querySelectorAll( + "#history-list .history-item .history-open-btn", + ), + ] + .find((button) => + /file location/i.test(button.getAttribute("aria-label") ?? ""), + ) + ?.click(), + ); + await browser.waitUntil( + async () => + (await browser.execute(() => window.__uiPolishOpenedPaths.length)) === + 1, + { + timeout: 5_000, + timeoutMsg: "Open folder action did not invoke the native bridge", + }, + ); + const paths = await browser.execute(() => { + window.api.openFileLocation = window.__uiPolishOriginalOpenFileLocation; + delete window.__uiPolishOriginalOpenFileLocation; + const captured = window.__uiPolishOpenedPaths; + delete window.__uiPolishOpenedPaths; + return captured; + }); + assert.deepEqual(paths, [outputPath]); + return { + outcome: row.status, + action: row.action, + outputPath, + fixture: "native-event", + }; + })); + + it("keeps keyboard access and layout across themes and text scales", async () => + scenario("theme-viewport-keyboard-layout", async () => { + const originalSize = await browser.getWindowSize(); + const matrix = []; + for (const theme of ["system", "light", "dark", "purple"]) { + matrix.push({ + theme, + width: 900, + height: 560, + ...(await captureViewport(theme, 900, 560, false)), + }); + matrix.push({ + theme, + width: 1200, + height: 900, + ...(await captureViewport(theme, 1200, 900, false)), + }); + matrix.push({ + theme, + width: 900, + height: 560, + ...(await captureViewport(theme, 900, 560, true)), + }); + } + await browser.execute(() => { + document.documentElement.style.fontSize = ""; + delete document.documentElement.dataset.reducedMotionProbe; + }); + await browser.setWindowSize(originalSize.width, originalSize.height); + await setSidebarOpen(true); + await browser.execute(() => + document.getElementById("settingsSearch").focus(), + ); + const keyboard = await browser.execute(() => ({ + focused: document.activeElement?.id, + focusVisible: + document.activeElement?.matches(":focus-visible") ?? false, + reducedMotionRule: [...document.styleSheets].some((sheet) => { + try { + return [...sheet.cssRules].some((rule) => + rule.conditionText?.includes("prefers-reduced-motion"), + ); + } catch { + return false; + } + }), + })); + assert.equal(keyboard.focused, "settingsSearch"); + assert.equal(keyboard.reducedMotionRule, true); + await setSidebarOpen(false); + return { + viewportCases: matrix.length, + keyboardFocus: keyboard.focused, + screenshots: report.screenshots.length, + }; + })); +}); diff --git a/package.json b/package.json index d0e08003..beaa3d9f 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "test:e2e": "node scripts/test-e2e.js", "test:e2e:stability": "node scripts/test-e2e.js --repeat 5", "test:e2e:updater-zst": "node scripts/e2e-updater-zst.mjs", + "test:e2e:macos-native-packages": "node scripts/e2e-macos-native-packages.mjs", "test:all": "node scripts/test-all.js", "test:cargo-safe-update": "node --test scripts/cargo-safe-update.test.mjs scripts/check-cargo-update-policy.test.mjs scripts/test-all.test.js scripts/run-release.test.js scripts/github-cli.test.cjs scripts/release-branch-protection.test.cjs scripts/release-licenses.test.mjs scripts/npm-dev-audit.test.cjs scripts/generate-cargo-licenses.test.mjs scripts/check-rustsec-ignore-policy.test.mjs scripts/legacy-v4-feed.test.mjs scripts/security-release-repairs.test.mjs scripts/round2-release-updater.test.mjs scripts/test-e2e-round2.test.mjs scripts/git-reset.test.mjs scripts/fetch-ytdlp-gpg-path.test.mjs scripts/release-preflight.test.mjs scripts/msstore-pack.test.mjs scripts/test-e2e-only.test.mjs scripts/test-e2e-background.test.mjs", "check:cargo-update-policy": "node scripts/check-cargo-update-policy.mjs", @@ -106,8 +107,17 @@ "build:msstore": "npm run sync-version && npm run licenses && npm run prepare:sidecars && npm run build:msstore:win && dotenv -e .env -- node scripts/msstore-pack.js", "build:mac:universal:prepared": "dotenv -e .env -- tauri build --target universal-apple-darwin --bundles dmg,app -- --locked", "build:mac:universal": "npm run sync-version && npm run licenses && npm run prepare:sidecars && npm run build:mac:universal:prepared", - "build:mac:zip": "node scripts/zip-macos.js", - "build:mac:updater-arches:prepared": "dotenv -e .env -- tauri build --target aarch64-apple-darwin --bundles app -- --locked && dotenv -e .env -- tauri build --target x86_64-apple-darwin --bundles app -- --locked", + "build:mac:arm64:prepared": "dotenv -e .env -- tauri build --target aarch64-apple-darwin --bundles dmg,app -- --locked", + "build:mac:x64:prepared": "dotenv -e .env -- tauri build --target x86_64-apple-darwin --bundles dmg,app -- --locked", + "build:mac:native:prepared": "npm run build:mac:arm64:prepared && npm run build:mac:x64:prepared", + "build:mac:arm64": "npm run sync-version && npm run licenses && npm run prepare:sidecars && npm run build:mac:arm64:prepared && node scripts/zip-macos.js --target aarch64-apple-darwin", + "build:mac:x64": "npm run sync-version && npm run licenses && npm run prepare:sidecars && npm run build:mac:x64:prepared && node scripts/zip-macos.js --target x86_64-apple-darwin", + "build:mac:native": "npm run sync-version && npm run licenses && npm run prepare:sidecars && npm run build:mac:native:prepared && npm run build:mac:zip:native", + "build:mac:zip": "node scripts/zip-macos.js --target universal-apple-darwin", + "build:mac:zip:arm64": "node scripts/zip-macos.js --target aarch64-apple-darwin", + "build:mac:zip:x64": "node scripts/zip-macos.js --target x86_64-apple-darwin", + "build:mac:zip:native": "npm run build:mac:zip:arm64 && npm run build:mac:zip:x64", + "build:mac:updater-arches:prepared": "npm run build:mac:native:prepared", "build:mac:updater-zst": "dotenv -e .env -- node scripts/pack-macos-updater-zst.js", "mac:ssh:keychain": "bash scripts/mac-keychain-ssh.sh", "build:linux:x64:prepared": "dotenv -e .env -- tauri build --target x86_64-unknown-linux-gnu --bundles appimage -- --locked", @@ -141,7 +151,7 @@ "release:win:continue": "npm run release:session:verify && npm run release:licenses && npm run release:draft && npm run release:legacy-v4-feed && npm run rust:targets:win && npm run build:win:prepared && npm run prepare:sidecars && npm run release:sign:gpg && npm run release:finalize", "release:win:resume": "npm run prerelease:prepare && npm run release:win:continue", "release:win": "node scripts/run-release.js win", - "release:mac:continue": "npm run release:session:verify && npm run release:licenses && npm run release:wait-draft && npm run rust:targets:mac && npm run build:mac:universal:prepared && npm run build:mac:zip && npm run build:mac:updater-arches:prepared && npm run build:mac:updater-zst && node scripts/e2e-updater-zst.mjs --require-real-builds && npm run release:sign:gpg && npm run release:finalize", + "release:mac:continue": "npm run release:session:verify && npm run release:licenses && npm run release:wait-draft && npm run rust:targets:mac && npm run build:mac:universal:prepared && npm run build:mac:zip && npm run build:mac:updater-arches:prepared && npm run build:mac:zip:native && npm run build:mac:updater-zst && npm run test:e2e:macos-native-packages -- --require-real-builds && node scripts/e2e-updater-zst.mjs --require-real-builds && npm run release:sign:gpg && npm run release:finalize", "release:mac:resume": "npm run prerelease:prepare && npm run release:mac:continue", "release:mac": "node scripts/run-release.js mac", "release:mac:ssh": "npm run mac:ssh:keychain && node scripts/run-release.js mac", diff --git a/scripts/benchmark-51.mjs b/scripts/benchmark-51.mjs new file mode 100644 index 00000000..1abf8661 --- /dev/null +++ b/scripts/benchmark-51.mjs @@ -0,0 +1,807 @@ +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; + +const REPO_ROOT = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); +const DEFAULT_ARTIFACTS = path.join(REPO_ROOT, "e2e", "artifacts"); +const METRIC_UNITS = Object.freeze({ + startupMs: "ms", + idleCpuPercent: "percent", + peakMemoryBytes: "bytes", + queueLatencyMs: "ms", + proxyThroughputBytesPerSecond: "bytes_per_second", +}); + +function sha256(value) { + return crypto.createHash("sha256").update(value).digest("hex"); +} + +function runVersion(command, args) { + let invocation = [command, args]; + if (process.platform === "win32" && command === "npm.cmd") { + invocation = ["cmd.exe", ["/d", "/s", "/c", `npm.cmd ${args.join(" ")}`]]; + } + const result = spawnSync(invocation[0], invocation[1], { + cwd: REPO_ROOT, + encoding: "utf8", + windowsHide: true, + timeout: 10_000, + }); + if (result.error || result.status !== 0) { + return { + status: "unavailable", + reason: + result.error?.message ?? `exited ${result.status ?? result.signal}`, + }; + } + return { + status: "available", + version: (result.stdout || result.stderr).trim().split(/\r?\n/, 1)[0], + }; +} + +function gitValue(args) { + const result = spawnSync("git", args, { + cwd: REPO_ROOT, + encoding: "utf8", + windowsHide: true, + timeout: 10_000, + }); + if (result.error || result.status !== 0) { + throw new Error( + `git ${args.join(" ")} failed: ${result.error?.message ?? result.stderr}`, + ); + } + return result.stdout.trim(); +} + +function gitRaw(args) { + const result = spawnSync("git", args, { + cwd: REPO_ROOT, + encoding: "utf8", + windowsHide: true, + timeout: 10_000, + }); + if (result.error || result.status !== 0) { + throw new Error( + `git ${args.join(" ")} failed: ${result.error?.message ?? result.stderr}`, + ); + } + return result.stdout; +} + +function repoRelative(file) { + return path.relative(REPO_ROOT, file).split(path.sep).join("/"); +} + +function displayPath(file) { + const relative = repoRelative(file); + return relative === ".." || relative.startsWith(`..${path.sep}`) + ? file + : relative; +} + +function walkFiles(root, accept = () => true) { + if (!fs.existsSync(root)) return []; + const files = []; + const visit = (directory) => { + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const file = path.join(directory, entry.name); + if (entry.isDirectory()) visit(file); + else if (entry.isFile() && accept(file)) files.push(file); + } + }; + visit(root); + return files.sort((a, b) => a.localeCompare(b)); +} + +function fileRecord(file) { + const bytes = fs.readFileSync(file); + return { + path: repoRelative(file), + bytes: bytes.byteLength, + sha256: sha256(bytes), + }; +} + +function collectArtifactSizes(artifactRoot) { + const files = walkFiles(artifactRoot, (file) => { + const basename = path.basename(file); + return !basename.startsWith("benchmark-51-"); + }); + const groups = {}; + for (const file of files) { + const relative = path.relative(artifactRoot, file).split(path.sep); + const group = relative.length > 1 ? relative[0] : "_root"; + const current = groups[group] ?? { files: 0, bytes: 0 }; + current.files += 1; + current.bytes += fs.statSync(file).size; + groups[group] = current; + } + return { + root: repoRelative(artifactRoot), + files: files.length, + bytes: files.reduce((total, file) => total + fs.statSync(file).size, 0), + groups, + }; +} + +function collectSidecars() { + const sidecarPattern = + /^rosi-(?:yt-dlp|ffmpeg|ffprobe)(?:-[^.]+)?(?:\.exe)?$/i; + const roots = [ + [path.join(REPO_ROOT, "src-tauri", "binaries"), "source"], + [path.join(REPO_ROOT, "src-tauri", "target", "debug"), "debug-build"], + ]; + const files = []; + for (const [root, kind] of roots) { + files.push( + ...walkFiles(root, (file) => + sidecarPattern.test(path.basename(file)), + ).map((file) => ({ ...fileRecord(file), kind })), + ); + } + return { + files, + fileCount: files.length, + bytes: files.reduce((total, file) => total + file.bytes, 0), + }; +} + +function collectFrontendBuild() { + const files = walkFiles(path.join(REPO_ROOT, "dist")); + return { + status: files.length > 0 ? "measured" : "not-measured", + files: files.length, + bytes: + files.length > 0 + ? files.reduce((total, file) => total + fs.statSync(file).size, 0) + : null, + note: "Frontend build output; not a native release package.", + }; +} + +function collectNativePackages() { + const roots = [path.join(REPO_ROOT, "dist")]; + const target = path.join(REPO_ROOT, "src-tauri", "target"); + if (fs.existsSync(target)) { + for (const entry of fs.readdirSync(target, { withFileTypes: true })) { + if ( + !entry.isDirectory() || + entry.name === "debug" || + entry.name === "release" + ) { + continue; + } + roots.push(path.join(target, entry.name, "release", "bundle")); + } + roots.push(path.join(target, "release", "bundle")); + } + const packagePattern = + /\.(?:dmg|appimage|flatpak|deb|rpm|msi|msix|msixbundle|exe|zip|app\.tar\.(?:gz|zst))$/i; + const files = roots.flatMap((root) => + walkFiles(root, (file) => packagePattern.test(path.basename(file))).map( + (file) => fileRecord(file), + ), + ); + if (files.length === 0) { + return { + status: "not-measured", + fileCount: null, + bytes: null, + files: [], + reason: + "No native release package artifacts were found in the scanned output directories.", + }; + } + return { + status: "measured", + files, + fileCount: files.length, + bytes: files.reduce((total, file) => total + file.bytes, 0), + }; +} + +function parseReportReference(file) { + const record = fileRecord(file); + let content = null; + try { + content = JSON.parse(fs.readFileSync(file, "utf8")); + } catch { + // A bad historical report remains visible as an unreadable reference. + } + return { + ...record, + readable: content !== null, + recordedOutcome: + content === null + ? "unreadable" + : content.passed === true || content.allPassed === true + ? "claims-passed-unverified" + : content.passed === false || content.allPassed === false + ? "claims-failed-unverified" + : "no-verdict-field", + commit: content?.commit ?? null, + platform: content?.platform ?? null, + arch: content?.arch ?? null, + startedAt: content?.startedAt ?? null, + finishedAt: content?.finishedAt ?? null, + scenarioCount: Array.isArray(content?.scenarios) + ? content.scenarios.length + : null, + binarySha256: content?.binarySha256 ?? null, + }; +} + +function collectReportReferences(artifactRoot) { + const files = walkFiles(artifactRoot, (file) => { + const basename = path.basename(file); + return ( + /^e2e-report-.*\.json$/i.test(basename) || + /^e2e-stability-.*\.json$/i.test(basename) || + basename === "report.json" || + basename === "result.json" + ); + }); + return files.map(parseReportReference); +} + +function collectScenarioInventory(manifest) { + const staticByFeature = {}; + for (const scenario of manifest.scenarios) { + staticByFeature[scenario.feature] = + (staticByFeature[scenario.feature] ?? 0) + 1; + } + const v5Root = path.join(REPO_ROOT, "e2e", "v5-fixes"); + const dynamicV5Areas = fs.existsSync(v5Root) + ? fs + .readdirSync(v5Root, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .filter((entry) => { + const directory = path.join(v5Root, entry.name); + return ( + fs.existsSync(path.join(directory, "run.mjs")) || + fs + .readdirSync(directory, { withFileTypes: true }) + .some((file) => file.isFile() && file.name.endsWith(".spec.js")) + ); + }) + .map((entry) => entry.name) + .sort() + : []; + return { + staticDiscoveredCount: manifest.scenarios.length, + staticByFeature, + staticIds: manifest.scenarios.map((scenario) => scenario.name), + dynamicV5DiscoveredCount: dynamicV5Areas.length, + dynamicV5Areas, + execution: { + status: "not-run-by-benchmark", + executedScenarioCount: null, + note: "Inventory discovery is not E2E execution evidence.", + }, + }; +} + +function loadRuntimeMetrics(metricsFile) { + const definitions = Object.keys(METRIC_UNITS); + if (!metricsFile) { + return { + status: "missing", + source: null, + missingMetrics: definitions, + reason: + "No runtime measurement file was supplied; no historical values were inferred.", + measurements: Object.fromEntries( + definitions.map((name) => [ + name, + { status: "not-measured", unit: METRIC_UNITS[name] }, + ]), + ), + }; + } + const file = path.resolve(metricsFile); + const inputBytes = fs.readFileSync(file); + const input = JSON.parse(inputBytes.toString("utf8")); + if (input.schemaVersion !== 1) { + throw new Error("runtime metrics schemaVersion must be 1"); + } + if (input.platform !== process.platform || input.arch !== process.arch) { + throw new Error( + `runtime metrics host ${input.platform}/${input.arch} does not match capture host ${process.platform}/${process.arch}`, + ); + } + if (input.platformRelease && input.platformRelease !== os.release()) { + throw new Error( + `runtime metrics OS release ${input.platformRelease} does not match capture release ${os.release()}`, + ); + } + if (typeof input.method !== "string" || input.method.trim() === "") { + throw new Error("runtime metrics must describe the measurement method"); + } + const values = input.measurements ?? {}; + const measurements = {}; + const missingMetrics = []; + for (const name of definitions) { + const measurement = values[name]; + if (measurement === undefined) { + measurements[name] = { status: "not-measured", unit: METRIC_UNITS[name] }; + missingMetrics.push(name); + continue; + } + if ( + typeof measurement.value !== "number" || + !Number.isFinite(measurement.value) || + measurement.value < 0 || + measurement.unit !== METRIC_UNITS[name] + ) { + throw new Error( + `runtime metric ${name} needs a nonnegative number in ${METRIC_UNITS[name]}`, + ); + } + measurements[name] = { + status: "measured", + value: measurement.value, + unit: measurement.unit, + samples: + Number.isInteger(measurement.samples) && measurement.samples > 0 + ? measurement.samples + : null, + method: measurement.method ?? input.method, + evidence: measurement.evidence ?? null, + }; + } + if ( + measurements.idleCpuPercent.status === "measured" && + measurements.idleCpuPercent.value > 100 + ) { + throw new Error("runtime metric idleCpuPercent must be between 0 and 100"); + } + return { + status: missingMetrics.length === 0 ? "measured" : "partial", + source: { + path: displayPath(file), + sha256: sha256(inputBytes), + measuredAt: input.measuredAt ?? null, + method: input.method, + platformRelease: input.platformRelease ?? os.release(), + }, + missingMetrics, + measurements, + }; +} + +function compareReports(current, baseline) { + if (baseline.schemaVersion !== 2) { + throw new Error("comparison baseline schemaVersion must be 2"); + } + const problems = []; + if (baseline.reportSha256) { + const { reportSha256, ...unsigned } = baseline; + if ( + sha256(Buffer.from(JSON.stringify(unsigned, null, 2))) !== reportSha256 + ) { + throw new Error("comparison baseline reportSha256 is invalid"); + } + } else { + problems.push("baseline has no reportSha256 integrity field"); + } + const sameHost = + current.platform === baseline.platform && current.arch === baseline.arch; + if (!sameHost) problems.push("platform or architecture differs"); + const sameRuntimeHost = + sameHost && current.platformRelease === baseline.platformRelease; + if (sameHost && !sameRuntimeHost) + problems.push("operating-system release differs"); + + const metrics = {}; + for (const [name, currentMetric] of Object.entries( + current.runtimeMetrics.measurements, + )) { + const baselineMetric = baseline.runtimeMetrics?.measurements?.[name]; + if ( + !sameRuntimeHost || + currentMetric.status !== "measured" || + baselineMetric?.status !== "measured" || + currentMetric.unit !== baselineMetric.unit || + currentMetric.method !== baselineMetric.method + ) { + metrics[name] = { + status: "not-comparable", + currentStatus: currentMetric.status, + baselineStatus: baselineMetric?.status ?? "missing", + unit: currentMetric.unit, + reason: + sameRuntimeHost && + currentMetric.status === "measured" && + baselineMetric?.status === "measured" && + currentMetric.method !== baselineMetric.method + ? "measurement method differs" + : undefined, + }; + continue; + } + const delta = currentMetric.value - baselineMetric.value; + metrics[name] = { + status: "compared", + baseline: baselineMetric.value, + current: currentMetric.value, + delta, + unit: currentMetric.unit, + deltaPercent: + baselineMetric.value === 0 + ? null + : (delta / baselineMetric.value) * 100, + }; + } + const sizeDelta = (currentValue, baselineValue) => + sameHost + ? { + status: "compared", + baseline: baselineValue, + current: currentValue, + delta: currentValue - baselineValue, + } + : { + status: "not-comparable", + reason: "platform or architecture differs", + }; + const packageSizes = () => { + const currentPackages = current.sizes.nativePackages; + const baselinePackages = baseline.sizes.nativePackages; + if (!sameHost) { + return { + status: "not-comparable", + reason: "platform or architecture differs", + }; + } + if ( + currentPackages?.status !== "measured" || + baselinePackages?.status !== "measured" + ) { + return { + status: "not-measured", + currentStatus: currentPackages?.status ?? "missing", + baselineStatus: baselinePackages?.status ?? "missing", + reason: "A missing package inventory is not a zero-size package.", + }; + } + return { + status: "compared", + baseline: baselinePackages.bytes, + current: currentPackages.bytes, + delta: currentPackages.bytes - baselinePackages.bytes, + }; + }; + return { + baseline: { + path: baseline.reportPath ?? null, + reportSha256: baseline.reportSha256 ?? null, + sourceRevision: baseline.sourceRevision ?? null, + platform: baseline.platform, + arch: baseline.arch, + platformRelease: baseline.platformRelease, + }, + compatible: sameHost, + runtimeEnvironmentMatches: sameRuntimeHost, + runtimeMetricsComparable: + sameRuntimeHost && + Object.keys(METRIC_UNITS).every( + (name) => metrics[name]?.status === "compared", + ), + problems, + sizes: { + evidenceArtifacts: sizeDelta( + current.sizes.evidenceArtifacts.bytes, + baseline.sizes.evidenceArtifacts.bytes, + ), + sidecars: sizeDelta( + current.sizes.sidecars.bytes, + baseline.sizes.sidecars.bytes, + ), + frontendBuild: sizeDelta( + current.sizes.frontendBuild.bytes, + baseline.sizes.frontendBuild.bytes, + ), + nativePackages: packageSizes(), + }, + runtimeMetrics: metrics, + }; +} + +function parseArgs(argv) { + const options = { + label: "current", + out: null, + compare: null, + metrics: null, + snapshot: null, + force: false, + }; + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (argument === "--help" || argument === "-h") { + options.help = true; + continue; + } + if (argument === "--force") { + options.force = true; + continue; + } + const [key, inlineValue] = argument.startsWith("--") + ? argument.slice(2).split(/=(.*)/s, 2) + : [null, null]; + if ( + !key || + !["label", "out", "compare", "runtime-metrics", "snapshot"].includes(key) + ) { + throw new Error(`unknown benchmark option: ${argument}`); + } + const value = inlineValue ?? argv[++index]; + if (!value || value.startsWith("--")) + throw new Error(`--${key} needs a value`); + if (key === "runtime-metrics") options.metrics = value; + else options[key] = value; + } + if (!/^[a-z0-9][a-z0-9._-]*$/i.test(options.label)) { + throw new Error( + "--label may contain only letters, numbers, dots, underscores, and hyphens", + ); + } + return options; +} + +function readSnapshot(snapshotDir) { + if (!snapshotDir) return null; + const root = path.resolve(snapshotDir); + const headFile = path.join(root, "head.txt"); + const hashesFile = path.join(root, "hashes.json"); + const trackedFile = path.join(root, "tracked.txt"); + if (![headFile, hashesFile, trackedFile].every(fs.existsSync)) { + throw new Error( + "clean snapshot needs head.txt, hashes.json, and tracked.txt", + ); + } + const hashes = JSON.parse(fs.readFileSync(hashesFile, "utf8")); + const stagedPatch = fs.existsSync(path.join(root, "staged.patch")) + ? fs.statSync(path.join(root, "staged.patch")).size + : null; + const unstagedPatch = fs.existsSync(path.join(root, "unstaged.patch")) + ? fs.statSync(path.join(root, "unstaged.patch")).size + : null; + const snapshotHead = fs.readFileSync(headFile, "utf8").trim(); + return { + path: root, + head: snapshotHead, + trackedFileCount: fs + .readFileSync(trackedFile, "utf8") + .split(/\r?\n/) + .filter(Boolean).length, + hashedFileCount: hashes.length, + stagedPatchBytes: stagedPatch, + unstagedPatchBytes: unstagedPatch, + matchesCurrentHead: snapshotHead === gitValue(["rev-parse", "HEAD"]), + cleanSnapshot: stagedPatch === 0 && unstagedPatch === 0, + }; +} + +function collectWorktreeIdentity() { + const statusRecords = gitRaw([ + "status", + "--porcelain=v1", + "-z", + "--untracked-files=all", + ]) + .split("\0") + .filter(Boolean); + const files = []; + for (let index = 0; index < statusRecords.length; index += 1) { + const record = statusRecords[index]; + const hasStatusPrefix = /^[ MADRCU?!]{2} /.test(record); + const status = hasStatusPrefix ? record.slice(0, 2) : "rename-source"; + const relativePath = hasStatusPrefix ? record.slice(3) : record; + const absolutePath = path.resolve(REPO_ROOT, relativePath); + const resolvedRelative = path.relative(REPO_ROOT, absolutePath); + if ( + resolvedRelative === ".." || + resolvedRelative.startsWith(`..${path.sep}`) || + path.isAbsolute(resolvedRelative) + ) { + throw new Error( + `git reported a worktree path outside the repository: ${relativePath}`, + ); + } + let kind = "missing"; + let fileSha256 = null; + if (fs.existsSync(absolutePath)) { + const stats = fs.lstatSync(absolutePath); + if (stats.isSymbolicLink()) { + kind = "symlink"; + fileSha256 = sha256(Buffer.from(fs.readlinkSync(absolutePath))); + } else if (stats.isFile()) { + kind = "file"; + fileSha256 = sha256(fs.readFileSync(absolutePath)); + } else if (stats.isDirectory()) { + kind = "directory"; + } + } + files.push({ + status, + path: resolvedRelative.split(path.sep).join("/"), + kind, + sha256: fileSha256, + }); + } + files.sort((a, b) => a.path.localeCompare(b.path)); + return { + files, + sha256: sha256(Buffer.from(JSON.stringify(files))), + }; +} + +function capture(options) { + const manifest = JSON.parse( + fs.readFileSync(path.join(REPO_ROOT, "e2e", "suites.json"), "utf8"), + ); + const artifactRoot = path.resolve(DEFAULT_ARTIFACTS); + const packageJson = JSON.parse( + fs.readFileSync(path.join(REPO_ROOT, "package.json"), "utf8"), + ); + const tauriCliPackage = path.join( + REPO_ROOT, + "node_modules", + "@tauri-apps", + "cli", + "package.json", + ); + const tauriCli = fs.existsSync(tauriCliPackage) + ? { + status: "available", + version: JSON.parse(fs.readFileSync(tauriCliPackage, "utf8")).version, + } + : { + status: "unavailable", + declaredRange: packageJson.devDependencies?.["@tauri-apps/cli"] ?? null, + }; + const commit = gitValue(["rev-parse", "HEAD"]); + const worktreeIdentity = collectWorktreeIdentity(); + const sourceRevision = { + commit, + dirty: worktreeIdentity.files.length > 0, + changedPathCount: worktreeIdentity.files.length, + worktreeSha256: worktreeIdentity.sha256, + worktreeFiles: worktreeIdentity.files, + diffSha256: sha256( + Buffer.from(gitRaw(["diff", "--binary", "HEAD", "--", "."])), + ), + }; + const scenarioInventory = collectScenarioInventory(manifest); + const reportReferences = collectReportReferences(artifactRoot); + const current = { + schemaVersion: 2, + label: options.label, + capturedAt: new Date().toISOString(), + platform: process.platform, + arch: process.arch, + platformRelease: os.release(), + sourceRevision, + cleanSnapshot: readSnapshot(options.snapshot), + versions: { + node: { status: "available", version: process.version }, + npm: runVersion(process.platform === "win32" ? "npm.cmd" : "npm", [ + "--version", + ]), + rustc: runVersion("rustc", ["--version"]), + cargo: runVersion("cargo", ["--version"]), + tauriCli, + packageManager: packageJson.packageManager ?? null, + packageVersion: packageJson.version, + }, + scenarioInventory, + sizes: { + evidenceArtifacts: collectArtifactSizes(artifactRoot), + sidecars: collectSidecars(), + frontendBuild: collectFrontendBuild(), + nativePackages: collectNativePackages(), + }, + runtimeMetrics: loadRuntimeMetrics(options.metrics), + historicalReportReferences: { + count: reportReferences.length, + references: reportReferences, + note: "Archived report contents are unverified references only; they are not baseline execution results for this capture.", + }, + executionEvidence: { + status: "not-run", + passed: null, + note: "This command inventories files and reports. It does not execute E2E scenarios or infer historical pass status.", + }, + }; + if (options.compare) { + const baselinePath = path.resolve(options.compare); + const baseline = JSON.parse(fs.readFileSync(baselinePath, "utf8")); + current.comparison = compareReports( + { ...current, reportPath: null }, + { ...baseline, reportPath: repoRelative(baselinePath) }, + ); + } + return current; +} + +function help() { + process.stdout.write( + [ + "Usage: node scripts/benchmark-51.mjs [options]", + " --label Report label (default: current)", + " --out Explicit report path (refuses overwrite by default)", + " --force Allow overwriting an explicit --out path", + " --compare Compare sizes and supplied runtime measurements", + " --runtime-metrics Import actual measurements using schemaVersion 1", + " --snapshot Record the saved clean-snapshot identity", + "", + "Runtime metrics fields: startupMs (ms), idleCpuPercent (percent), peakMemoryBytes (bytes),", + "queueLatencyMs (ms), proxyThroughputBytesPerSecond (bytes_per_second).", + ].join("\n") + "\n", + ); +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + if (options.help) return help(); + const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); + const outPath = path.resolve( + options.out ?? + path.join( + DEFAULT_ARTIFACTS, + `benchmark-51-${options.label}-${process.platform}-${process.arch}-${timestamp}-${process.pid}.json`, + ), + ); + if ( + !options.force && + (fs.existsSync(outPath) || fs.existsSync(`${outPath}.sha256`)) + ) { + throw new Error( + `benchmark output already exists; choose a new --out path or pass --force: ${displayPath(outPath)}`, + ); + } + const report = capture(options); + fs.mkdirSync(path.dirname(outPath), { recursive: true }); + report.reportPath = displayPath(outPath); + const canonical = JSON.stringify(report, null, 2); + report.reportSha256 = sha256(Buffer.from(canonical)); + const serialized = `${JSON.stringify(report, null, 2)}\n`; + fs.writeFileSync(outPath, serialized); + const fileHash = sha256(Buffer.from(serialized)); + fs.writeFileSync( + `${outPath}.sha256`, + `${fileHash} ${path.basename(outPath)}\n`, + ); + process.stdout.write( + `${report.reportPath}\n` + + `reportSha256=${report.reportSha256}\n` + + `evidenceArtifacts=${report.sizes.evidenceArtifacts.files} files, ${report.sizes.evidenceArtifacts.bytes} bytes\n` + + `sidecars=${report.sizes.sidecars.fileCount} files, ${report.sizes.sidecars.bytes} bytes\n` + + `nativePackages=${report.sizes.nativePackages.status}${report.sizes.nativePackages.bytes === null ? " (not measured)" : `: ${report.sizes.nativePackages.bytes} bytes`}\n` + + `staticScenarios=${report.scenarioInventory.staticDiscoveredCount}; dynamicV5Areas=${report.scenarioInventory.dynamicV5DiscoveredCount}; executed=not-run\n` + + `runtimeMetrics=${report.runtimeMetrics.status}\n`, + ); +} + +if ( + process.argv[1] && + fileURLToPath(import.meta.url) === path.resolve(process.argv[1]) +) { + try { + main(); + } catch (error) { + process.stderr.write( + `${error instanceof Error ? error.message : String(error)}\n`, + ); + process.exitCode = 1; + } +} diff --git a/scripts/e2e-macos-native-packages.mjs b/scripts/e2e-macos-native-packages.mjs new file mode 100644 index 00000000..6bb1a4fa --- /dev/null +++ b/scripts/e2e-macos-native-packages.mjs @@ -0,0 +1,1077 @@ +#!/usr/bin/env node + +// Fixture E2E for native macOS package naming, architecture routing, release +// asset completeness, and checksums. Native signing/notarization acceptance is +// recorded separately because those checks require a macOS release machine. + +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { + assertArchitectureCompatibility, + assertBundleVersions, + assertMinimumMacOSVersion, + macosPackageName, + normalizeDmgPackage, + packageOutputPath, + MACOS_TARGETS, + verifyAppBundle, +} from "./zip-macos.js"; +import { + artifactMatchesVersion, + checksumGroupsForArtifacts, + checksumTargetKeysForArtifactName, + cleanArtifactName, + isArtifact, + isSignable, + pickNewestByBasename, + resolveUpdaterTargets, +} from "./gpg-sign.js"; +import { + assertDraftReleaseShape, + requiredDraftAssetNames, + requiredDraftInstallerNames, + requiredDraftSidecarNames, +} from "./verify-release-draft.js"; +import { validateManifestData } from "./validate-updater-manifest.js"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const reportPath = path.join( + root, + "e2e", + "artifacts", + "macos-native-packages-report.json", +); +const pkg = JSON.parse( + fs.readFileSync(path.join(root, "package.json"), "utf8"), +); +const scenarios = []; +const REQUIRE_REAL_BUILDS = process.argv.includes("--require-real-builds"); +const MACOS_PACKAGE_TARGETS = [ + { target: "universal-apple-darwin", arch: "universal" }, + { target: "aarch64-apple-darwin", arch: "arm64" }, + { target: "x86_64-apple-darwin", arch: "x64" }, +]; + +function sha256File(filePath) { + const hash = crypto.createHash("sha256"); + const descriptor = fs.openSync(filePath, "r"); + const buffer = Buffer.allocUnsafe(1024 * 1024); + try { + let bytesRead; + do { + bytesRead = fs.readSync(descriptor, buffer, 0, buffer.length, null); + if (bytesRead > 0) hash.update(buffer.subarray(0, bytesRead)); + } while (bytesRead > 0); + } finally { + fs.closeSync(descriptor); + } + return hash.digest("hex"); +} + +function runMacTool(command, args, options = {}) { + const result = spawnSync(command, args, { + encoding: "utf8", + maxBuffer: 16 * 1024 * 1024, + windowsHide: true, + ...options, + }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error( + `${command} ${args.join(" ")} failed (${result.status}): ${result.stderr || result.stdout}`, + ); + } + return `${result.stdout || ""}${result.stderr || ""}`.trim(); +} + +function bundleInventory(bundlePath) { + const entries = []; + let totalBytes = 0; + const visit = (absolutePath, relativePath) => { + const stat = fs.lstatSync(absolutePath); + const mode = stat.mode & 0o7777; + if (stat.isSymbolicLink()) { + entries.push({ + path: relativePath, + type: "symlink", + mode, + target: fs.readlinkSync(absolutePath), + }); + return; + } + if (stat.isDirectory()) { + entries.push({ path: relativePath, type: "directory", mode }); + const children = fs + .readdirSync(absolutePath) + .sort((left, right) => left.localeCompare(right)); + for (const child of children) { + visit( + path.join(absolutePath, child), + relativePath ? `${relativePath}/${child}` : child, + ); + } + return; + } + if (stat.isFile()) { + totalBytes += stat.size; + entries.push({ + path: relativePath, + type: "file", + mode, + bytes: stat.size, + sha256: sha256File(absolutePath), + }); + return; + } + throw new Error(`Unsupported special file in app bundle: ${absolutePath}`); + }; + visit(bundlePath, ""); + const sha256 = crypto + .createHash("sha256") + .update(JSON.stringify(entries)) + .digest("hex"); + return { entries, totalBytes, sha256 }; +} + +function requiredBundleAtRoot(directory, { exactRoot = false } = {}) { + const entries = fs.readdirSync(directory, { withFileTypes: true }); + const appEntries = entries.filter((entry) => entry.name === "ROSI.app"); + if ( + appEntries.length !== 1 || + !appEntries[0].isDirectory() || + appEntries[0].isSymbolicLink() + ) { + throw new Error( + `${directory} must contain exactly one directory named ROSI.app`, + ); + } + if (exactRoot && (entries.length !== 1 || entries[0].name !== "ROSI.app")) { + throw new Error( + `${directory} ZIP extraction must contain only ROSI.app at its root`, + ); + } + return path.join(directory, "ROSI.app"); +} + +function relativePath(filePath) { + return path.relative(root, filePath).replaceAll("\\", "/"); +} + +function packagePaths({ target, arch }) { + const bundle = path.join( + root, + "src-tauri", + "target", + target, + "release", + "bundle", + ); + return { + target, + arch, + appPath: path.join(bundle, "macos", "ROSI.app"), + dmgPath: path.join(bundle, "dmg", `ROSI-MacOS-${arch}.dmg`), + zipPath: path.join(bundle, "macos", `ROSI-MacOS-${arch}.zip`), + }; +} + +function assertRecentBuild(filePath, buildStartedAt) { + if (!fs.existsSync(filePath)) { + throw new Error(`Missing required real macOS build artifact: ${filePath}`); + } + const stat = fs.lstatSync(filePath); + if (stat.isSymbolicLink() || (!stat.isFile() && !stat.isDirectory())) { + throw new Error(`Expected a regular build output at ${filePath}`); + } + if (stat.mtimeMs < buildStartedAt - 2000) { + throw new Error( + `${filePath} predates the current release session; rebuild it before native acceptance.`, + ); + } + return stat; +} + +function checkRealBuilds() { + const acceptance = { + status: "failed", + mode: "require-real-builds", + packages: [], + checks: [], + cleanup: { status: "not-needed", detachedMounts: [] }, + }; + if (process.platform !== "darwin") { + acceptance.status = "blocked"; + acceptance.reason = `--require-real-builds requires macOS; current host is ${process.platform}.`; + return acceptance; + } + + const mountedVolumes = []; + let temporaryRoot = null; + let primaryError = null; + try { + const tauriConfig = JSON.parse( + fs.readFileSync(path.join(root, "src-tauri", "tauri.conf.json"), "utf8"), + ); + if (tauriConfig.version !== pkg.version) { + throw new Error( + `Tauri version ${tauriConfig.version} does not match package.json ${pkg.version}.`, + ); + } + const sessionPath = path.join(root, "release", ".build-session.json"); + if (!fs.existsSync(sessionPath)) { + throw new Error( + "Release build session is missing; run release:prepare before real package acceptance.", + ); + } + const session = JSON.parse(fs.readFileSync(sessionPath, "utf8")); + if ( + session.version !== pkg.version || + !Number.isFinite(session.startedAt) + ) { + throw new Error( + "Release build session version or start time is invalid.", + ); + } + acceptance.checks.push({ + name: "release-session-version", + status: "passed", + version: session.version, + startedAt: session.startedAt, + }); + + const packageRecords = new Map(); + for (const targetSpec of MACOS_PACKAGE_TARGETS) { + const paths = packagePaths(targetSpec); + const appInfo = path.join(paths.appPath, "Contents", "Info.plist"); + const hostBinary = path.join(paths.appPath, "Contents", "MacOS", "rosi"); + for (const outputPath of [ + paths.appPath, + paths.dmgPath, + paths.zipPath, + appInfo, + hostBinary, + ]) { + const stat = assertRecentBuild(outputPath, session.startedAt); + if (stat.isFile() && stat.size === 0) { + throw new Error( + `Required real macOS build output is empty: ${outputPath}`, + ); + } + } + verifyAppBundle(paths.appPath, paths.target, tauriConfig, root); + const sourceTree = bundleInventory(paths.appPath); + const source = { + path: relativePath(paths.appPath), + bytes: sourceTree.totalBytes, + sha256: sourceTree.sha256, + inventory: sourceTree.entries, + }; + acceptance.checks.push({ + name: `${targetSpec.arch}-source-bundle`, + status: "passed", + sourcePath: source.path, + sourceBytes: source.bytes, + sourceSha256: source.sha256, + }); + + for (const kind of ["dmg", "zip"]) { + const packagePath = kind === "dmg" ? paths.dmgPath : paths.zipPath; + const stat = fs.statSync(packagePath); + const record = { + target: paths.target, + arch: paths.arch, + kind, + name: path.basename(packagePath), + path: relativePath(packagePath), + bytes: stat.size, + sha256: sha256File(packagePath), + sourceBundle: { + path: source.path, + bytes: source.bytes, + sha256: source.sha256, + }, + }; + if (kind === "zip") { + const extractionRoot = path.join( + temporaryRoot ?? + (temporaryRoot = fs.mkdtempSync( + path.join(os.tmpdir(), "rosi-macos-real-"), + )), + `zip-${paths.arch}`, + ); + fs.mkdirSync(extractionRoot, { recursive: true }); + runMacTool("ditto", ["-x", "-k", packagePath, extractionRoot]); + const extractedApp = requiredBundleAtRoot(extractionRoot, { + exactRoot: true, + }); + verifyAppBundle(extractedApp, paths.target, tauriConfig, root); + const extractedTree = bundleInventory(extractedApp); + assert.deepEqual( + extractedTree.entries, + sourceTree.entries, + `${record.name} changed ROSI.app content, permissions, or symlink targets`, + ); + record.roundTrip = { + status: "passed", + bundleBytes: extractedTree.totalBytes, + bundleSha256: extractedTree.sha256, + signature: "passed", + staple: "passed", + }; + } else { + runMacTool("xcrun", ["stapler", "validate", packagePath]); + const mountRoot = path.join( + temporaryRoot ?? + (temporaryRoot = fs.mkdtempSync( + path.join(os.tmpdir(), "rosi-macos-real-"), + )), + `mount-${paths.arch}`, + ); + fs.mkdirSync(mountRoot, { recursive: true }); + runMacTool("hdiutil", [ + "attach", + "-readonly", + "-nobrowse", + "-noautoopen", + "-mountpoint", + mountRoot, + packagePath, + ]); + mountedVolumes.push(mountRoot); + const mountedApp = requiredBundleAtRoot(mountRoot); + verifyAppBundle(mountedApp, paths.target, tauriConfig, root); + const mountedTree = bundleInventory(mountedApp); + assert.deepEqual( + mountedTree.entries, + sourceTree.entries, + `${record.name} changed ROSI.app content, permissions, or symlink targets`, + ); + record.mount = { + status: "passed", + bundleBytes: mountedTree.totalBytes, + bundleSha256: mountedTree.sha256, + signature: "passed", + staple: "passed", + imageStaple: "passed", + }; + } + packageRecords.set(`${paths.arch}.${kind}`, record); + acceptance.packages.push(record); + } + } + + const universal = { + dmg: packageRecords.get("universal.dmg"), + zip: packageRecords.get("universal.zip"), + }; + for (const arch of ["arm64", "x64"]) { + for (const kind of ["dmg", "zip"]) { + const native = packageRecords.get(`${arch}.${kind}`); + const baseline = universal[kind]; + native.universalBytes = baseline.bytes; + native.smallerThanUniversal = native.bytes < baseline.bytes; + if (!native.smallerThanUniversal) { + throw new Error( + `${native.name} is ${native.bytes} bytes, not smaller than ${baseline.name} at ${baseline.bytes} bytes.`, + ); + } + acceptance.checks.push({ + name: `${arch}-${kind}-smaller-than-universal`, + status: "passed", + nativeBytes: native.bytes, + universalBytes: baseline.bytes, + nativeSha256: native.sha256, + universalSha256: baseline.sha256, + }); + } + } + acceptance.checks.push({ + name: "all-six-real-package-files", + status: "passed", + packageCount: acceptance.packages.length, + }); + acceptance.status = "passed"; + } catch (error) { + primaryError = error instanceof Error ? error : new Error(String(error)); + acceptance.error = primaryError.message; + } finally { + const detachErrors = []; + for (const mountPoint of mountedVolumes.toReversed()) { + try { + runMacTool("hdiutil", ["detach", "-quiet", mountPoint]); + acceptance.cleanup.detachedMounts.push(mountPoint); + } catch (firstError) { + try { + runMacTool("hdiutil", ["detach", "-force", "-quiet", mountPoint]); + acceptance.cleanup.detachedMounts.push(mountPoint); + } catch (forceError) { + detachErrors.push({ + mountPoint, + error: + forceError instanceof Error + ? forceError.message + : String(forceError), + originalError: + firstError instanceof Error + ? firstError.message + : String(firstError), + }); + } + } + } + if (detachErrors.length > 0) { + acceptance.cleanup.status = "failed"; + acceptance.cleanup.errors = detachErrors; + acceptance.status = "failed"; + acceptance.error = [ + acceptance.error, + "Could not detach every mounted DMG.", + ] + .filter(Boolean) + .join(" "); + } else if (mountedVolumes.length > 0) { + acceptance.cleanup.status = "passed"; + } + if (temporaryRoot) { + try { + fs.rmSync(temporaryRoot, { recursive: true, force: true }); + } catch (cleanupError) { + acceptance.status = "failed"; + acceptance.cleanup.status = "failed"; + acceptance.cleanup.temporaryRootError = + cleanupError instanceof Error + ? cleanupError.message + : String(cleanupError); + acceptance.error = [ + acceptance.error, + "Could not remove temporary package verification files.", + ] + .filter(Boolean) + .join(" "); + } + } + if (primaryError && acceptance.status !== "failed") { + acceptance.status = "failed"; + } + } + return acceptance; +} + +async function scenario(id, title, body) { + const startedAt = Date.now(); + try { + const details = (await body()) ?? {}; + scenarios.push({ + id, + title, + ok: true, + ms: Date.now() - startedAt, + ...details, + }); + console.log(`ok ${id} ${title}`); + } catch (error) { + scenarios.push({ + id, + title, + ok: false, + ms: Date.now() - startedAt, + error: error instanceof Error ? error.message : String(error), + }); + console.log( + `FAIL ${id} ${title}\n ${error instanceof Error ? error.message : String(error)}`, + ); + } +} + +function expectFailure(body, pattern) { + assert.throws(body, pattern); +} + +function makeDmgFixture(scratch, target, rawName) { + const bundleRoot = path.join(scratch, target, "release", "bundle"); + const appPath = path.join(bundleRoot, "macos", "ROSI.app"); + const dmgDirectory = path.join(bundleRoot, "dmg"); + fs.mkdirSync(appPath, { recursive: true }); + fs.mkdirSync(dmgDirectory, { recursive: true }); + fs.writeFileSync(path.join(dmgDirectory, rawName), `${target} fixture`); + return { appPath, dmgDirectory }; +} + +async function main() { + const scratch = fs.mkdtempSync( + path.join(os.tmpdir(), "rosi-macos-packages-"), + ); + try { + await scenario("MNP01", "native architecture mismatch is rejected", () => { + assertArchitectureCompatibility(["arm64"], "aarch64-apple-darwin"); + expectFailure( + () => + assertArchitectureCompatibility(["x86_64"], "aarch64-apple-darwin"), + /expected.*arm64/, + ); + expectFailure( + () => + assertArchitectureCompatibility( + ["arm64", "x86_64"], + "x86_64-apple-darwin", + ), + /expected.*x86_64/, + ); + return { nativeTargets: Object.keys(MACOS_TARGETS) }; + }); + + await scenario( + "MNP02", + "universal yt-dlp is valid for native targets", + () => { + assertArchitectureCompatibility( + ["x86_64", "arm64"], + "aarch64-apple-darwin", + { allowAdditional: true, label: "rosi-yt-dlp" }, + ); + expectFailure( + () => + assertArchitectureCompatibility( + ["x86_64"], + "aarch64-apple-darwin", + { allowAdditional: true, label: "rosi-yt-dlp" }, + ), + /expected to include.*arm64/, + ); + return { ytDlp: "universal2 allowed when requested slice exists" }; + }, + ); + + await scenario( + "MNP03", + "minimum macOS floor is checked per requested slice", + () => { + assertMinimumMacOSVersion("rosi-ffmpeg", "arm64", "14.0", "15.0"); + expectFailure( + () => + assertMinimumMacOSVersion("rosi-ffmpeg", "x86_64", "15.1", "15.0"), + /requires macOS 15\.1/, + ); + return { + floor: "15.0", + source: "fixture comparison through production guard", + }; + }, + ); + + await scenario( + "MNP04", + "signed-package acceptance requirements stay enforced", + () => { + const zipSource = fs.readFileSync( + path.join(root, "scripts", "zip-macos.js"), + "utf8", + ); + const zstdSource = fs.readFileSync( + path.join(root, "scripts", "pack-macos-updater-zst.js"), + "utf8", + ); + assert.match(zipSource, /codesign/); + assert.match(zipSource, /stapler.*validate/s); + assert.match(zipSource, /spctl/); + assert.match(zstdSource, /codesign/); + assert.match(zstdSource, /stapler.*validate/s); + return { + fixtureChecks: + "signing, staple validation, and Gatekeeper calls remain wired", + nativeAcceptance: + process.platform === "darwin" ? "not-run" : "blocked", + }; + }, + ); + + await scenario( + "MNP05", + "bundle versions must match the release configuration", + () => { + assertBundleVersions( + { bundleVersion: "5.1.3001", marketingVersion: "5.1.0" }, + { + expectedBundleVersion: "5.1.3001", + expectedMarketingVersion: "5.1.0", + }, + ); + expectFailure( + () => + assertBundleVersions( + { bundleVersion: "5.1.3001", marketingVersion: "5.0.9" }, + { + expectedBundleVersion: "5.1.3001", + expectedMarketingVersion: "5.1.0", + }, + ), + /CFBundleShortVersionString/, + ); + return { releaseVersion: pkg.version }; + }, + ); + + await scenario( + "MNP06", + "package naming and DMG normalization stay unique by target", + () => { + assert.equal( + macosPackageName("aarch64-apple-darwin", "dmg"), + "ROSI-MacOS-arm64.dmg", + ); + assert.equal( + macosPackageName("x86_64-apple-darwin", "zip"), + "ROSI-MacOS-x64.zip", + ); + assert.equal( + macosPackageName("universal-apple-darwin", "dmg"), + "ROSI-MacOS-universal.dmg", + ); + const arm = makeDmgFixture( + scratch, + "aarch64-apple-darwin", + "ROSI_5.1.0-beta.1_aarch64.dmg", + ); + const x64 = makeDmgFixture( + scratch, + "x86_64-apple-darwin", + "ROSI_5.1.0-beta.1_x64.dmg", + ); + const universal = makeDmgFixture( + scratch, + "universal-apple-darwin", + "ROSI_5.1.0-beta.1_universal.dmg", + ); + const armDmg = normalizeDmgPackage(arm.appPath, "aarch64-apple-darwin"); + const x64Dmg = normalizeDmgPackage(x64.appPath, "x86_64-apple-darwin"); + const universalDmg = normalizeDmgPackage( + universal.appPath, + "universal-apple-darwin", + ); + assert.equal(path.basename(armDmg), "ROSI-MacOS-arm64.dmg"); + assert.equal(path.basename(x64Dmg), "ROSI-MacOS-x64.dmg"); + assert.equal(path.basename(universalDmg), "ROSI-MacOS-universal.dmg"); + for (const dmgPath of [armDmg, x64Dmg, universalDmg]) { + assert.equal(fs.statSync(dmgPath).size > 0, true); + } + assert.equal( + packageOutputPath(arm.appPath, "aarch64-apple-darwin"), + path.join(path.dirname(arm.appPath), "ROSI-MacOS-arm64.zip"), + ); + const rebuiltRawDmg = path.join( + arm.dmgDirectory, + "ROSI_5.1.0-beta.1_aarch64-rebuilt.dmg", + ); + fs.writeFileSync(rebuiltRawDmg, "rebuilt arm64 fixture"); + normalizeDmgPackage(arm.appPath, "aarch64-apple-darwin"); + assert.equal(fs.readFileSync(armDmg, "utf8"), "rebuilt arm64 fixture"); + const ambiguous = makeDmgFixture( + scratch, + "ambiguous-apple-darwin", + "ROSI_5.1.0-beta.1_x64.dmg", + ); + fs.writeFileSync( + path.join(ambiguous.dmgDirectory, "second.dmg"), + "second", + ); + expectFailure( + () => normalizeDmgPackage(ambiguous.appPath, "x86_64-apple-darwin"), + /Expected one DMG/, + ); + return { + normalized: [ + path.basename(armDmg), + path.basename(x64Dmg), + path.basename(universalDmg), + ], + }; + }, + ); + + await scenario( + "MNP07", + "artifact collection preserves native names and signing eligibility", + () => { + const raw = path.join( + "src-tauri", + "target", + "aarch64-apple-darwin", + "release", + "bundle", + "dmg", + "ROSI_5.1.0-beta.1.dmg", + ); + assert.equal( + cleanArtifactName(path.basename(raw), raw), + "ROSI-MacOS-arm64.dmg", + ); + assert.equal( + cleanArtifactName("ROSI-MacOS-x64.zip"), + "ROSI-MacOS-x64.zip", + ); + for (const name of [ + "ROSI-MacOS-arm64.dmg", + "ROSI-MacOS-arm64.zip", + "ROSI-MacOS-x64.dmg", + "ROSI-MacOS-x64.zip", + ]) { + assert.equal(isArtifact(name), true, `${name} must be collected`); + assert.equal( + isSignable(name), + true, + `${name} must receive a GPG signature`, + ); + } + assert.equal(artifactMatchesVersion("ROSI-MacOS-arm64.dmg"), true); + const duplicateA = path.join( + scratch, + "aarch64-apple-darwin", + "first", + "ROSI_5.1.0-beta.1.dmg", + ); + const duplicateB = path.join( + scratch, + "aarch64-apple-darwin", + "second", + "ROSI_5.1.0-beta.1.dmg", + ); + fs.mkdirSync(path.dirname(duplicateA), { recursive: true }); + fs.mkdirSync(path.dirname(duplicateB), { recursive: true }); + fs.writeFileSync(duplicateA, "first"); + fs.writeFileSync(duplicateB, "second"); + expectFailure( + () => pickNewestByBasename([duplicateA, duplicateB]), + /Multiple current macOS package artifacts normalize to ROSI-MacOS-arm64\.dmg/, + ); + return { nativePackageCount: 4 }; + }, + ); + + await scenario( + "MNP08", + "draft verification requires all native and universal installers", + () => { + const required = requiredDraftAssetNames(); + const nativeInstallers = [ + "ROSI-MacOS-arm64.dmg", + "ROSI-MacOS-arm64.zip", + "ROSI-MacOS-x64.dmg", + "ROSI-MacOS-x64.zip", + ]; + for (const name of [ + ...nativeInstallers, + "ROSI-MacOS-universal.dmg", + "ROSI-MacOS-universal.zip", + ]) { + assert(required.includes(name), `${name} must be required`); + assert(requiredDraftInstallerNames().includes(name)); + assert(requiredDraftSidecarNames([name]).includes(`${name}.asc`)); + } + assertDraftReleaseShape({ + release: { draft: true, prerelease: true }, + assetNames: required, + version: pkg.version, + }); + expectFailure( + () => + assertDraftReleaseShape({ + release: { draft: true, prerelease: true }, + assetNames: required.filter( + (name) => name !== "ROSI-MacOS-arm64.zip", + ), + version: pkg.version, + }), + /ROSI-MacOS-arm64\.zip/, + ); + return { + requiredAssetCount: required.length, + missingAssetRejected: "ROSI-MacOS-arm64.zip", + }; + }, + ); + + await scenario( + "MNP09", + "each native package has a GPG signing rule", + () => { + for (const name of [ + "ROSI-MacOS-arm64.dmg", + "ROSI-MacOS-arm64.zip", + "ROSI-MacOS-x64.dmg", + "ROSI-MacOS-x64.zip", + ]) { + assert.equal( + isSignable(name), + true, + `${name} must receive a GPG signature`, + ); + assert(requiredDraftSidecarNames([name]).includes(`${name}.asc`)); + } + return { gpgSidecars: 4 }; + }, + ); + + await scenario( + "MNP10", + "checksum groups cover each package on its own architectures", + () => { + const packages = [ + "ROSI-MacOS-arm64.dmg", + "ROSI-MacOS-arm64.zip", + "ROSI-MacOS-x64.dmg", + "ROSI-MacOS-x64.zip", + "ROSI-MacOS-universal.dmg", + "ROSI-MacOS-universal.zip", + ]; + const channels = [ + { targetSuffix: "", baseUrl: "stable" }, + { targetSuffix: "-beta", baseUrl: "beta" }, + ]; + const groups = checksumGroupsForArtifacts(packages, channels); + const names = (target) => + new Set( + groups.get(target).map((filePath) => path.basename(filePath)), + ); + for (const target of ["darwin-aarch64", "darwin-beta-aarch64"]) { + assert(names(target).has("ROSI-MacOS-arm64.dmg")); + assert(names(target).has("ROSI-MacOS-arm64.zip")); + assert(names(target).has("ROSI-MacOS-universal.dmg")); + assert.equal(names(target).has("ROSI-MacOS-x64.dmg"), false); + } + for (const target of ["darwin-x86_64", "darwin-beta-x86_64"]) { + assert(names(target).has("ROSI-MacOS-x64.dmg")); + assert(names(target).has("ROSI-MacOS-x64.zip")); + assert(names(target).has("ROSI-MacOS-universal.zip")); + assert.equal(names(target).has("ROSI-MacOS-arm64.zip"), false); + } + assert.deepEqual( + checksumTargetKeysForArtifactName("ROSI-MacOS-arm64.zip", channels), + ["darwin-aarch64", "darwin-beta-aarch64"], + ); + return { checksumTargets: [...groups.keys()] }; + }, + ); + + await scenario( + "MNP11", + "updater manifests keep universal fallback and architecture-specific zstd feeds", + () => { + const universal = resolveUpdaterTargets("ROSI.app.tar.gz").sort( + (a, b) => a.arch.localeCompare(b.arch), + ); + assert.deepEqual( + universal.map(({ os: operatingSystem, arch, installer }) => ({ + operatingSystem, + arch, + installer, + })), + [ + { operatingSystem: "darwin", arch: "aarch64", installer: "app" }, + { operatingSystem: "darwin", arch: "x86_64", installer: "app" }, + ], + ); + assert.deepEqual(resolveUpdaterTargets("ROSI-aarch64.app.tar.zst"), [ + { os: "darwin", arch: "aarch64", installer: "app-zst" }, + ]); + assert.deepEqual(resolveUpdaterTargets("ROSI-x86_64.app.tar.zst"), [ + { os: "darwin", arch: "x86_64", installer: "app-zst" }, + ]); + assert.deepEqual(resolveUpdaterTargets("ROSI-MacOS-arm64.dmg"), []); + + const fixture = JSON.parse( + fs.readFileSync( + path.join( + root, + "testdata", + "updater", + "latest-darwin-aarch64-app-zst.json", + ), + "utf8", + ), + ); + assert.deepEqual( + validateManifestData(fixture, "latest-darwin-aarch64-app-zst.json"), + [], + ); + const wrongArch = structuredClone(fixture); + wrongArch.platforms["darwin-aarch64-app-zst"].url = + "https://github.com/BurntToasters/ROSI/releases/download/vfixture/ROSI-x86_64.app.tar.zst"; + assert( + validateManifestData( + wrongArch, + "latest-darwin-aarch64-app-zst.json", + ).some((problem) => problem.includes("does not match artifact")), + ); + return { + universalFeeds: 2, + zstdFeeds: 2, + signatureFixture: "valid shape", + }; + }, + ); + + await scenario( + "MNP12", + "release scripts reuse each native app build for DMG, ZIP, and zstd", + () => { + const scripts = pkg.scripts; + assert.match( + scripts["build:mac:arm64:prepared"], + /--target aarch64-apple-darwin --bundles dmg,app/, + ); + assert.match( + scripts["build:mac:x64:prepared"], + /--target x86_64-apple-darwin --bundles dmg,app/, + ); + assert.match( + scripts["build:mac:updater-arches:prepared"], + /build:mac:native:prepared/, + ); + assert.match( + scripts["release:mac:continue"], + /build:mac:zip:native.*build:mac:updater-zst.*--require-real-builds/, + ); + return { + preparedBuilds: ["aarch64-apple-darwin", "x86_64-apple-darwin"], + }; + }, + ); + + await scenario( + "MNP13", + "native packaging never claims macOS acceptance on Windows", + () => { + const status = process.platform === "darwin" ? "not-run" : "blocked"; + assert(["blocked", "not-run"].includes(status)); + return { hostPlatform: process.platform, nativeAcceptance: status }; + }, + ); + + await scenario( + "MNP14", + "release verification retains fallback and Rosetta coverage", + () => { + const scripts = pkg.scripts; + assert.match( + scripts["release:mac:continue"], + /e2e-updater-zst\.mjs --require-real-builds/, + ); + assert( + fs.existsSync(path.join(root, "scripts", "e2e-updater-zst.mjs")), + ); + return { + updaterE2e: + "universal fallback and Rosetta scenarios remain in the release gate", + }; + }, + ); + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } + + const nativeAcceptance = REQUIRE_REAL_BUILDS + ? checkRealBuilds() + : { + status: process.platform === "darwin" ? "not-run" : "blocked", + mode: "fixture-only", + reason: + process.platform === "darwin" + ? "Fixture E2E does not inspect release packages; pass --require-real-builds after the signed macOS builds." + : "macOS signing, notarization/stapling, DMG mounting, lipo/otool, and native app launch require the macOS release machine.", + packages: [], + checks: [], + cleanup: { status: "not-run", detachedMounts: [] }, + }; + const fixtureFailures = scenarios.filter((item) => !item.ok).length; + const nativeFailures = + REQUIRE_REAL_BUILDS && nativeAcceptance.status !== "passed" ? 1 : 0; + const evidenceNativeAcceptance = { + status: nativeAcceptance.status, + mode: nativeAcceptance.mode, + reason: nativeAcceptance.reason ?? "", + error: nativeAcceptance.error ?? "", + packages: nativeAcceptance.packages.map((record) => ({ + target: record.target, + arch: record.arch, + kind: record.kind, + name: record.name, + bytes: record.bytes, + sha256: record.sha256, + sourceBundle: record.sourceBundle, + smallerThanUniversal: record.smallerThanUniversal ?? null, + roundTrip: record.roundTrip ?? null, + mount: record.mount ?? null, + })), + checks: nativeAcceptance.checks, + cleanup: nativeAcceptance.cleanup, + }; + const evidenceIdentity = { + version: pkg.version, + hostPlatform: process.platform, + hostArch: process.arch, + scenarioResults: scenarios.map(({ id, title, ok }) => ({ id, title, ok })), + nativeAcceptance: evidenceNativeAcceptance, + }; + const report = { + schemaVersion: 1, + generatedAt: new Date().toISOString(), + version: pkg.version, + mode: REQUIRE_REAL_BUILDS ? "require-real-builds" : "fixture-only", + host: { platform: process.platform, arch: process.arch }, + failureModes: "e2e/macos-native-packages.failure-modes.md", + scenarios, + evidenceIdentity, + nativeAcceptance: { + ...nativeAcceptance, + requiredChecks: [ + "Current release-session package and source outputs for all three targets", + "Package and source bundle SHA-256 and byte counts", + "Native DMG and ZIP smaller than the universal equivalents", + "ZIP extraction preserves app tree, target architectures, signature, and staple", + "Mounted DMG contains the target app with matching tree, signature, and staple", + "Every mounted DMG detaches in finally", + ], + }, + summary: { + passed: scenarios.filter((item) => item.ok).length, + failed: fixtureFailures + nativeFailures, + fixtureFailures, + nativeFailures, + nativeAcceptance: nativeAcceptance.status, + evidenceSha256: crypto + .createHash("sha256") + .update(JSON.stringify(evidenceIdentity)) + .digest("hex"), + }, + }; + fs.mkdirSync(path.dirname(reportPath), { recursive: true }); + fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`); + const savedReport = JSON.parse(fs.readFileSync(reportPath, "utf8")); + const savedDigest = crypto + .createHash("sha256") + .update(JSON.stringify(savedReport.evidenceIdentity)) + .digest("hex"); + assert.equal(savedReport.summary.evidenceSha256, savedDigest); + console.log( + `e2e-macos-native-packages: ${report.summary.passed} passed, ${report.summary.failed} failed`, + ); + console.log( + `native macOS acceptance: ${nativeAcceptance.status} (${nativeAcceptance.mode})${nativeAcceptance.error ? `: ${nativeAcceptance.error}` : nativeAcceptance.reason ? `: ${nativeAcceptance.reason}` : ""}`, + ); + console.log( + `evidence: ${path.relative(root, reportPath).replaceAll("\\", "/")}`, + ); + if (report.summary.failed > 0) process.exitCode = 1; +} + +main().catch((error) => { + console.error( + `e2e-macos-native-packages: FAILED: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); +}); diff --git a/scripts/gpg-sign.js b/scripts/gpg-sign.js index d7195a09..d56bfe72 100644 --- a/scripts/gpg-sign.js +++ b/scripts/gpg-sign.js @@ -121,7 +121,7 @@ const ARTIFACT_RULES = [ ext(".flatpak"), rx(/\.appimage$/i), - rx(/^ROSI(?:-MacOS-universal)?\.zip$/i), + rx(/^ROSI(?:-MacOS-(?:universal|arm64|x64))?\.zip$/i), rx(/\.nsis\.zip$/i), rx(/\.app\.tar\.gz$/i), @@ -129,7 +129,7 @@ const ARTIFACT_RULES = [ rx(/\.appimage\.tar\.gz$/i), rx(/\.(?:exe|msi|dmg|flatpak|appimage)\.sig$/i), - rx(/^ROSI(?:-MacOS-universal)?\.zip\.sig$/i), + rx(/^ROSI(?:-MacOS-(?:universal|arm64|x64))?\.zip\.sig$/i), rx(/\.nsis\.zip\.sig$/i), rx(/\.tar\.(?:gz|zst)\.sig$/i), @@ -143,7 +143,7 @@ const SIGN_RULES = [ ext(".dmg"), ext(".flatpak"), rx(/\.appimage$/i), - rx(/^ROSI(?:-MacOS-universal)?\.zip$/i), + rx(/^ROSI(?:-MacOS-(?:universal|arm64|x64))?\.zip$/i), rx(/\.nsis\.zip$/i), rx(/\.app\.tar\.gz$/i), rx(/\.app\.tar\.zst$/i), @@ -276,7 +276,7 @@ function clearPreStagedUpdaterManifests() { function pickNewestByBasename(paths) { const latest = new Map(); for (const filePath of paths) { - const name = path.basename(filePath); + const name = cleanArtifactName(path.basename(filePath), filePath); let stat; try { stat = fs.statSync(filePath); @@ -284,6 +284,14 @@ function pickNewestByBasename(paths) { continue; } const current = latest.get(name); + if ( + current && + /^ROSI-MacOS-(?:universal|arm64|x64)\.(?:dmg|zip)$/i.test(name) + ) { + throw new Error( + `Multiple current macOS package artifacts normalize to ${name}: ${current.filePath}, ${filePath}`, + ); + } if (!current || stat.mtimeMs > current.mtimeMs) { latest.set(name, { filePath, mtimeMs: stat.mtimeMs }); } @@ -317,12 +325,42 @@ function walk(dir, results = []) { return results; } -function cleanArtifactBaseName(name) { +function inferMacosPackageArch(name, filePath = "") { + const canonical = name.match( + /^ROSI-MacOS-(universal|arm64|x64)\.(?:dmg|zip)$/i, + ); + if (canonical) return canonical[1].toLowerCase(); + + const source = `${name} ${filePath}`; + if (/universal-apple-darwin|(?:^|[-_.])universal(?:[-_.]|$)/i.test(source)) { + return "universal"; + } + if ( + /aarch64-apple-darwin|(?:^|[-_.])(?:aarch64|arm64)(?:[-_.]|$)/i.test(source) + ) { + return "arm64"; + } + if ( + /x86_64-apple-darwin|(?:^|[-_.])(?:x86_64|amd64|x64)(?:[-_.]|$)/i.test( + source, + ) + ) { + return "x64"; + } + // Old universal outputs named ROSI.dmg/ROSI.zip have no architecture token. + return "universal"; +} + +function cleanArtifactBaseName(name, filePath = "") { if (/\.tar\.(?:gz|zst)$/i.test(name)) return name; if (/\.nsis\.zip$/i.test(name)) return name; - if (/\.dmg$/i.test(name)) return "ROSI-MacOS-universal.dmg"; - if (/^ROSI\.zip$/i.test(name)) return "ROSI-MacOS-universal.zip"; + if (/\.dmg$/i.test(name)) { + return `ROSI-MacOS-${inferMacosPackageArch(name, filePath)}.dmg`; + } + if (/^ROSI\.zip$/i.test(name)) { + return `ROSI-MacOS-${inferMacosPackageArch(name, filePath)}.zip`; + } if (/x64-setup\.exe$/i.test(name)) return "ROSI-Windows-x64.exe"; if (/arm64-setup\.exe$/i.test(name)) return "ROSI-Windows-arm64.exe"; @@ -337,13 +375,13 @@ function cleanArtifactBaseName(name) { return name; } -function cleanArtifactName(name) { +function cleanArtifactName(name, filePath = "") { if (name === "latest.json") return name; if (name.endsWith(".sig")) { const base = name.slice(0, -4); - return `${cleanArtifactBaseName(base)}.sig`; + return `${cleanArtifactBaseName(base, filePath)}.sig`; } - return cleanArtifactBaseName(name); + return cleanArtifactBaseName(name, filePath); } // Installers that only custom-target clients request, on every channel. They @@ -673,6 +711,24 @@ function checksumTargetKeysForArtifactName( if (manifestKey) return [manifestKey]; const baseName = name.endsWith(".sig") ? name.slice(0, -4) : name; + const macosPackage = baseName.match( + /^ROSI-MacOS-(universal|arm64|x64)\.(?:dmg|zip)$/i, + ); + if (macosPackage) { + const arches = + macosPackage[1].toLowerCase() === "universal" + ? ["x86_64", "aarch64"] + : [macosPackage[1].toLowerCase() === "arm64" ? "aarch64" : "x86_64"]; + return Array.from( + new Set( + arches.flatMap((arch) => + channelVariants.map( + (channel) => `darwin${channel.targetSuffix}-${arch}`, + ), + ), + ), + ); + } return Array.from( new Set( resolveUpdaterTargets(baseName).flatMap((target) => @@ -684,11 +740,47 @@ function checksumTargetKeysForArtifactName( ); } +function checksumGroupsForArtifacts( + files, + channelVariants = updaterChannelVariants(IS_PRERELEASE), +) { + const candidates = files.filter((filePath) => { + const name = path.basename(filePath); + return !name.endsWith(".asc") && !isChecksumTextName(name); + }); + const manifestTargetKeys = Array.from( + new Set( + candidates + .map((filePath) => parseManifestTargetKey(path.basename(filePath))) + .filter(Boolean), + ), + ); + const buckets = new Map(); + for (const filePath of candidates) { + const name = path.basename(filePath); + let targetKeys = checksumTargetKeysForArtifactName(name, channelVariants); + if (targetKeys.length === 0 && manifestTargetKeys.length > 0) { + targetKeys = manifestTargetKeys; + } + if (targetKeys.length === 0) targetKeys = ["generic"]; + for (const targetKey of targetKeys) { + if (!buckets.has(targetKey)) buckets.set(targetKey, []); + buckets.get(targetKey).push(filePath); + } + } + return new Map( + Array.from(buckets, ([key, values]) => [ + key, + Array.from(new Set(values)), + ]).sort(([left], [right]) => left.localeCompare(right)), + ); +} + function normalizePreStagedArtifacts(staged) { const selected = new Map(); for (const filePath of staged) { const originalName = path.basename(filePath); - const cleanName = cleanArtifactName(originalName); + const cleanName = cleanArtifactName(originalName, filePath); let stat; try { stat = fs.statSync(filePath); @@ -747,7 +839,7 @@ function collectArtifacts() { const collected = []; for (const src of selected) { const originalName = path.basename(src); - const cleanName = cleanArtifactName(originalName); + const cleanName = cleanArtifactName(originalName, src); const dest = path.join(releaseDir, cleanName); fs.copyFileSync(src, dest); if (cleanName !== originalName) { @@ -811,41 +903,8 @@ function sha256(filePath) { } function generateChecksums(files) { - const candidates = files.filter((f) => { - const name = path.basename(f); - return !name.endsWith(".asc") && !isChecksumTextName(name); - }); const channelVariants = updaterChannelVariants(IS_PRERELEASE); - - const manifestTargetKeys = Array.from( - new Set( - candidates - .map((f) => parseManifestTargetKey(path.basename(f))) - .filter(Boolean), - ), - ); - - const buckets = new Map(); - const addToBucket = (targetKey, filePath) => { - if (!buckets.has(targetKey)) { - buckets.set(targetKey, []); - } - buckets.get(targetKey).push(filePath); - }; - - for (const filePath of candidates) { - const name = path.basename(filePath); - let targetKeys = checksumTargetKeysForArtifactName(name, channelVariants); - if (targetKeys.length === 0 && manifestTargetKeys.length > 0) { - targetKeys = manifestTargetKeys; - } - if (targetKeys.length === 0) { - targetKeys = ["generic"]; - } - for (const targetKey of targetKeys) { - addToBucket(targetKey, filePath); - } - } + const buckets = checksumGroupsForArtifacts(files, channelVariants); const outputs = []; for (const targetKey of Array.from(buckets.keys()).sort()) { @@ -1746,6 +1805,9 @@ export { assertReleaseTargetsCommit, buildUploadList, checksumTargetKeysForArtifactName, + checksumGroupsForArtifacts, + pickNewestByBasename, + isSignable, isChecksumTextName, isDirectExecution, isExplicitTruthy, diff --git a/scripts/test-e2e.js b/scripts/test-e2e.js index 82b19761..226803c4 100644 --- a/scripts/test-e2e.js +++ b/scripts/test-e2e.js @@ -22,111 +22,130 @@ import { import { usesWindowsCmdShell } from "./npm-safe-update.mjs"; const ARTIFACT_DIR = path.join(REPO_ROOT, "e2e", "artifacts"); -export const EXPECTED_SCENARIOS = [ - "legacy-v4-import", - "legacy-v4-corrupt-settings", - "launch", - "legacy-v4-preserve", - "settings-sidebar", - "settings-persistence", - "download-profiles", - "settings-layout", - "flat-ui-tokens", - "window-theme", - "no-overscroll", - "sidebar-glass", - "url-safety", - "loopback-exception-and-thumbnail-data", - "loopback-download", - "proxy-delayed-http-response", - "proxy-cancels-streamed-response", - "private-dns-alias", - "dns-rebinding-connection-time", - "redirect-and-extractor-handoffs", - "verified-https-connect-proxy", - "untrusted-https-certificate-rejected", - "credential-bearing-urls", - "guarded-hls-fragments", - "bracketed-ipv6-classification", - "proxy-cancellation-closes-active-sockets", - "thumbnail-fetch-cancellation", - "dns-cancellation-reserved-ipc", - "proxy-rejects-unreviewed-pipelined-destination", - "bounded-dns-cancellation", - "persisted-offline-queue", - "manual-download", - "unicode-download", - "queue", - "cancel", - "conversion", - "audio-extract", - "gpu-detect", - "licenses", - "navigation-guard", - "preview", - "formats", - "merge-download", - "queue-management", - "queue-cancel", - "dock-tabs", - "webview-guard", - "link-drop", - "small-window", - "dock-empty", - "save-path", - "lucide-icons", - "status-icons", - "console-log", - "activity-actions", - "activity-action-clicks", - "theme-contrast", - "setup-wizard", - "setup-wizard-skip", - "setup-wizard-escape", - "setup-wizard-small", - "setup-wizard-deno", - "browser-choice", - "xdg-download-dir", - "ui-screenshots", - "stats", - "settings-search-reset", - "settings-controls", - "settings-reset-all", - "settings-response-revision", - "settings-rejection-preserves-newer-field", - "settings-lifecycle-latest-revision", - "settings-captured-wizard-deno", - "compatible-profile-wording", - "guarded-preview-thumbnail", - "queue-latest-snapshot", - "updater-generation-retry", - "queue-flush-backup-failure", - "close-pending-timeout", - "download-session-isolation", - "external-links", - "menu-actions", - "update-check", - "dialogs", - "download-card-input", - "presets", - "custom-formats", - "playlist-range", - "embed-extras", - "queue-controls", - "save-location", - "notifications", - "download-again-quickly", - "download-process-repairs", - "activity-clear", - "close-flow", - "round2-renderer", - "round2-native", - "long-term-persistence", - "audit3-native-targeted", - "audit4-repairs", - "audit-v5-beta2", - "round3-renderer-repairs", -]; +const SUITE_MANIFEST_PATH = path.join(REPO_ROOT, "e2e", "suites.json"); +export const E2E_SUITE_MANIFEST = JSON.parse( + fs.readFileSync(SUITE_MANIFEST_PATH, "utf8"), +); + +function validateSuiteManifest(manifest) { + if (manifest?.schemaVersion !== 1) { + throw new Error("e2e/suites.json has an unsupported schemaVersion"); + } + if (!Array.isArray(manifest.scenarios) || !Array.isArray(manifest.groups)) { + throw new Error("e2e/suites.json must define scenarios and groups arrays"); + } + const ownerIds = new Set(Object.keys(manifest.owners ?? {})); + const groupIds = new Set(); + for (const group of manifest.groups) { + if (!group?.id || groupIds.has(group.id)) { + throw new Error( + `e2e/suites.json has a missing or duplicate group id: ${group?.id}`, + ); + } + groupIds.add(group.id); + if (!Array.isArray(group.owners) || !Array.isArray(group.v5FixAreas)) { + throw new Error( + `e2e/suites.json group ${group.id} has invalid owner or area lists`, + ); + } + for (const owner of group.owners) { + if (!ownerIds.has(owner)) { + throw new Error( + `e2e/suites.json group ${group.id} has unknown owner ${owner}`, + ); + } + } + if (group.v5FixAreas.some((area) => typeof area !== "string" || !area)) { + throw new Error( + `e2e/suites.json group ${group.id} has an invalid v5-fixes area`, + ); + } + } + const names = new Set(); + for (const scenario of manifest.scenarios) { + if (!scenario?.name || names.has(scenario.name)) { + throw new Error( + `e2e/suites.json has a missing or duplicate scenario: ${scenario?.name}`, + ); + } + names.add(scenario.name); + if (!groupIds.has(scenario.feature) || !ownerIds.has(scenario.owner)) { + throw new Error( + `e2e/suites.json scenario ${scenario.name} has an unknown feature or owner`, + ); + } + if (!Array.isArray(scenario.allowedSkips)) { + throw new Error( + `e2e/suites.json scenario ${scenario.name} has invalid skip allowances`, + ); + } + if ( + scenario.allowedSkips.some( + (platform) => !["darwin", "linux", "win32"].includes(platform), + ) + ) { + throw new Error( + `e2e/suites.json scenario ${scenario.name} has an unknown platform allowance`, + ); + } + } + const areaGroups = manifest.dynamicV5Fixes?.groupAreas ?? {}; + const mappedAreas = new Set(); + for (const [groupId, areas] of Object.entries(areaGroups)) { + const group = manifest.groups.find((candidate) => candidate.id === groupId); + if (!group || !Array.isArray(areas)) { + throw new Error( + `e2e/suites.json has invalid dynamic area mapping for ${groupId}`, + ); + } + for (const area of areas) { + if (mappedAreas.has(area) || !group.v5FixAreas.includes(area)) { + throw new Error( + `e2e/suites.json has duplicate or inconsistent v5-fixes mapping: ${area}`, + ); + } + mappedAreas.add(area); + } + } + for (const group of manifest.groups) { + const scenarioOwners = new Set( + manifest.scenarios + .filter((scenario) => scenario.feature === group.id) + .map((scenario) => scenario.owner), + ); + if ([...scenarioOwners].some((owner) => !group.owners.includes(owner))) { + throw new Error( + `e2e/suites.json group ${group.id} omits a scenario owner`, + ); + } + for (const area of group.v5FixAreas) { + if (!mappedAreas.has(area)) { + throw new Error( + `e2e/suites.json group ${group.id} has unmapped v5-fixes area ${area}`, + ); + } + } + } + if (!ownerIds.has(manifest.dynamicV5Fixes?.owner)) { + throw new Error("e2e/suites.json has an unknown dynamic v5-fixes owner"); + } + for (const group of manifest.groups) { + if ( + group.v5FixAreas.length > 0 && + !group.owners.includes(manifest.dynamicV5Fixes.owner) + ) { + throw new Error( + `e2e/suites.json group ${group.id} omits its dynamic v5-fixes owner`, + ); + } + } +} + +validateSuiteManifest(E2E_SUITE_MANIFEST); + +export const EXPECTED_SCENARIOS = E2E_SUITE_MANIFEST.scenarios.map( + (scenario) => scenario.name, +); export const ROUND2_RENDERER_OBSERVATIONS = Object.freeze([ "renderer-startup-settings-ready", "updater-channel-and-singleflight", @@ -146,12 +165,42 @@ export const ROUND2_NATIVE_OBSERVATIONS = Object.freeze([ "download-retry-cleans-staging", "windows-job-object-leader-exit", ]); -export const ALLOWED_E2E_SKIPS = Object.freeze({ - "download-process-repairs": Object.freeze(["win32"]), - "audit3-native-targeted": Object.freeze(["win32"]), - "audit-v5-beta2": Object.freeze(["linux", "win32"]), - "xdg-download-dir": Object.freeze(["darwin", "win32"]), -}); +export const ALLOWED_E2E_SKIPS = Object.freeze( + Object.fromEntries( + E2E_SUITE_MANIFEST.scenarios + .filter((scenario) => scenario.allowedSkips.length > 0) + .map((scenario) => [scenario.name, Object.freeze(scenario.allowedSkips)]), + ), +); + +function groupedScenarioResults(scenarios, expectedScenarios) { + const expected = new Set(expectedScenarios); + const dynamicGroups = E2E_SUITE_MANIFEST.dynamicV5Fixes.groupAreas; + return Object.fromEntries( + E2E_SUITE_MANIFEST.groups.map((group) => { + const groupNames = [ + ...E2E_SUITE_MANIFEST.scenarios + .filter((scenario) => scenario.feature === group.id) + .map((scenario) => scenario.name), + ...(dynamicGroups[group.id] ?? []).map((area) => `v5-fixes/${area}`), + ].filter((name) => expected.has(name)); + const reported = scenarios.filter((scenario) => + groupNames.includes(scenario?.name), + ); + const reportedNames = new Set(reported.map((scenario) => scenario.name)); + return [ + group.id, + { + expectedScenarios: groupNames, + reportedScenarios: reported, + missingScenarios: groupNames.filter( + (name) => !reportedNames.has(name), + ), + }, + ]; + }), + ); +} export function scenarioOutcomeProblems( scenarios, @@ -468,17 +517,67 @@ export function e2eOnlySpec(value) { return spec === "" ? null : spec; } +/** Read one or more manifest feature groups from CLI arguments or the env. */ +export function parseE2eGroups(argv, env = process.env) { + const fromArgs = []; + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (argument === "--group") { + const value = argv[index + 1]; + if (!value || value.startsWith("--")) { + throw new Error("--group needs a comma-separated feature group list"); + } + fromArgs.push(value); + index += 1; + } else if (argument.startsWith("--group=")) { + const value = argument.slice("--group=".length); + if (value.trim() === "") { + throw new Error("--group needs a comma-separated feature group list"); + } + fromArgs.push(value); + } + } + const rawGroups = + fromArgs.length > 0 ? fromArgs : [env.ROSI_E2E_GROUPS ?? ""]; + const groups = rawGroups.flatMap((value) => value.split(",")); + const normalized = groups.map((group) => group.trim()).filter(Boolean); + if (new Set(normalized).size !== normalized.length) { + throw new Error("E2E feature groups must not be listed more than once"); + } + return normalized; +} + /** True for specs under e2e/v5-fixes/, which report through their own files. */ export function isV5FixesSpec(spec) { return /^(\.\/)?v5-fixes\//.test((spec ?? "").replace(/\\/g, "/")); } /** - * The full gate keeps the complete inventory. An ad-hoc ROSI_E2E_ONLY run - * names no suites and is always partial, so its report cannot pass as proof. + * The full gate keeps the complete inventory. Ad-hoc specs and manifest group + * selections are always partial, so neither report can pass as release proof. */ -export function e2eRunPlan({ onlySpec, v5AreaNames = [] }) { - if (onlySpec === null) { +export function e2eRunPlan({ + onlySpec, + v5AreaNames = [], + selectedGroups = [], +}) { + if (onlySpec !== null && selectedGroups.length > 0) { + throw new Error( + "ROSI_E2E_ONLY cannot be combined with --group or ROSI_E2E_GROUPS", + ); + } + const mappedV5Areas = new Set( + Object.values(E2E_SUITE_MANIFEST.dynamicV5Fixes.groupAreas).flat(), + ); + const ungroupedV5Areas = v5AreaNames.filter( + (area) => !mappedV5Areas.has(area), + ); + if (ungroupedV5Areas.length > 0) { + throw new Error( + `v5-fixes area(s) need a feature group in e2e/suites.json: ${ungroupedV5Areas.join(", ")}`, + ); + } + if (onlySpec === null && selectedGroups.length === 0) { return { fullSuite: true, mainSpecs: "./specs/main.spec.js", @@ -486,9 +585,62 @@ export function e2eRunPlan({ onlySpec, v5AreaNames = [] }) { ...EXPECTED_SCENARIOS, ...v5AreaNames.map((area) => `v5-fixes/${area}`), ], + enabledOwners: Object.keys(E2E_SUITE_MANIFEST.owners), + selectedGroups: [], + v5AreaNames, }; } - return { fullSuite: false, mainSpecs: onlySpec, expectedScenarios: [] }; + if (onlySpec !== null) { + return { + fullSuite: false, + mainSpecs: onlySpec, + expectedScenarios: [], + enabledOwners: [], + selectedGroups: [], + v5AreaNames: [], + }; + } + + const groupsById = new Map( + E2E_SUITE_MANIFEST.groups.map((group) => [group.id, group]), + ); + const unknownGroups = selectedGroups.filter( + (group) => !groupsById.has(group), + ); + if (unknownGroups.length > 0) { + throw new Error( + `unknown E2E feature group(s): ${unknownGroups.join(", ")}`, + ); + } + const selected = selectedGroups.map((id) => groupsById.get(id)); + const enabledOwners = new Set(selected.flatMap((group) => group.owners)); + const requiredV5Areas = new Set( + selected.flatMap((group) => group.v5FixAreas), + ); + const selectedV5Areas = v5AreaNames.filter((area) => + requiredV5Areas.has(area), + ); + const missingV5Areas = [...requiredV5Areas].filter( + (area) => !v5AreaNames.includes(area), + ); + if (missingV5Areas.length > 0) { + throw new Error( + `selected E2E feature group(s) require missing v5-fixes area(s): ${missingV5Areas.join(", ")}`, + ); + } + return { + fullSuite: false, + mainSpecs: "./specs/main.spec.js", + expectedScenarios: [ + ...E2E_SUITE_MANIFEST.scenarios + .filter((scenario) => enabledOwners.has(scenario.owner)) + .map((scenario) => scenario.name), + ...selectedV5Areas.map((area) => `v5-fixes/${area}`), + ], + enabledOwners: [...enabledOwners], + selectedGroups, + v5AreaNames: selectedV5Areas, + }; } /** @@ -1546,6 +1698,18 @@ async function main() { ); } const onlySpec = e2eOnlySpec(process.env.ROSI_E2E_ONLY); + const selectedGroups = parseE2eGroups(process.argv.slice(2), process.env); + const availableV5Areas = onlySpec ? [] : discoverV5Fixes(); + const runPlan = e2eRunPlan({ + onlySpec, + selectedGroups, + v5AreaNames: availableV5Areas.map((area) => area.area), + }); + const v5Areas = availableV5Areas.filter((area) => + runPlan.v5AreaNames.includes(area.area), + ); + const ownerEnabled = (owner) => + runPlan.fullSuite || runPlan.enabledOwners.includes(owner); // Set before any launch so every pass, runner and probe inherits it. const background = e2eBackgroundValue({ env: process.env, @@ -1558,7 +1722,7 @@ async function main() { const reuseRequested = process.env.ROSI_E2E_REUSE === "1"; if ( !mayReuseE2eBinary({ - onlySpec: Boolean(onlySpec), + onlySpec: Boolean(onlySpec) && selectedGroups.length === 0, reuseRequested, binaryFresh: !reuseRequested || e2eBinaryIsFresh(), }) @@ -1702,20 +1866,21 @@ async function main() { // Fresh ROSI 5 profiles with ROSI 4 data beside them, each a separate app // launch because the import only runs before the first settings file. - // ROSI_E2E_ONLY runs one ad-hoc spec, so it skips these passes. - const legacyPasses = onlySpec - ? [] - : ["import", "corrupt-settings"].map((legacyCase) => { - const legacyProfile = createE2eProfile({ seedSettings: false }); - return { - legacyCase, - profile: legacyProfile, - seed: seedLegacyV4Data(legacyProfile, { - corruptSettings: legacyCase === "corrupt-settings", - }), - resultsPath: path.join(legacyProfile.profileDir, "results.json"), - }; - }); + // Ad-hoc and group runs include only their selected owner passes. + const legacyPasses = + onlySpec || !ownerEnabled("legacy-import") + ? [] + : ["import", "corrupt-settings"].map((legacyCase) => { + const legacyProfile = createE2eProfile({ seedSettings: false }); + return { + legacyCase, + profile: legacyProfile, + seed: seedLegacyV4Data(legacyProfile, { + corruptSettings: legacyCase === "corrupt-settings", + }), + resultsPath: path.join(legacyProfile.profileDir, "results.json"), + }; + }); const mainPass = { profile, // The main profile already has ROSI 5 settings, so this ROSI 4 folder @@ -1730,91 +1895,90 @@ async function main() { // Security downloads intentionally populate stats/activity and can exercise // renderer state that the main UI suite expects to start fresh. Keep the // security proof in its own profile while aggregating both result files. - const securityPass = onlySpec - ? null - : (() => { - const securityProfile = createE2eProfile({ - ffmpegPath: ffmpeg?.customPath ?? "", - }); - return { - profile: securityProfile, - resultsPath: path.join( - securityProfile.profileDir, - "security-repairs-results.json", - ), - }; - })(); + const securityPass = + onlySpec || !ownerEnabled("security") + ? null + : (() => { + const securityProfile = createE2eProfile({ + ffmpegPath: ffmpeg?.customPath ?? "", + }); + return { + profile: securityProfile, + resultsPath: path.join( + securityProfile.profileDir, + "security-repairs-results.json", + ), + }; + })(); // State-repair close-failure scenarios deliberately leave native warning // dialogs open. Run them in their own profile before the security and main // specs, whose final close-flow scenario closes this app window. - const stateRepairPass = onlySpec - ? null - : (() => { - const stateProfile = createE2eProfile({ - ffmpegPath: ffmpeg?.customPath ?? "", - }); - return { - profile: stateProfile, - resultsPath: path.join( - stateProfile.profileDir, - "state-repairs-results.json", - ), - }; - })(); - const offlineQueuePass = onlySpec - ? null - : (() => { - const offlineProfile = createE2eProfile({ - ffmpegPath: ffmpeg?.customPath ?? "", - }); - fs.writeFileSync( - path.join(offlineProfile.dataDir, "download-queue.json"), - `${JSON.stringify( - [ - { - id: "offline-dns-queue", - url: "http://offline-repair.invalid/video.mp4", - status: "pending", - addedAt: Date.now(), - request: null, - }, - ], - null, - 2, - )}\n`, - ); - return { - profile: offlineProfile, - resultsPath: path.join( - offlineProfile.profileDir, - "offline-queue-results.json", - ), - }; - })(); - const round2RendererPass = onlySpec - ? null - : (() => { - const rendererProfile = createE2eProfile({ - ffmpegPath: ffmpeg?.customPath ?? "", - }); - const resultsDirectory = path.join( - ARTIFACT_DIR, - "round2-renderer", - `${process.platform}-${process.arch}`, - ); - fs.mkdirSync(resultsDirectory, { recursive: true }); - const runId = `${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`; - const resultsPath = path.join(resultsDirectory, `${runId}.json`); - fs.rmSync(resultsPath, { force: true }); - return { profile: rendererProfile, resultsPath }; - })(); + const stateRepairPass = + onlySpec || !ownerEnabled("state-repairs") + ? null + : (() => { + const stateProfile = createE2eProfile({ + ffmpegPath: ffmpeg?.customPath ?? "", + }); + return { + profile: stateProfile, + resultsPath: path.join( + stateProfile.profileDir, + "state-repairs-results.json", + ), + }; + })(); + const offlineQueuePass = + onlySpec || !ownerEnabled("offline-queue") + ? null + : (() => { + const offlineProfile = createE2eProfile({ + ffmpegPath: ffmpeg?.customPath ?? "", + }); + fs.writeFileSync( + path.join(offlineProfile.dataDir, "download-queue.json"), + `${JSON.stringify( + [ + { + id: "offline-dns-queue", + url: "http://offline-repair.invalid/video.mp4", + status: "pending", + addedAt: Date.now(), + request: null, + }, + ], + null, + 2, + )}\n`, + ); + return { + profile: offlineProfile, + resultsPath: path.join( + offlineProfile.profileDir, + "offline-queue-results.json", + ), + }; + })(); + const round2RendererPass = + onlySpec || !ownerEnabled("round2-renderer") + ? null + : (() => { + const rendererProfile = createE2eProfile({ + ffmpegPath: ffmpeg?.customPath ?? "", + }); + const resultsDirectory = path.join( + ARTIFACT_DIR, + "round2-renderer", + `${process.platform}-${process.arch}`, + ); + fs.mkdirSync(resultsDirectory, { recursive: true }); + const runId = `${new Date().toISOString().replace(/[:.]/g, "-")}-${process.pid}`; + const resultsPath = path.join(resultsDirectory, `${runId}.json`); + fs.rmSync(resultsPath, { force: true }); + return { profile: rendererProfile, resultsPath }; + })(); // Each e2e/v5-fixes// with *.spec.js and no run.mjs gets its own fresh // profile. Areas that skip or focus tests fail before WebdriverIO starts. - const v5Areas = onlySpec ? [] : discoverV5Fixes(); - const runPlan = e2eRunPlan({ - onlySpec, - v5AreaNames: v5Areas.map((area) => area.area), - }); // Runner-owned areas (run.mjs) get no generic wdio pass; the runner drives // their specs. const v5Passes = v5Areas @@ -1889,16 +2053,18 @@ async function main() { pass.status = "failed"; } } - await runPass(mainPass, { - // ROSI_E2E_ONLY runs a single ad-hoc spec while debugging; the full - // gate always runs main.spec.js and requires every scenario. - ROSI_E2E_SPECS: runPlan.mainSpecs, - // Preserve this path for ROSI_E2E_ONLY debugging when the selected spec - // is the state-repair suite. The full gate uses the isolated pass above. - ROSI_STATE_REPAIR_RESULTS: mainPass.stateRepairResultsPath, - ROSI_E2E_LEGACY_V4: JSON.stringify(mainPass.seed), - ROSI_E2E_SCREENSHOTS: screenshotDir, - }); + if (onlySpec || ownerEnabled("main")) { + await runPass(mainPass, { + // ROSI_E2E_ONLY runs a single ad-hoc spec while debugging; the full + // gate always runs main.spec.js and requires every scenario. + ROSI_E2E_SPECS: runPlan.mainSpecs, + // Preserve this path for ROSI_E2E_ONLY debugging when the selected spec + // is the state-repair suite. The full gate uses the isolated pass above. + ROSI_STATE_REPAIR_RESULTS: mainPass.stateRepairResultsPath, + ROSI_E2E_LEGACY_V4: JSON.stringify(mainPass.seed), + ROSI_E2E_SCREENSHOTS: screenshotDir, + }); + } } catch (error) { failure = error instanceof Error ? error.message : String(error); } finally { @@ -1907,45 +2073,52 @@ async function main() { // Both specs share one isolated wrapper, which is the only code that starts // WebdriverIO with the process-level probe fixtures. - const processRepairScenarios = onlySpec - ? [] - : [ - runDownloadProcessRepairs({ - ffmpeg, - binary: e2eBinaryPath(), - suiteStartedAt: startedAt, - }), - runDownloadProcessRepairs({ - ffmpeg, - binary: e2eBinaryPath(), - suiteStartedAt: startedAt, - name: "audit3-native-targeted", - spec: "./audit3-native-targeted.spec.js", - }), - ]; - const round2NativeScenarios = onlySpec - ? [] - : [ - runRound2NativeRepairs({ - ffmpeg, - binary: e2eBinaryPath(), - suiteStartedAt: startedAt, - }), - ]; + const processRepairScenarios = + onlySpec || !ownerEnabled("process-repairs") + ? [] + : [ + runDownloadProcessRepairs({ + ffmpeg, + binary: e2eBinaryPath(), + suiteStartedAt: startedAt, + }), + runDownloadProcessRepairs({ + ffmpeg, + binary: e2eBinaryPath(), + suiteStartedAt: startedAt, + name: "audit3-native-targeted", + spec: "./audit3-native-targeted.spec.js", + }), + ]; + const round2NativeScenarios = + onlySpec || !ownerEnabled("round2-native") + ? [] + : [ + runRound2NativeRepairs({ + ffmpeg, + binary: e2eBinaryPath(), + suiteStartedAt: startedAt, + }), + ]; const round2RendererScenarios = round2RendererPass ? [round2RendererScenario(round2RendererPass, round2RendererFailure)] : []; - const persistenceScenarios = onlySpec - ? [] - : [runLongTermPersistenceRepairs()]; + const persistenceScenarios = + onlySpec || !ownerEnabled("persistence") + ? [] + : [runLongTermPersistenceRepairs()]; const binary = e2eBinaryPath(); const auditScenarios = onlySpec ? [] : [ - runAudit4Repairs({ ffmpeg, binary, suiteStartedAt: startedAt }), - runAuditV5Probes({ ffmpeg, binary, suiteStartedAt: startedAt }), - runRound3Renderer(), - ...v5Areas.map((area) => { + ...(ownerEnabled("audit4-repairs") + ? [runAudit4Repairs({ ffmpeg, binary, suiteStartedAt: startedAt })] + : []), + ...(ownerEnabled("audit-v5-beta2") + ? [runAuditV5Probes({ ffmpeg, binary, suiteStartedAt: startedAt })] + : []), + ...(ownerEnabled("round3-renderer") ? [runRound3Renderer()] : []), + ...(ownerEnabled("v5-fixes") ? v5Areas : []).map((area) => { const pass = v5Passes.find((candidate) => candidate.area === area); const runnerResult = area.runner ? runV5FixesRunner(area, binary, ffmpeg) @@ -1988,7 +2161,7 @@ async function main() { ...(offlineQueuePass ? [offlineQueuePass] : []), ...(stateRepairPass ? [stateRepairPass] : []), ...(securityPass ? [securityPass] : []), - mainPass, + ...(onlySpec || ownerEnabled("main") ? [mainPass] : []), ].flatMap((pass) => [ ...readResults(pass.resultsPath), ...(pass === mainPass && !stateRepairPass @@ -2009,11 +2182,13 @@ async function main() { }, ]), ); - const uncovered = onlySpec - ? [] - : Object.entries(legacyImportCoverage) + const checksLegacyImportCoverage = + fullSuite || runPlan.enabledOwners.includes("legacy-import"); + const uncovered = checksLegacyImportCoverage + ? Object.entries(legacyImportCoverage) .filter(([, mode]) => mode.coveredBy.length === 0) - .map(([id]) => id); + .map(([id]) => id) + : []; const { screenshots, problems: screenshotProblems } = verifyScreenshots( scenarios, screenshotDir, @@ -2021,18 +2196,25 @@ async function main() { const packageJson = JSON.parse( fs.readFileSync(path.join(REPO_ROOT, "package.json"), "utf8"), ); - const scenarioProblems = fullSuite - ? scenarioOutcomeProblems(scenarios, process.platform, expectedScenarios) - : onlyRunScenarioProblems({ - onlySpec, - scenarios, - platform: process.platform, - }); + const scenarioProblems = + fullSuite || selectedGroups.length > 0 + ? scenarioOutcomeProblems(scenarios, process.platform, expectedScenarios) + : onlyRunScenarioProblems({ + onlySpec, + scenarios, + platform: process.platform, + }); const evidence = writeEvidence({ app: "ROSI", fullSuite, // Present only on partial runs, so full-gate evidence keeps its shape. ...(onlySpec ? { onlySpec } : {}), + ...(selectedGroups.length > 0 + ? { + selectedGroups, + selectedOwners: runPlan.enabledOwners, + } + : {}), expectedScenarios, version: packageJson.version, commit: gitCommit(), @@ -2055,6 +2237,7 @@ async function main() { appTmpdir: process.env.ROSI_E2E_APP_TMPDIR || null, fixtures, scenarios, + scenarioGroups: groupedScenarioResults(scenarios, expectedScenarios), missingScenarios: missing, scenarioProblems, legacyImportCoverage, @@ -2126,13 +2309,25 @@ export function parseRepeat(argv, env = process.env) { */ export function summarizeStability(runs) { const names = new Set([ - ...EXPECTED_SCENARIOS, + ...runs.flatMap((run) => run.expected ?? EXPECTED_SCENARIOS), ...runs.flatMap((run) => run.passed), + ...runs.flatMap((run) => run.skipped), + ...runs.flatMap((run) => run.failed ?? []), ]); const scenarios = [...names].sort().map((name) => { - const passed = runs.filter((run) => run.passed.includes(name)).length; - const skipped = runs.filter((run) => run.skipped.includes(name)).length; - return { name, passed, skipped, failed: runs.length - passed - skipped }; + const eligible = runs.filter( + (run) => + (run.expected ?? EXPECTED_SCENARIOS).includes(name) || + run.passed.includes(name) || + run.skipped.includes(name) || + (run.failed ?? []).includes(name), + ); + const passed = eligible.filter((run) => run.passed.includes(name)).length; + const skipped = eligible.filter((run) => run.skipped.includes(name)).length; + const failed = eligible.filter( + (run) => !run.passed.includes(name) && !run.skipped.includes(name), + ).length; + return { name, passed, skipped, failed }; }); return { runs: runs.length, @@ -2183,6 +2378,10 @@ async function runStability(times) { skipped: report.scenarios .filter((scenario) => scenario.status === "skipped") .map((scenario) => scenario.name), + failed: report.scenarios + .filter((scenario) => scenario.status === "failed") + .map((scenario) => scenario.name), + expected: report.expectedScenarios ?? EXPECTED_SCENARIOS, }); } const summary = { diff --git a/scripts/verify-release-draft.js b/scripts/verify-release-draft.js index fb8e2cb9..b708f341 100644 --- a/scripts/verify-release-draft.js +++ b/scripts/verify-release-draft.js @@ -66,6 +66,10 @@ export function requiredDraftInstallerNames({ const names = [ "ROSI-Windows-x64.exe", "ROSI-Windows-arm64.exe", + "ROSI-MacOS-arm64.dmg", + "ROSI-MacOS-arm64.zip", + "ROSI-MacOS-x64.dmg", + "ROSI-MacOS-x64.zip", "ROSI-MacOS-universal.dmg", "ROSI-MacOS-universal.zip", "ROSI-Linux-x64.AppImage", diff --git a/scripts/zip-macos.js b/scripts/zip-macos.js index 92735ff7..f43f94b5 100644 --- a/scripts/zip-macos.js +++ b/scripts/zip-macos.js @@ -1,53 +1,73 @@ +#!/usr/bin/env node + import fs from "fs"; import os from "os"; import path from "path"; import { execFileSync, spawnSync } from "child_process"; +import { fileURLToPath, pathToFileURL } from "url"; import { isDeepStrictEqual } from "util"; -if (process.platform !== "darwin") { - console.log("zip-macos can only run on macOS."); - process.exit(0); -} +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +export const MACOS_TARGETS = Object.freeze({ + "universal-apple-darwin": Object.freeze({ + assetArch: "universal", + architectures: Object.freeze(["x86_64", "arm64"]), + }), + "aarch64-apple-darwin": Object.freeze({ + assetArch: "arm64", + architectures: Object.freeze(["arm64"]), + }), + "x86_64-apple-darwin": Object.freeze({ + assetArch: "x64", + architectures: Object.freeze(["x86_64"]), + }), +}); -const root = process.cwd(); -const targetArg = process.argv.indexOf("--target"); -const target = - targetArg >= 0 ? process.argv[targetArg + 1] : "universal-apple-darwin"; -if (!target || target.startsWith("--")) { - console.error("Usage: node scripts/zip-macos.js [--target ]"); - process.exit(1); +export function macosPackageName(target, extension) { + const targetConfig = MACOS_TARGETS[target]; + if (!targetConfig) throw new Error(`unsupported macOS target: ${target}`); + if (extension !== "dmg" && extension !== "zip") { + throw new Error(`unsupported macOS package extension: ${extension}`); + } + return `ROSI-MacOS-${targetConfig.assetArch}.${extension}`; } -const appPath = path.join( - root, - "src-tauri", - "target", +export function assertArchitectureCompatibility( + architectures, target, - "release", - "bundle", - "macos", - "ROSI.app", -); -if (!fs.existsSync(appPath)) { - console.error(`Expected macOS bundle was not found: ${appPath}`); - process.exit(1); + { allowAdditional = false, label = "binary" } = {}, +) { + const targetConfig = MACOS_TARGETS[target]; + if (!targetConfig) throw new Error(`unsupported macOS target: ${target}`); + const observed = Array.isArray(architectures) + ? architectures.map(String) + : String(architectures || "") + .trim() + .split(/\s+/) + .filter(Boolean); + const required = targetConfig.architectures; + const compatible = + required.every((arch) => observed.includes(arch)) && + (allowAdditional || observed.length === required.length); + if (!compatible) { + throw new Error( + `${label} has architectures "${observed.join(" ")}", expected ${allowAdditional ? "to include " : ""}"${required.join(" ")}" for ${target}`, + ); + } + return observed; } -const tauriConfig = JSON.parse( - fs.readFileSync(path.join(root, "src-tauri", "tauri.conf.json"), "utf8"), -); -const requiredMacOS = tauriConfig.bundle?.macOS?.minimumSystemVersion; -const expectedBundleVersion = tauriConfig.bundle?.macOS?.bundleVersion; -const marketingVersionMatch = tauriConfig.version?.match( - /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-beta\.(?:0|[1-9]\d*))?$/, -); -const expectedMarketingVersion = marketingVersionMatch - ? `${marketingVersionMatch[1]}.${marketingVersionMatch[2]}.${marketingVersionMatch[3]}` - : undefined; -if (!requiredMacOS || !expectedBundleVersion || !expectedMarketingVersion) { - throw new Error( - "tauri.conf.json must define a supported version, bundle.macOS.minimumSystemVersion, and bundleVersion", - ); +function parseTargetArguments(args) { + const targetIndex = args.indexOf("--target"); + const target = + targetIndex >= 0 ? args[targetIndex + 1] : "universal-apple-darwin"; + if (!target || target.startsWith("--") || !MACOS_TARGETS[target]) { + throw new Error( + "Usage: node scripts/zip-macos.js [--target universal-apple-darwin|aarch64-apple-darwin|x86_64-apple-darwin]", + ); + } + return target; } function compareVersions(left, right) { @@ -61,13 +81,20 @@ function compareVersions(left, right) { return 0; } +export function assertMinimumMacOSVersion(binary, arch, minimum, required) { + if (compareVersions(minimum, required) > 0) { + throw new Error( + `${path.basename(binary)} (${arch}) requires macOS ${minimum}, above ROSI's declared ${required} floor`, + ); + } +} + function parseMachOMinimumVersion(otoolOutput) { const buildVersion = otoolOutput.match( /cmd LC_BUILD_VERSION[\s\S]*?\bminos\s+(\d+(?:\.\d+)*)/, ); if (buildVersion?.[1]) return buildVersion[1]; - // Binaries built for older deployment targets (for example the upstream - // yt-dlp x86_64 slice) carry the legacy LC_VERSION_MIN_MACOSX command. + // Upstream yt-dlp x86_64 may use the legacy LC_VERSION_MIN_MACOSX command. const legacy = otoolOutput.match( /cmd LC_VERSION_MIN_MACOSX[\s\S]*?\bversion\s+(\d+(?:\.\d+)*)/, ); @@ -87,14 +114,18 @@ function readMachOMinimumVersion(binary, arch) { return minimum; } -function verifyMachOCompatibility(binary) { - for (const arch of ["x86_64", "arm64"]) { +function verifyMachOCompatibility(binary, target, requiredMacOS, options = {}) { + const targetConfig = MACOS_TARGETS[target]; + const architectures = execFileSync("lipo", ["-archs", binary], { + encoding: "utf8", + }).trim(); + assertArchitectureCompatibility(architectures, target, { + ...options, + label: path.basename(binary), + }); + for (const arch of targetConfig.architectures) { const minos = readMachOMinimumVersion(binary, arch); - if (compareVersions(minos, requiredMacOS) > 0) { - throw new Error( - `${path.basename(binary)} (${arch}) requires macOS ${minos}, above ROSI's declared ${requiredMacOS} floor`, - ); - } + assertMinimumMacOSVersion(binary, arch, minos, requiredMacOS); } } @@ -177,83 +208,219 @@ function readPlistValue(plistPath, key) { ).trim(); } -const infoPlist = path.join(appPath, "Contents", "Info.plist"); -const bundleVersion = readPlistValue(infoPlist, "CFBundleVersion"); -if (!/^\d+(?:\.\d+){0,2}$/.test(bundleVersion)) { - throw new Error(`CFBundleVersion must be numeric: ${bundleVersion}`); -} -if (bundleVersion !== expectedBundleVersion) { - throw new Error( - `CFBundleVersion ${bundleVersion} does not match configured ${expectedBundleVersion}`, - ); -} -const marketingVersion = readPlistValue( +function validateVersion( infoPlist, - "CFBundleShortVersionString", -); -if (marketingVersion !== expectedMarketingVersion) { - throw new Error( - `CFBundleShortVersionString ${marketingVersion} does not match expected ${expectedMarketingVersion}`, + { expectedBundleVersion, expectedMarketingVersion }, +) { + const bundleVersion = readPlistValue(infoPlist, "CFBundleVersion"); + const marketingVersion = readPlistValue( + infoPlist, + "CFBundleShortVersionString", + ); + assertBundleVersions( + { bundleVersion, marketingVersion }, + { expectedBundleVersion, expectedMarketingVersion }, ); } -const hostBinary = path.join(appPath, "Contents", "MacOS", "rosi"); -verifyMachOCompatibility(hostBinary); -// Tauri installs externalBin sidecars next to the host with the target triple -// stripped. yt-dlp, FFmpeg, and ffprobe must all be universal Mach-O files. -const sidecars = ["rosi-yt-dlp", "rosi-ffmpeg", "rosi-ffprobe"].map((name) => - path.join(appPath, "Contents", "MacOS", name), -); -for (const sidecar of sidecars) { - if (!fs.existsSync(sidecar)) { - throw new Error(`Missing bundled sidecar: ${sidecar}`); +export function assertBundleVersions( + actual, + { expectedBundleVersion, expectedMarketingVersion }, +) { + const { bundleVersion, marketingVersion } = actual; + if (!/^\d+(?:\.\d+){0,2}$/.test(bundleVersion)) { + throw new Error(`CFBundleVersion must be numeric: ${bundleVersion}`); + } + if (bundleVersion !== expectedBundleVersion) { + throw new Error( + `CFBundleVersion ${bundleVersion} does not match configured ${expectedBundleVersion}`, + ); } - const head = fs.readFileSync(sidecar).subarray(0, 4096).toString("latin1"); - if (head.includes("ROSI-SIDECAR-STUB")) { - throw new Error(`Bundled sidecar is a development stub: ${sidecar}`); + if (marketingVersion !== expectedMarketingVersion) { + throw new Error( + `CFBundleShortVersionString ${marketingVersion} does not match expected ${expectedMarketingVersion}`, + ); } - verifyMachOCompatibility(sidecar); } -execFileSync( - "codesign", - ["--verify", "--deep", "--strict", "--verbose=2", appPath], - { stdio: "inherit" }, -); -const hostTeam = verifyDeveloperIdSignature(appPath, "macOS app"); -const hostEntitlements = readEntitlementsTemplate( - path.join(root, "src-tauri", "entitlements.plist"), -); -verifySignedEntitlements(appPath, hostEntitlements); -// Tauri signs externalBin sidecars with the same entitlements.plist as the app; -// the PyInstaller yt-dlp runtime needs disable-library-validation to load. -for (const sidecar of sidecars) { - verifySignedEntitlements(sidecar, hostEntitlements); - const sidecarTeam = verifyDeveloperIdSignature( - sidecar, - `${path.basename(sidecar)} sidecar`, +export function verifyAppBundle( + appPath, + target, + tauriConfig, + repositoryRoot = root, +) { + const requiredMacOS = tauriConfig.bundle?.macOS?.minimumSystemVersion; + const expectedBundleVersion = tauriConfig.bundle?.macOS?.bundleVersion; + const marketingVersionMatch = tauriConfig.version?.match( + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-beta\.(?:0|[1-9]\d*))?$/, ); - if (sidecarTeam !== hostTeam) { + const expectedMarketingVersion = marketingVersionMatch + ? `${marketingVersionMatch[1]}.${marketingVersionMatch[2]}.${marketingVersionMatch[3]}` + : undefined; + if (!requiredMacOS || !expectedBundleVersion || !expectedMarketingVersion) { throw new Error( - `${path.basename(sidecar)} TeamIdentifier ${sidecarTeam} does not match host ${hostTeam}.`, + "tauri.conf.json must define a supported version, bundle.macOS.minimumSystemVersion, and bundleVersion", ); } -} -execFileSync("xcrun", ["stapler", "validate", appPath], { stdio: "inherit" }); -execFileSync( - "spctl", - ["--assess", "--type", "execute", "--verbose=2", appPath], - { + + validateVersion(path.join(appPath, "Contents", "Info.plist"), { + expectedBundleVersion, + expectedMarketingVersion, + }); + + const hostBinary = path.join(appPath, "Contents", "MacOS", "rosi"); + verifyMachOCompatibility(hostBinary, target, requiredMacOS); + // yt-dlp is upstream universal2. It may retain its other slice in a native + // installer, but it must include the requested architecture and meet its OS floor. + const sidecars = [ + { name: "rosi-yt-dlp", allowAdditional: true }, + { name: "rosi-ffmpeg", allowAdditional: false }, + { name: "rosi-ffprobe", allowAdditional: false }, + ].map(({ name, allowAdditional }) => ({ + filePath: path.join(appPath, "Contents", "MacOS", name), + allowAdditional, + })); + for (const { filePath, allowAdditional } of sidecars) { + if (!fs.existsSync(filePath)) { + throw new Error(`Missing bundled sidecar: ${filePath}`); + } + const head = fs.readFileSync(filePath).subarray(0, 4096).toString("latin1"); + if (head.includes("ROSI-SIDECAR-STUB")) { + throw new Error(`Bundled sidecar is a development stub: ${filePath}`); + } + verifyMachOCompatibility(filePath, target, requiredMacOS, { + allowAdditional, + }); + } + + execFileSync( + "codesign", + ["--verify", "--deep", "--strict", "--verbose=2", appPath], + { stdio: "inherit" }, + ); + const hostTeam = verifyDeveloperIdSignature(appPath, "macOS app"); + const hostEntitlements = readEntitlementsTemplate( + path.join(repositoryRoot, "src-tauri", "entitlements.plist"), + ); + verifySignedEntitlements(appPath, hostEntitlements); + // Tauri signs externalBin sidecars with the app's entitlements; the + // PyInstaller yt-dlp runtime needs disable-library-validation to load. + for (const { filePath } of sidecars) { + verifySignedEntitlements(filePath, hostEntitlements); + const sidecarTeam = verifyDeveloperIdSignature( + filePath, + `${path.basename(filePath)} sidecar`, + ); + if (sidecarTeam !== hostTeam) { + throw new Error( + `${path.basename(filePath)} TeamIdentifier ${sidecarTeam} does not match host ${hostTeam}.`, + ); + } + } + execFileSync("xcrun", ["stapler", "validate", appPath], { stdio: "inherit", - }, -); + }); + execFileSync( + "spctl", + ["--assess", "--type", "execute", "--verbose=2", appPath], + { stdio: "inherit" }, + ); +} + +export function packageOutputPath(appPath, target) { + return path.join(path.dirname(appPath), macosPackageName(target, "zip")); +} + +export function normalizeDmgPackage(appPath, target) { + const dmgDirectory = path.join(path.dirname(appPath), "..", "dmg"); + if (!fs.existsSync(dmgDirectory)) return null; + const candidates = fs + .readdirSync(dmgDirectory, { withFileTypes: true }) + .filter( + (entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".dmg"), + ) + .map((entry) => path.join(dmgDirectory, entry.name)); + if (candidates.length === 0) return null; + const destination = path.join(dmgDirectory, macosPackageName(target, "dmg")); + if (candidates.length > 1) { + const rawCandidates = candidates.filter( + (candidate) => path.resolve(candidate) !== path.resolve(destination), + ); + // A prior packaging pass may have left the normalized name beside the + // newly written Tauri DMG. Replace that known output; other duplicates are + // ambiguous and must be resolved by the caller. + if (candidates.includes(destination) && rawCandidates.length === 1) { + fs.rmSync(destination, { force: true }); + fs.renameSync(rawCandidates[0], destination); + return destination; + } + throw new Error( + `Expected one DMG for ${target} in ${dmgDirectory}, found ${candidates.map((candidate) => path.basename(candidate)).join(", ")}`, + ); + } + if (path.resolve(candidates[0]) === path.resolve(destination)) + return destination; + fs.rmSync(destination, { force: true }); + fs.renameSync(candidates[0], destination); + return destination; +} + +export function zipMacosApp({ + target, + repositoryRoot = root, + run = execFileSync, +}) { + if (process.platform !== "darwin") { + throw new Error("zip-macos can only run on macOS."); + } + if (!MACOS_TARGETS[target]) + throw new Error(`unsupported macOS target: ${target}`); + const appPath = path.join( + repositoryRoot, + "src-tauri", + "target", + target, + "release", + "bundle", + "macos", + "ROSI.app", + ); + if (!fs.existsSync(appPath)) { + throw new Error(`Expected macOS bundle was not found: ${appPath}`); + } + const tauriConfig = JSON.parse( + fs.readFileSync( + path.join(repositoryRoot, "src-tauri", "tauri.conf.json"), + "utf8", + ), + ); + verifyAppBundle(appPath, target, tauriConfig, repositoryRoot); + normalizeDmgPackage(appPath, target); + const zipPath = packageOutputPath(appPath, target); + run( + "ditto", + ["-c", "-k", "--sequesterRsrc", "--keepParent", appPath, zipPath], + { stdio: "inherit" }, + ); + console.log(`Created ${zipPath}`); + return zipPath; +} -const baseName = path.basename(appPath, ".app"); -const zipPath = path.join(path.dirname(appPath), `${baseName}.zip`); -execFileSync( - "ditto", - ["-c", "-k", "--sequesterRsrc", "--keepParent", appPath, zipPath], - { stdio: "inherit" }, -); +function main() { + const target = parseTargetArguments(process.argv.slice(2)); + zipMacosApp({ target }); +} -console.log(`Created ${zipPath}`); +if ( + process.argv[1] && + pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url +) { + try { + main(); + } catch (error) { + console.error( + `zip-macos: FAILED: ${error instanceof Error ? error.message : String(error)}`, + ); + process.exit(1); + } +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 194f9360..cd54cb23 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3431,6 +3431,7 @@ dependencies = [ "tauri-plugin-updater", "tauri-plugin-wdio", "tauri-plugin-wdio-webdriver", + "tokio", "ts-rs", "url", "windows-sys 0.61.2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b3e2099f..228f9130 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -23,6 +23,7 @@ shared_child = "1.1" getrandom = "0.3" url = "2" reqwest = { version = "0.13", default-features = false, features = ["rustls"] } +tokio = { version = "1.53.3", features = ["io-util", "macros", "net", "rt", "sync", "time"] } [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] tauri-plugin-single-instance = "2" diff --git a/src-tauri/build.rs b/src-tauri/build.rs index cbd8c735..9f01ec9c 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -19,6 +19,7 @@ const COMMANDS: &[&str] = &[ "get_video_info", "cancel_video_info", "download_video", + "resolve_download_options", "cancel_download", "add_to_queue", "remove_from_queue", @@ -66,6 +67,7 @@ const COMMANDS_WITH_E2E: &[&str] = &[ "get_video_info", "cancel_video_info", "download_video", + "resolve_download_options", "cancel_download", "add_to_queue", "remove_from_queue", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index a8c9517b..f4536dd5 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -26,6 +26,7 @@ "allow-get-video-info", "allow-cancel-video-info", "allow-download-video", + "allow-resolve-download-options", "allow-cancel-download", "allow-add-to-queue", "allow-remove-from-queue", diff --git a/src-tauri/gen/schemas/acl-manifests.json b/src-tauri/gen/schemas/acl-manifests.json index dbd84013..42e5d1fe 100644 --- a/src-tauri/gen/schemas/acl-manifests.json +++ b/src-tauri/gen/schemas/acl-manifests.json @@ -1 +1 @@ -{"__app-acl__":{"default_permission":null,"permissions":{"allow-add-to-queue":{"identifier":"allow-add-to-queue","description":"Enables the add_to_queue command without any pre-configured scope.","commands":{"allow":["add_to_queue"],"deny":[]}},"allow-cancel-download":{"identifier":"allow-cancel-download","description":"Enables the cancel_download command without any pre-configured scope.","commands":{"allow":["cancel_download"],"deny":[]}},"allow-cancel-formats":{"identifier":"allow-cancel-formats","description":"Enables the cancel_formats command without any pre-configured scope.","commands":{"allow":["cancel_formats"],"deny":[]}},"allow-cancel-queue":{"identifier":"allow-cancel-queue","description":"Enables the cancel_queue command without any pre-configured scope.","commands":{"allow":["cancel_queue"],"deny":[]}},"allow-cancel-video-info":{"identifier":"allow-cancel-video-info","description":"Enables the cancel_video_info command without any pre-configured scope.","commands":{"allow":["cancel_video_info"],"deny":[]}},"allow-check-deno-installed":{"identifier":"allow-check-deno-installed","description":"Enables the check_deno_installed command without any pre-configured scope.","commands":{"allow":["check_deno_installed"],"deny":[]}},"allow-clear-download-activity":{"identifier":"allow-clear-download-activity","description":"Enables the clear_download_activity command without any pre-configured scope.","commands":{"allow":["clear_download_activity"],"deny":[]}},"allow-clear-finished-queue":{"identifier":"allow-clear-finished-queue","description":"Enables the clear_finished_queue command without any pre-configured scope.","commands":{"allow":["clear_finished_queue"],"deny":[]}},"allow-clear-queue":{"identifier":"allow-clear-queue","description":"Enables the clear_queue command without any pre-configured scope.","commands":{"allow":["clear_queue"],"deny":[]}},"allow-detect-gpu":{"identifier":"allow-detect-gpu","description":"Enables the detect_gpu command without any pre-configured scope.","commands":{"allow":["detect_gpu"],"deny":[]}},"allow-download-video":{"identifier":"allow-download-video","description":"Enables the download_video command without any pre-configured scope.","commands":{"allow":["download_video"],"deny":[]}},"allow-e2e-cancel-close-request":{"identifier":"allow-e2e-cancel-close-request","description":"Enables the e2e_cancel_close_request command without any pre-configured scope.","commands":{"allow":["e2e_cancel_close_request"],"deny":[]}},"allow-e2e-emit-stale-download-events":{"identifier":"allow-e2e-emit-stale-download-events","description":"Enables the e2e_emit_stale_download_events command without any pre-configured scope.","commands":{"allow":["e2e_emit_stale_download_events"],"deny":[]}},"allow-e2e-network-pipelining-probe":{"identifier":"allow-e2e-network-pipelining-probe","description":"Enables the e2e_network_pipelining_probe command without any pre-configured scope.","commands":{"allow":["e2e_network_pipelining_probe"],"deny":[]}},"allow-e2e-updater-install-probe":{"identifier":"allow-e2e-updater-install-probe","description":"Enables the e2e_updater_install_probe command without any pre-configured scope.","commands":{"allow":["e2e_updater_install_probe"],"deny":[]}},"allow-export-settings":{"identifier":"allow-export-settings","description":"Enables the export_settings command without any pre-configured scope.","commands":{"allow":["export_settings"],"deny":[]}},"allow-get-app-platform":{"identifier":"allow-get-app-platform","description":"Enables the get_app_platform command without any pre-configured scope.","commands":{"allow":["get_app_platform"],"deny":[]}},"allow-get-beta-updater-target":{"identifier":"allow-get-beta-updater-target","description":"Enables the get_beta_updater_target command without any pre-configured scope.","commands":{"allow":["get_beta_updater_target"],"deny":[]}},"allow-get-compact-updater-target":{"identifier":"allow-get-compact-updater-target","description":"Enables the get_compact_updater_target command without any pre-configured scope.","commands":{"allow":["get_compact_updater_target"],"deny":[]}},"allow-get-default-settings":{"identifier":"allow-get-default-settings","description":"Enables the get_default_settings command without any pre-configured scope.","commands":{"allow":["get_default_settings"],"deny":[]}},"allow-get-distribution-channel":{"identifier":"allow-get-distribution-channel","description":"Enables the get_distribution_channel command without any pre-configured scope.","commands":{"allow":["get_distribution_channel"],"deny":[]}},"allow-get-download-activity":{"identifier":"allow-get-download-activity","description":"Enables the get_download_activity command without any pre-configured scope.","commands":{"allow":["get_download_activity"],"deny":[]}},"allow-get-formats":{"identifier":"allow-get-formats","description":"Enables the get_formats command without any pre-configured scope.","commands":{"allow":["get_formats"],"deny":[]}},"allow-get-queue":{"identifier":"allow-get-queue","description":"Enables the get_queue command without any pre-configured scope.","commands":{"allow":["get_queue"],"deny":[]}},"allow-get-settings":{"identifier":"allow-get-settings","description":"Enables the get_settings command without any pre-configured scope.","commands":{"allow":["get_settings"],"deny":[]}},"allow-get-stats":{"identifier":"allow-get-stats","description":"Enables the get_stats command without any pre-configured scope.","commands":{"allow":["get_stats"],"deny":[]}},"allow-get-video-info":{"identifier":"allow-get-video-info","description":"Enables the get_video_info command without any pre-configured scope.","commands":{"allow":["get_video_info"],"deny":[]}},"allow-import-settings":{"identifier":"allow-import-settings","description":"Enables the import_settings command without any pre-configured scope.","commands":{"allow":["import_settings"],"deny":[]}},"allow-install-deno":{"identifier":"allow-install-deno","description":"Enables the install_deno command without any pre-configured scope.","commands":{"allow":["install_deno"],"deny":[]}},"allow-is-flatpak":{"identifier":"allow-is-flatpak","description":"Enables the is_flatpak command without any pre-configured scope.","commands":{"allow":["is_flatpak"],"deny":[]}},"allow-is-packaged":{"identifier":"allow-is-packaged","description":"Enables the is_packaged command without any pre-configured scope.","commands":{"allow":["is_packaged"],"deny":[]}},"allow-log-error":{"identifier":"allow-log-error","description":"Enables the log_error command without any pre-configured scope.","commands":{"allow":["log_error"],"deny":[]}},"allow-mark-main-window-ready":{"identifier":"allow-mark-main-window-ready","description":"Enables the mark_main_window_ready command without any pre-configured scope.","commands":{"allow":["mark_main_window_ready"],"deny":[]}},"allow-notify-settings-flushed":{"identifier":"allow-notify-settings-flushed","description":"Enables the notify_settings_flushed command without any pre-configured scope.","commands":{"allow":["notify_settings_flushed"],"deny":[]}},"allow-open-external":{"identifier":"allow-open-external","description":"Enables the open_external command without any pre-configured scope.","commands":{"allow":["open_external"],"deny":[]}},"allow-open-file-location":{"identifier":"allow-open-file-location","description":"Enables the open_file_location command without any pre-configured scope.","commands":{"allow":["open_file_location"],"deny":[]}},"allow-remove-from-queue":{"identifier":"allow-remove-from-queue","description":"Enables the remove_from_queue command without any pre-configured scope.","commands":{"allow":["remove_from_queue"],"deny":[]}},"allow-reorder-queue-item":{"identifier":"allow-reorder-queue-item","description":"Enables the reorder_queue_item command without any pre-configured scope.","commands":{"allow":["reorder_queue_item"],"deny":[]}},"allow-reset-settings":{"identifier":"allow-reset-settings","description":"Enables the reset_settings command without any pre-configured scope.","commands":{"allow":["reset_settings"],"deny":[]}},"allow-reset-stats":{"identifier":"allow-reset-stats","description":"Enables the reset_stats command without any pre-configured scope.","commands":{"allow":["reset_stats"],"deny":[]}},"allow-restart-app":{"identifier":"allow-restart-app","description":"Enables the restart_app command without any pre-configured scope.","commands":{"allow":["restart_app"],"deny":[]}},"allow-retry-queue-item":{"identifier":"allow-retry-queue-item","description":"Enables the retry_queue_item command without any pre-configured scope.","commands":{"allow":["retry_queue_item"],"deny":[]}},"allow-save-settings":{"identifier":"allow-save-settings","description":"Enables the save_settings command without any pre-configured scope.","commands":{"allow":["save_settings"],"deny":[]}},"allow-select-download-location":{"identifier":"allow-select-download-location","description":"Enables the select_download_location command without any pre-configured scope.","commands":{"allow":["select_download_location"],"deny":[]}},"allow-show-notification":{"identifier":"allow-show-notification","description":"Enables the show_notification command without any pre-configured scope.","commands":{"allow":["show_notification"],"deny":[]}},"allow-start-queue":{"identifier":"allow-start-queue","description":"Enables the start_queue command without any pre-configured scope.","commands":{"allow":["start_queue"],"deny":[]}},"deny-add-to-queue":{"identifier":"deny-add-to-queue","description":"Denies the add_to_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["add_to_queue"]}},"deny-cancel-download":{"identifier":"deny-cancel-download","description":"Denies the cancel_download command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_download"]}},"deny-cancel-formats":{"identifier":"deny-cancel-formats","description":"Denies the cancel_formats command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_formats"]}},"deny-cancel-queue":{"identifier":"deny-cancel-queue","description":"Denies the cancel_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_queue"]}},"deny-cancel-video-info":{"identifier":"deny-cancel-video-info","description":"Denies the cancel_video_info command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_video_info"]}},"deny-check-deno-installed":{"identifier":"deny-check-deno-installed","description":"Denies the check_deno_installed command without any pre-configured scope.","commands":{"allow":[],"deny":["check_deno_installed"]}},"deny-clear-download-activity":{"identifier":"deny-clear-download-activity","description":"Denies the clear_download_activity command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_download_activity"]}},"deny-clear-finished-queue":{"identifier":"deny-clear-finished-queue","description":"Denies the clear_finished_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_finished_queue"]}},"deny-clear-queue":{"identifier":"deny-clear-queue","description":"Denies the clear_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_queue"]}},"deny-detect-gpu":{"identifier":"deny-detect-gpu","description":"Denies the detect_gpu command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_gpu"]}},"deny-download-video":{"identifier":"deny-download-video","description":"Denies the download_video command without any pre-configured scope.","commands":{"allow":[],"deny":["download_video"]}},"deny-e2e-cancel-close-request":{"identifier":"deny-e2e-cancel-close-request","description":"Denies the e2e_cancel_close_request command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_cancel_close_request"]}},"deny-e2e-emit-stale-download-events":{"identifier":"deny-e2e-emit-stale-download-events","description":"Denies the e2e_emit_stale_download_events command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_emit_stale_download_events"]}},"deny-e2e-network-pipelining-probe":{"identifier":"deny-e2e-network-pipelining-probe","description":"Denies the e2e_network_pipelining_probe command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_network_pipelining_probe"]}},"deny-e2e-updater-install-probe":{"identifier":"deny-e2e-updater-install-probe","description":"Denies the e2e_updater_install_probe command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_updater_install_probe"]}},"deny-export-settings":{"identifier":"deny-export-settings","description":"Denies the export_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["export_settings"]}},"deny-get-app-platform":{"identifier":"deny-get-app-platform","description":"Denies the get_app_platform command without any pre-configured scope.","commands":{"allow":[],"deny":["get_app_platform"]}},"deny-get-beta-updater-target":{"identifier":"deny-get-beta-updater-target","description":"Denies the get_beta_updater_target command without any pre-configured scope.","commands":{"allow":[],"deny":["get_beta_updater_target"]}},"deny-get-compact-updater-target":{"identifier":"deny-get-compact-updater-target","description":"Denies the get_compact_updater_target command without any pre-configured scope.","commands":{"allow":[],"deny":["get_compact_updater_target"]}},"deny-get-default-settings":{"identifier":"deny-get-default-settings","description":"Denies the get_default_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_default_settings"]}},"deny-get-distribution-channel":{"identifier":"deny-get-distribution-channel","description":"Denies the get_distribution_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["get_distribution_channel"]}},"deny-get-download-activity":{"identifier":"deny-get-download-activity","description":"Denies the get_download_activity command without any pre-configured scope.","commands":{"allow":[],"deny":["get_download_activity"]}},"deny-get-formats":{"identifier":"deny-get-formats","description":"Denies the get_formats command without any pre-configured scope.","commands":{"allow":[],"deny":["get_formats"]}},"deny-get-queue":{"identifier":"deny-get-queue","description":"Denies the get_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["get_queue"]}},"deny-get-settings":{"identifier":"deny-get-settings","description":"Denies the get_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_settings"]}},"deny-get-stats":{"identifier":"deny-get-stats","description":"Denies the get_stats command without any pre-configured scope.","commands":{"allow":[],"deny":["get_stats"]}},"deny-get-video-info":{"identifier":"deny-get-video-info","description":"Denies the get_video_info command without any pre-configured scope.","commands":{"allow":[],"deny":["get_video_info"]}},"deny-import-settings":{"identifier":"deny-import-settings","description":"Denies the import_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["import_settings"]}},"deny-install-deno":{"identifier":"deny-install-deno","description":"Denies the install_deno command without any pre-configured scope.","commands":{"allow":[],"deny":["install_deno"]}},"deny-is-flatpak":{"identifier":"deny-is-flatpak","description":"Denies the is_flatpak command without any pre-configured scope.","commands":{"allow":[],"deny":["is_flatpak"]}},"deny-is-packaged":{"identifier":"deny-is-packaged","description":"Denies the is_packaged command without any pre-configured scope.","commands":{"allow":[],"deny":["is_packaged"]}},"deny-log-error":{"identifier":"deny-log-error","description":"Denies the log_error command without any pre-configured scope.","commands":{"allow":[],"deny":["log_error"]}},"deny-mark-main-window-ready":{"identifier":"deny-mark-main-window-ready","description":"Denies the mark_main_window_ready command without any pre-configured scope.","commands":{"allow":[],"deny":["mark_main_window_ready"]}},"deny-notify-settings-flushed":{"identifier":"deny-notify-settings-flushed","description":"Denies the notify_settings_flushed command without any pre-configured scope.","commands":{"allow":[],"deny":["notify_settings_flushed"]}},"deny-open-external":{"identifier":"deny-open-external","description":"Denies the open_external command without any pre-configured scope.","commands":{"allow":[],"deny":["open_external"]}},"deny-open-file-location":{"identifier":"deny-open-file-location","description":"Denies the open_file_location command without any pre-configured scope.","commands":{"allow":[],"deny":["open_file_location"]}},"deny-remove-from-queue":{"identifier":"deny-remove-from-queue","description":"Denies the remove_from_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_from_queue"]}},"deny-reorder-queue-item":{"identifier":"deny-reorder-queue-item","description":"Denies the reorder_queue_item command without any pre-configured scope.","commands":{"allow":[],"deny":["reorder_queue_item"]}},"deny-reset-settings":{"identifier":"deny-reset-settings","description":"Denies the reset_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["reset_settings"]}},"deny-reset-stats":{"identifier":"deny-reset-stats","description":"Denies the reset_stats command without any pre-configured scope.","commands":{"allow":[],"deny":["reset_stats"]}},"deny-restart-app":{"identifier":"deny-restart-app","description":"Denies the restart_app command without any pre-configured scope.","commands":{"allow":[],"deny":["restart_app"]}},"deny-retry-queue-item":{"identifier":"deny-retry-queue-item","description":"Denies the retry_queue_item command without any pre-configured scope.","commands":{"allow":[],"deny":["retry_queue_item"]}},"deny-save-settings":{"identifier":"deny-save-settings","description":"Denies the save_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["save_settings"]}},"deny-select-download-location":{"identifier":"deny-select-download-location","description":"Denies the select_download_location command without any pre-configured scope.","commands":{"allow":[],"deny":["select_download_location"]}},"deny-show-notification":{"identifier":"deny-show-notification","description":"Denies the show_notification command without any pre-configured scope.","commands":{"allow":[],"deny":["show_notification"]}},"deny-start-queue":{"identifier":"deny-start-queue","description":"Denies the start_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["start_queue"]}}},"permission_sets":{},"global_scope_schema":null},"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null},"notification":{"default_permission":{"identifier":"default","description":"This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n","permissions":["allow-is-permission-granted","allow-request-permission","allow-notify","allow-register-action-types","allow-register-listener","allow-remove-listener","allow-cancel","allow-get-pending","allow-remove-active","allow-get-active","allow-check-permissions","allow-show","allow-batch","allow-list-channels","allow-delete-channel","allow-create-channel","allow-permission-state"]},"permissions":{"allow-batch":{"identifier":"allow-batch","description":"Enables the batch command without any pre-configured scope.","commands":{"allow":["batch"],"deny":[]}},"allow-cancel":{"identifier":"allow-cancel","description":"Enables the cancel command without any pre-configured scope.","commands":{"allow":["cancel"],"deny":[]}},"allow-check-permissions":{"identifier":"allow-check-permissions","description":"Enables the check_permissions command without any pre-configured scope.","commands":{"allow":["check_permissions"],"deny":[]}},"allow-create-channel":{"identifier":"allow-create-channel","description":"Enables the create_channel command without any pre-configured scope.","commands":{"allow":["create_channel"],"deny":[]}},"allow-delete-channel":{"identifier":"allow-delete-channel","description":"Enables the delete_channel command without any pre-configured scope.","commands":{"allow":["delete_channel"],"deny":[]}},"allow-get-active":{"identifier":"allow-get-active","description":"Enables the get_active command without any pre-configured scope.","commands":{"allow":["get_active"],"deny":[]}},"allow-get-pending":{"identifier":"allow-get-pending","description":"Enables the get_pending command without any pre-configured scope.","commands":{"allow":["get_pending"],"deny":[]}},"allow-is-permission-granted":{"identifier":"allow-is-permission-granted","description":"Enables the is_permission_granted command without any pre-configured scope.","commands":{"allow":["is_permission_granted"],"deny":[]}},"allow-list-channels":{"identifier":"allow-list-channels","description":"Enables the list_channels command without any pre-configured scope.","commands":{"allow":["list_channels"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-permission-state":{"identifier":"allow-permission-state","description":"Enables the permission_state command without any pre-configured scope.","commands":{"allow":["permission_state"],"deny":[]}},"allow-register-action-types":{"identifier":"allow-register-action-types","description":"Enables the register_action_types command without any pre-configured scope.","commands":{"allow":["register_action_types"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-active":{"identifier":"allow-remove-active","description":"Enables the remove_active command without any pre-configured scope.","commands":{"allow":["remove_active"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-request-permission":{"identifier":"allow-request-permission","description":"Enables the request_permission command without any pre-configured scope.","commands":{"allow":["request_permission"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"deny-batch":{"identifier":"deny-batch","description":"Denies the batch command without any pre-configured scope.","commands":{"allow":[],"deny":["batch"]}},"deny-cancel":{"identifier":"deny-cancel","description":"Denies the cancel command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel"]}},"deny-check-permissions":{"identifier":"deny-check-permissions","description":"Denies the check_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_permissions"]}},"deny-create-channel":{"identifier":"deny-create-channel","description":"Denies the create_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["create_channel"]}},"deny-delete-channel":{"identifier":"deny-delete-channel","description":"Denies the delete_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_channel"]}},"deny-get-active":{"identifier":"deny-get-active","description":"Denies the get_active command without any pre-configured scope.","commands":{"allow":[],"deny":["get_active"]}},"deny-get-pending":{"identifier":"deny-get-pending","description":"Denies the get_pending command without any pre-configured scope.","commands":{"allow":[],"deny":["get_pending"]}},"deny-is-permission-granted":{"identifier":"deny-is-permission-granted","description":"Denies the is_permission_granted command without any pre-configured scope.","commands":{"allow":[],"deny":["is_permission_granted"]}},"deny-list-channels":{"identifier":"deny-list-channels","description":"Denies the list_channels command without any pre-configured scope.","commands":{"allow":[],"deny":["list_channels"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-permission-state":{"identifier":"deny-permission-state","description":"Denies the permission_state command without any pre-configured scope.","commands":{"allow":[],"deny":["permission_state"]}},"deny-register-action-types":{"identifier":"deny-register-action-types","description":"Denies the register_action_types command without any pre-configured scope.","commands":{"allow":[],"deny":["register_action_types"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-active":{"identifier":"deny-remove-active","description":"Denies the remove_active command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_active"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-request-permission":{"identifier":"deny-request-permission","description":"Denies the request_permission command without any pre-configured scope.","commands":{"allow":[],"deny":["request_permission"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}}},"permission_sets":{},"global_scope_schema":null},"opener":{"default_permission":{"identifier":"default","description":"This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer","permissions":["allow-open-url","allow-reveal-item-in-dir","allow-default-urls"]},"permissions":{"allow-default-urls":{"identifier":"allow-default-urls","description":"This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.","commands":{"allow":[],"deny":[]},"scope":{"allow":[{"url":"mailto:*"},{"url":"tel:*"},{"url":"http://*"},{"url":"https://*"}]}},"allow-open-path":{"identifier":"allow-open-path","description":"Enables the open_path command without any pre-configured scope.","commands":{"allow":["open_path"],"deny":[]}},"allow-open-url":{"identifier":"allow-open-url","description":"Enables the open_url command without any pre-configured scope.","commands":{"allow":["open_url"],"deny":[]}},"allow-reveal-item-in-dir":{"identifier":"allow-reveal-item-in-dir","description":"Enables the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":["reveal_item_in_dir"],"deny":[]}},"deny-open-path":{"identifier":"deny-open-path","description":"Denies the open_path command without any pre-configured scope.","commands":{"allow":[],"deny":["open_path"]}},"deny-open-url":{"identifier":"deny-open-url","description":"Denies the open_url command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url"]}},"deny-reveal-item-in-dir":{"identifier":"deny-reveal-item-in-dir","description":"Denies the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":[],"deny":["reveal_item_in_dir"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this url with, for example: firefox."},"url":{"description":"A URL that can be opened by the webview when using the Opener APIs.\n\nWildcards can be used following the UNIX glob pattern.\n\nExamples:\n\n- \"https://*\" : allows all HTTPS origin\n\n- \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path\n\n- \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"","type":"string"}},"required":["url"],"type":"object"},{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this path with, for example: xdg-open."},"path":{"description":"A path that can be opened by the webview when using the Opener APIs.\n\nThe pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"}},"required":["path"],"type":"object"}],"definitions":{"Application":{"anyOf":[{"description":"Open in default application.","type":"null"},{"description":"If true, allow open with any application.","type":"boolean"},{"description":"Allow specific application to open with.","type":"string"}],"description":"Opener scope application."}},"description":"Opener scope entry.","title":"OpenerScopeEntry"}},"process":{"default_permission":{"identifier":"default","description":"This permission set configures which\nprocess features are by default exposed.\n\n#### Granted Permissions\n\nThis enables to quit via `allow-exit` and restart via `allow-restart`\nthe application.\n","permissions":["allow-exit","allow-restart"]},"permissions":{"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-restart":{"identifier":"allow-restart","description":"Enables the restart command without any pre-configured scope.","commands":{"allow":["restart"],"deny":[]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-restart":{"identifier":"deny-restart","description":"Denies the restart command without any pre-configured scope.","commands":{"allow":[],"deny":["restart"]}}},"permission_sets":{},"global_scope_schema":null},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file +{"__app-acl__":{"default_permission":null,"permissions":{"allow-add-to-queue":{"identifier":"allow-add-to-queue","description":"Enables the add_to_queue command without any pre-configured scope.","commands":{"allow":["add_to_queue"],"deny":[]}},"allow-cancel-download":{"identifier":"allow-cancel-download","description":"Enables the cancel_download command without any pre-configured scope.","commands":{"allow":["cancel_download"],"deny":[]}},"allow-cancel-formats":{"identifier":"allow-cancel-formats","description":"Enables the cancel_formats command without any pre-configured scope.","commands":{"allow":["cancel_formats"],"deny":[]}},"allow-cancel-queue":{"identifier":"allow-cancel-queue","description":"Enables the cancel_queue command without any pre-configured scope.","commands":{"allow":["cancel_queue"],"deny":[]}},"allow-cancel-video-info":{"identifier":"allow-cancel-video-info","description":"Enables the cancel_video_info command without any pre-configured scope.","commands":{"allow":["cancel_video_info"],"deny":[]}},"allow-check-deno-installed":{"identifier":"allow-check-deno-installed","description":"Enables the check_deno_installed command without any pre-configured scope.","commands":{"allow":["check_deno_installed"],"deny":[]}},"allow-clear-download-activity":{"identifier":"allow-clear-download-activity","description":"Enables the clear_download_activity command without any pre-configured scope.","commands":{"allow":["clear_download_activity"],"deny":[]}},"allow-clear-finished-queue":{"identifier":"allow-clear-finished-queue","description":"Enables the clear_finished_queue command without any pre-configured scope.","commands":{"allow":["clear_finished_queue"],"deny":[]}},"allow-clear-queue":{"identifier":"allow-clear-queue","description":"Enables the clear_queue command without any pre-configured scope.","commands":{"allow":["clear_queue"],"deny":[]}},"allow-detect-gpu":{"identifier":"allow-detect-gpu","description":"Enables the detect_gpu command without any pre-configured scope.","commands":{"allow":["detect_gpu"],"deny":[]}},"allow-download-video":{"identifier":"allow-download-video","description":"Enables the download_video command without any pre-configured scope.","commands":{"allow":["download_video"],"deny":[]}},"allow-e2e-cancel-close-request":{"identifier":"allow-e2e-cancel-close-request","description":"Enables the e2e_cancel_close_request command without any pre-configured scope.","commands":{"allow":["e2e_cancel_close_request"],"deny":[]}},"allow-e2e-emit-stale-download-events":{"identifier":"allow-e2e-emit-stale-download-events","description":"Enables the e2e_emit_stale_download_events command without any pre-configured scope.","commands":{"allow":["e2e_emit_stale_download_events"],"deny":[]}},"allow-e2e-network-pipelining-probe":{"identifier":"allow-e2e-network-pipelining-probe","description":"Enables the e2e_network_pipelining_probe command without any pre-configured scope.","commands":{"allow":["e2e_network_pipelining_probe"],"deny":[]}},"allow-e2e-updater-install-probe":{"identifier":"allow-e2e-updater-install-probe","description":"Enables the e2e_updater_install_probe command without any pre-configured scope.","commands":{"allow":["e2e_updater_install_probe"],"deny":[]}},"allow-export-settings":{"identifier":"allow-export-settings","description":"Enables the export_settings command without any pre-configured scope.","commands":{"allow":["export_settings"],"deny":[]}},"allow-get-app-platform":{"identifier":"allow-get-app-platform","description":"Enables the get_app_platform command without any pre-configured scope.","commands":{"allow":["get_app_platform"],"deny":[]}},"allow-get-beta-updater-target":{"identifier":"allow-get-beta-updater-target","description":"Enables the get_beta_updater_target command without any pre-configured scope.","commands":{"allow":["get_beta_updater_target"],"deny":[]}},"allow-get-compact-updater-target":{"identifier":"allow-get-compact-updater-target","description":"Enables the get_compact_updater_target command without any pre-configured scope.","commands":{"allow":["get_compact_updater_target"],"deny":[]}},"allow-get-default-settings":{"identifier":"allow-get-default-settings","description":"Enables the get_default_settings command without any pre-configured scope.","commands":{"allow":["get_default_settings"],"deny":[]}},"allow-get-distribution-channel":{"identifier":"allow-get-distribution-channel","description":"Enables the get_distribution_channel command without any pre-configured scope.","commands":{"allow":["get_distribution_channel"],"deny":[]}},"allow-get-download-activity":{"identifier":"allow-get-download-activity","description":"Enables the get_download_activity command without any pre-configured scope.","commands":{"allow":["get_download_activity"],"deny":[]}},"allow-get-formats":{"identifier":"allow-get-formats","description":"Enables the get_formats command without any pre-configured scope.","commands":{"allow":["get_formats"],"deny":[]}},"allow-get-queue":{"identifier":"allow-get-queue","description":"Enables the get_queue command without any pre-configured scope.","commands":{"allow":["get_queue"],"deny":[]}},"allow-get-settings":{"identifier":"allow-get-settings","description":"Enables the get_settings command without any pre-configured scope.","commands":{"allow":["get_settings"],"deny":[]}},"allow-get-stats":{"identifier":"allow-get-stats","description":"Enables the get_stats command without any pre-configured scope.","commands":{"allow":["get_stats"],"deny":[]}},"allow-get-video-info":{"identifier":"allow-get-video-info","description":"Enables the get_video_info command without any pre-configured scope.","commands":{"allow":["get_video_info"],"deny":[]}},"allow-import-settings":{"identifier":"allow-import-settings","description":"Enables the import_settings command without any pre-configured scope.","commands":{"allow":["import_settings"],"deny":[]}},"allow-install-deno":{"identifier":"allow-install-deno","description":"Enables the install_deno command without any pre-configured scope.","commands":{"allow":["install_deno"],"deny":[]}},"allow-is-flatpak":{"identifier":"allow-is-flatpak","description":"Enables the is_flatpak command without any pre-configured scope.","commands":{"allow":["is_flatpak"],"deny":[]}},"allow-is-packaged":{"identifier":"allow-is-packaged","description":"Enables the is_packaged command without any pre-configured scope.","commands":{"allow":["is_packaged"],"deny":[]}},"allow-log-error":{"identifier":"allow-log-error","description":"Enables the log_error command without any pre-configured scope.","commands":{"allow":["log_error"],"deny":[]}},"allow-mark-main-window-ready":{"identifier":"allow-mark-main-window-ready","description":"Enables the mark_main_window_ready command without any pre-configured scope.","commands":{"allow":["mark_main_window_ready"],"deny":[]}},"allow-notify-settings-flushed":{"identifier":"allow-notify-settings-flushed","description":"Enables the notify_settings_flushed command without any pre-configured scope.","commands":{"allow":["notify_settings_flushed"],"deny":[]}},"allow-open-external":{"identifier":"allow-open-external","description":"Enables the open_external command without any pre-configured scope.","commands":{"allow":["open_external"],"deny":[]}},"allow-open-file-location":{"identifier":"allow-open-file-location","description":"Enables the open_file_location command without any pre-configured scope.","commands":{"allow":["open_file_location"],"deny":[]}},"allow-remove-from-queue":{"identifier":"allow-remove-from-queue","description":"Enables the remove_from_queue command without any pre-configured scope.","commands":{"allow":["remove_from_queue"],"deny":[]}},"allow-reorder-queue-item":{"identifier":"allow-reorder-queue-item","description":"Enables the reorder_queue_item command without any pre-configured scope.","commands":{"allow":["reorder_queue_item"],"deny":[]}},"allow-reset-settings":{"identifier":"allow-reset-settings","description":"Enables the reset_settings command without any pre-configured scope.","commands":{"allow":["reset_settings"],"deny":[]}},"allow-reset-stats":{"identifier":"allow-reset-stats","description":"Enables the reset_stats command without any pre-configured scope.","commands":{"allow":["reset_stats"],"deny":[]}},"allow-resolve-download-options":{"identifier":"allow-resolve-download-options","description":"Enables the resolve_download_options command without any pre-configured scope.","commands":{"allow":["resolve_download_options"],"deny":[]}},"allow-restart-app":{"identifier":"allow-restart-app","description":"Enables the restart_app command without any pre-configured scope.","commands":{"allow":["restart_app"],"deny":[]}},"allow-retry-queue-item":{"identifier":"allow-retry-queue-item","description":"Enables the retry_queue_item command without any pre-configured scope.","commands":{"allow":["retry_queue_item"],"deny":[]}},"allow-save-settings":{"identifier":"allow-save-settings","description":"Enables the save_settings command without any pre-configured scope.","commands":{"allow":["save_settings"],"deny":[]}},"allow-select-download-location":{"identifier":"allow-select-download-location","description":"Enables the select_download_location command without any pre-configured scope.","commands":{"allow":["select_download_location"],"deny":[]}},"allow-show-notification":{"identifier":"allow-show-notification","description":"Enables the show_notification command without any pre-configured scope.","commands":{"allow":["show_notification"],"deny":[]}},"allow-start-queue":{"identifier":"allow-start-queue","description":"Enables the start_queue command without any pre-configured scope.","commands":{"allow":["start_queue"],"deny":[]}},"deny-add-to-queue":{"identifier":"deny-add-to-queue","description":"Denies the add_to_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["add_to_queue"]}},"deny-cancel-download":{"identifier":"deny-cancel-download","description":"Denies the cancel_download command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_download"]}},"deny-cancel-formats":{"identifier":"deny-cancel-formats","description":"Denies the cancel_formats command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_formats"]}},"deny-cancel-queue":{"identifier":"deny-cancel-queue","description":"Denies the cancel_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_queue"]}},"deny-cancel-video-info":{"identifier":"deny-cancel-video-info","description":"Denies the cancel_video_info command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_video_info"]}},"deny-check-deno-installed":{"identifier":"deny-check-deno-installed","description":"Denies the check_deno_installed command without any pre-configured scope.","commands":{"allow":[],"deny":["check_deno_installed"]}},"deny-clear-download-activity":{"identifier":"deny-clear-download-activity","description":"Denies the clear_download_activity command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_download_activity"]}},"deny-clear-finished-queue":{"identifier":"deny-clear-finished-queue","description":"Denies the clear_finished_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_finished_queue"]}},"deny-clear-queue":{"identifier":"deny-clear-queue","description":"Denies the clear_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_queue"]}},"deny-detect-gpu":{"identifier":"deny-detect-gpu","description":"Denies the detect_gpu command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_gpu"]}},"deny-download-video":{"identifier":"deny-download-video","description":"Denies the download_video command without any pre-configured scope.","commands":{"allow":[],"deny":["download_video"]}},"deny-e2e-cancel-close-request":{"identifier":"deny-e2e-cancel-close-request","description":"Denies the e2e_cancel_close_request command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_cancel_close_request"]}},"deny-e2e-emit-stale-download-events":{"identifier":"deny-e2e-emit-stale-download-events","description":"Denies the e2e_emit_stale_download_events command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_emit_stale_download_events"]}},"deny-e2e-network-pipelining-probe":{"identifier":"deny-e2e-network-pipelining-probe","description":"Denies the e2e_network_pipelining_probe command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_network_pipelining_probe"]}},"deny-e2e-updater-install-probe":{"identifier":"deny-e2e-updater-install-probe","description":"Denies the e2e_updater_install_probe command without any pre-configured scope.","commands":{"allow":[],"deny":["e2e_updater_install_probe"]}},"deny-export-settings":{"identifier":"deny-export-settings","description":"Denies the export_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["export_settings"]}},"deny-get-app-platform":{"identifier":"deny-get-app-platform","description":"Denies the get_app_platform command without any pre-configured scope.","commands":{"allow":[],"deny":["get_app_platform"]}},"deny-get-beta-updater-target":{"identifier":"deny-get-beta-updater-target","description":"Denies the get_beta_updater_target command without any pre-configured scope.","commands":{"allow":[],"deny":["get_beta_updater_target"]}},"deny-get-compact-updater-target":{"identifier":"deny-get-compact-updater-target","description":"Denies the get_compact_updater_target command without any pre-configured scope.","commands":{"allow":[],"deny":["get_compact_updater_target"]}},"deny-get-default-settings":{"identifier":"deny-get-default-settings","description":"Denies the get_default_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_default_settings"]}},"deny-get-distribution-channel":{"identifier":"deny-get-distribution-channel","description":"Denies the get_distribution_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["get_distribution_channel"]}},"deny-get-download-activity":{"identifier":"deny-get-download-activity","description":"Denies the get_download_activity command without any pre-configured scope.","commands":{"allow":[],"deny":["get_download_activity"]}},"deny-get-formats":{"identifier":"deny-get-formats","description":"Denies the get_formats command without any pre-configured scope.","commands":{"allow":[],"deny":["get_formats"]}},"deny-get-queue":{"identifier":"deny-get-queue","description":"Denies the get_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["get_queue"]}},"deny-get-settings":{"identifier":"deny-get-settings","description":"Denies the get_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_settings"]}},"deny-get-stats":{"identifier":"deny-get-stats","description":"Denies the get_stats command without any pre-configured scope.","commands":{"allow":[],"deny":["get_stats"]}},"deny-get-video-info":{"identifier":"deny-get-video-info","description":"Denies the get_video_info command without any pre-configured scope.","commands":{"allow":[],"deny":["get_video_info"]}},"deny-import-settings":{"identifier":"deny-import-settings","description":"Denies the import_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["import_settings"]}},"deny-install-deno":{"identifier":"deny-install-deno","description":"Denies the install_deno command without any pre-configured scope.","commands":{"allow":[],"deny":["install_deno"]}},"deny-is-flatpak":{"identifier":"deny-is-flatpak","description":"Denies the is_flatpak command without any pre-configured scope.","commands":{"allow":[],"deny":["is_flatpak"]}},"deny-is-packaged":{"identifier":"deny-is-packaged","description":"Denies the is_packaged command without any pre-configured scope.","commands":{"allow":[],"deny":["is_packaged"]}},"deny-log-error":{"identifier":"deny-log-error","description":"Denies the log_error command without any pre-configured scope.","commands":{"allow":[],"deny":["log_error"]}},"deny-mark-main-window-ready":{"identifier":"deny-mark-main-window-ready","description":"Denies the mark_main_window_ready command without any pre-configured scope.","commands":{"allow":[],"deny":["mark_main_window_ready"]}},"deny-notify-settings-flushed":{"identifier":"deny-notify-settings-flushed","description":"Denies the notify_settings_flushed command without any pre-configured scope.","commands":{"allow":[],"deny":["notify_settings_flushed"]}},"deny-open-external":{"identifier":"deny-open-external","description":"Denies the open_external command without any pre-configured scope.","commands":{"allow":[],"deny":["open_external"]}},"deny-open-file-location":{"identifier":"deny-open-file-location","description":"Denies the open_file_location command without any pre-configured scope.","commands":{"allow":[],"deny":["open_file_location"]}},"deny-remove-from-queue":{"identifier":"deny-remove-from-queue","description":"Denies the remove_from_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_from_queue"]}},"deny-reorder-queue-item":{"identifier":"deny-reorder-queue-item","description":"Denies the reorder_queue_item command without any pre-configured scope.","commands":{"allow":[],"deny":["reorder_queue_item"]}},"deny-reset-settings":{"identifier":"deny-reset-settings","description":"Denies the reset_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["reset_settings"]}},"deny-reset-stats":{"identifier":"deny-reset-stats","description":"Denies the reset_stats command without any pre-configured scope.","commands":{"allow":[],"deny":["reset_stats"]}},"deny-resolve-download-options":{"identifier":"deny-resolve-download-options","description":"Denies the resolve_download_options command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_download_options"]}},"deny-restart-app":{"identifier":"deny-restart-app","description":"Denies the restart_app command without any pre-configured scope.","commands":{"allow":[],"deny":["restart_app"]}},"deny-retry-queue-item":{"identifier":"deny-retry-queue-item","description":"Denies the retry_queue_item command without any pre-configured scope.","commands":{"allow":[],"deny":["retry_queue_item"]}},"deny-save-settings":{"identifier":"deny-save-settings","description":"Denies the save_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["save_settings"]}},"deny-select-download-location":{"identifier":"deny-select-download-location","description":"Denies the select_download_location command without any pre-configured scope.","commands":{"allow":[],"deny":["select_download_location"]}},"deny-show-notification":{"identifier":"deny-show-notification","description":"Denies the show_notification command without any pre-configured scope.","commands":{"allow":[],"deny":["show_notification"]}},"deny-start-queue":{"identifier":"deny-start-queue","description":"Denies the start_queue command without any pre-configured scope.","commands":{"allow":[],"deny":["start_queue"]}}},"permission_sets":{},"global_scope_schema":null},"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null},"notification":{"default_permission":{"identifier":"default","description":"This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n","permissions":["allow-is-permission-granted","allow-request-permission","allow-notify","allow-register-action-types","allow-register-listener","allow-remove-listener","allow-cancel","allow-get-pending","allow-remove-active","allow-get-active","allow-check-permissions","allow-show","allow-batch","allow-list-channels","allow-delete-channel","allow-create-channel","allow-permission-state"]},"permissions":{"allow-batch":{"identifier":"allow-batch","description":"Enables the batch command without any pre-configured scope.","commands":{"allow":["batch"],"deny":[]}},"allow-cancel":{"identifier":"allow-cancel","description":"Enables the cancel command without any pre-configured scope.","commands":{"allow":["cancel"],"deny":[]}},"allow-check-permissions":{"identifier":"allow-check-permissions","description":"Enables the check_permissions command without any pre-configured scope.","commands":{"allow":["check_permissions"],"deny":[]}},"allow-create-channel":{"identifier":"allow-create-channel","description":"Enables the create_channel command without any pre-configured scope.","commands":{"allow":["create_channel"],"deny":[]}},"allow-delete-channel":{"identifier":"allow-delete-channel","description":"Enables the delete_channel command without any pre-configured scope.","commands":{"allow":["delete_channel"],"deny":[]}},"allow-get-active":{"identifier":"allow-get-active","description":"Enables the get_active command without any pre-configured scope.","commands":{"allow":["get_active"],"deny":[]}},"allow-get-pending":{"identifier":"allow-get-pending","description":"Enables the get_pending command without any pre-configured scope.","commands":{"allow":["get_pending"],"deny":[]}},"allow-is-permission-granted":{"identifier":"allow-is-permission-granted","description":"Enables the is_permission_granted command without any pre-configured scope.","commands":{"allow":["is_permission_granted"],"deny":[]}},"allow-list-channels":{"identifier":"allow-list-channels","description":"Enables the list_channels command without any pre-configured scope.","commands":{"allow":["list_channels"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-permission-state":{"identifier":"allow-permission-state","description":"Enables the permission_state command without any pre-configured scope.","commands":{"allow":["permission_state"],"deny":[]}},"allow-register-action-types":{"identifier":"allow-register-action-types","description":"Enables the register_action_types command without any pre-configured scope.","commands":{"allow":["register_action_types"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-active":{"identifier":"allow-remove-active","description":"Enables the remove_active command without any pre-configured scope.","commands":{"allow":["remove_active"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-request-permission":{"identifier":"allow-request-permission","description":"Enables the request_permission command without any pre-configured scope.","commands":{"allow":["request_permission"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"deny-batch":{"identifier":"deny-batch","description":"Denies the batch command without any pre-configured scope.","commands":{"allow":[],"deny":["batch"]}},"deny-cancel":{"identifier":"deny-cancel","description":"Denies the cancel command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel"]}},"deny-check-permissions":{"identifier":"deny-check-permissions","description":"Denies the check_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_permissions"]}},"deny-create-channel":{"identifier":"deny-create-channel","description":"Denies the create_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["create_channel"]}},"deny-delete-channel":{"identifier":"deny-delete-channel","description":"Denies the delete_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_channel"]}},"deny-get-active":{"identifier":"deny-get-active","description":"Denies the get_active command without any pre-configured scope.","commands":{"allow":[],"deny":["get_active"]}},"deny-get-pending":{"identifier":"deny-get-pending","description":"Denies the get_pending command without any pre-configured scope.","commands":{"allow":[],"deny":["get_pending"]}},"deny-is-permission-granted":{"identifier":"deny-is-permission-granted","description":"Denies the is_permission_granted command without any pre-configured scope.","commands":{"allow":[],"deny":["is_permission_granted"]}},"deny-list-channels":{"identifier":"deny-list-channels","description":"Denies the list_channels command without any pre-configured scope.","commands":{"allow":[],"deny":["list_channels"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-permission-state":{"identifier":"deny-permission-state","description":"Denies the permission_state command without any pre-configured scope.","commands":{"allow":[],"deny":["permission_state"]}},"deny-register-action-types":{"identifier":"deny-register-action-types","description":"Denies the register_action_types command without any pre-configured scope.","commands":{"allow":[],"deny":["register_action_types"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-active":{"identifier":"deny-remove-active","description":"Denies the remove_active command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_active"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-request-permission":{"identifier":"deny-request-permission","description":"Denies the request_permission command without any pre-configured scope.","commands":{"allow":[],"deny":["request_permission"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}}},"permission_sets":{},"global_scope_schema":null},"opener":{"default_permission":{"identifier":"default","description":"This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer","permissions":["allow-open-url","allow-reveal-item-in-dir","allow-default-urls"]},"permissions":{"allow-default-urls":{"identifier":"allow-default-urls","description":"This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.","commands":{"allow":[],"deny":[]},"scope":{"allow":[{"url":"mailto:*"},{"url":"tel:*"},{"url":"http://*"},{"url":"https://*"}]}},"allow-open-path":{"identifier":"allow-open-path","description":"Enables the open_path command without any pre-configured scope.","commands":{"allow":["open_path"],"deny":[]}},"allow-open-url":{"identifier":"allow-open-url","description":"Enables the open_url command without any pre-configured scope.","commands":{"allow":["open_url"],"deny":[]}},"allow-reveal-item-in-dir":{"identifier":"allow-reveal-item-in-dir","description":"Enables the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":["reveal_item_in_dir"],"deny":[]}},"deny-open-path":{"identifier":"deny-open-path","description":"Denies the open_path command without any pre-configured scope.","commands":{"allow":[],"deny":["open_path"]}},"deny-open-url":{"identifier":"deny-open-url","description":"Denies the open_url command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url"]}},"deny-reveal-item-in-dir":{"identifier":"deny-reveal-item-in-dir","description":"Denies the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":[],"deny":["reveal_item_in_dir"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this url with, for example: firefox."},"url":{"description":"A URL that can be opened by the webview when using the Opener APIs.\n\nWildcards can be used following the UNIX glob pattern.\n\nExamples:\n\n- \"https://*\" : allows all HTTPS origin\n\n- \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path\n\n- \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"","type":"string"}},"required":["url"],"type":"object"},{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this path with, for example: xdg-open."},"path":{"description":"A path that can be opened by the webview when using the Opener APIs.\n\nThe pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"}},"required":["path"],"type":"object"}],"definitions":{"Application":{"anyOf":[{"description":"Open in default application.","type":"null"},{"description":"If true, allow open with any application.","type":"boolean"},{"description":"Allow specific application to open with.","type":"string"}],"description":"Opener scope application."}},"description":"Opener scope entry.","title":"OpenerScopeEntry"}},"process":{"default_permission":{"identifier":"default","description":"This permission set configures which\nprocess features are by default exposed.\n\n#### Granted Permissions\n\nThis enables to quit via `allow-exit` and restart via `allow-restart`\nthe application.\n","permissions":["allow-exit","allow-restart"]},"permissions":{"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-restart":{"identifier":"allow-restart","description":"Enables the restart command without any pre-configured scope.","commands":{"allow":["restart"],"deny":[]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-restart":{"identifier":"deny-restart","description":"Denies the restart command without any pre-configured scope.","commands":{"allow":[],"deny":["restart"]}}},"permission_sets":{},"global_scope_schema":null},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file diff --git a/src-tauri/gen/schemas/capabilities.json b/src-tauri/gen/schemas/capabilities.json index 03a64d53..e200d3e4 100644 --- a/src-tauri/gen/schemas/capabilities.json +++ b/src-tauri/gen/schemas/capabilities.json @@ -1 +1 @@ -{"default":{"identifier":"default","description":"Permissions for the ROSI main window","local":true,"windows":["main"],"permissions":["core:app:allow-version","core:event:allow-listen","core:event:allow-unlisten","core:window:allow-set-theme","updater:allow-check","updater:allow-download","updater:allow-install","allow-get-settings","allow-get-default-settings","allow-save-settings","allow-reset-settings","allow-export-settings","allow-import-settings","allow-get-stats","allow-reset-stats","allow-get-download-activity","allow-clear-download-activity","allow-get-formats","allow-cancel-formats","allow-get-video-info","allow-cancel-video-info","allow-download-video","allow-cancel-download","allow-add-to-queue","allow-remove-from-queue","allow-retry-queue-item","allow-reorder-queue-item","allow-clear-queue","allow-clear-finished-queue","allow-get-queue","allow-start-queue","allow-cancel-queue","allow-select-download-location","allow-open-external","allow-open-file-location","allow-show-notification","allow-check-deno-installed","allow-install-deno","allow-detect-gpu","allow-is-packaged","allow-is-flatpak","allow-get-app-platform","allow-get-distribution-channel","allow-get-beta-updater-target","allow-get-compact-updater-target","allow-restart-app","allow-log-error","allow-notify-settings-flushed","allow-mark-main-window-ready"]},"splash":{"identifier":"splash","description":"Minimal permissions for the packaged startup splash window","local":true,"windows":["splash"],"permissions":["core:app:allow-version"]}} \ No newline at end of file +{"default":{"identifier":"default","description":"Permissions for the ROSI main window","local":true,"windows":["main"],"permissions":["core:app:allow-version","core:event:allow-listen","core:event:allow-unlisten","core:window:allow-set-theme","updater:allow-check","updater:allow-download","updater:allow-install","allow-get-settings","allow-get-default-settings","allow-save-settings","allow-reset-settings","allow-export-settings","allow-import-settings","allow-get-stats","allow-reset-stats","allow-get-download-activity","allow-clear-download-activity","allow-get-formats","allow-cancel-formats","allow-get-video-info","allow-cancel-video-info","allow-download-video","allow-resolve-download-options","allow-cancel-download","allow-add-to-queue","allow-remove-from-queue","allow-retry-queue-item","allow-reorder-queue-item","allow-clear-queue","allow-clear-finished-queue","allow-get-queue","allow-start-queue","allow-cancel-queue","allow-select-download-location","allow-open-external","allow-open-file-location","allow-show-notification","allow-check-deno-installed","allow-install-deno","allow-detect-gpu","allow-is-packaged","allow-is-flatpak","allow-get-app-platform","allow-get-distribution-channel","allow-get-beta-updater-target","allow-get-compact-updater-target","allow-restart-app","allow-log-error","allow-notify-settings-flushed","allow-mark-main-window-ready"]},"splash":{"identifier":"splash","description":"Minimal permissions for the packaged startup splash window","local":true,"windows":["splash"],"permissions":["core:app:allow-version"]}} \ No newline at end of file diff --git a/src-tauri/gen/schemas/desktop-schema.json b/src-tauri/gen/schemas/desktop-schema.json index c8e4edfd..3f162086 100644 --- a/src-tauri/gen/schemas/desktop-schema.json +++ b/src-tauri/gen/schemas/desktop-schema.json @@ -584,6 +584,12 @@ "const": "allow-reset-stats", "markdownDescription": "Enables the reset_stats command without any pre-configured scope." }, + { + "description": "Enables the resolve_download_options command without any pre-configured scope.", + "type": "string", + "const": "allow-resolve-download-options", + "markdownDescription": "Enables the resolve_download_options command without any pre-configured scope." + }, { "description": "Enables the restart_app command without any pre-configured scope.", "type": "string", @@ -860,6 +866,12 @@ "const": "deny-reset-stats", "markdownDescription": "Denies the reset_stats command without any pre-configured scope." }, + { + "description": "Denies the resolve_download_options command without any pre-configured scope.", + "type": "string", + "const": "deny-resolve-download-options", + "markdownDescription": "Denies the resolve_download_options command without any pre-configured scope." + }, { "description": "Denies the restart_app command without any pre-configured scope.", "type": "string", diff --git a/src-tauri/gen/schemas/windows-schema.json b/src-tauri/gen/schemas/windows-schema.json index c8e4edfd..3f162086 100644 --- a/src-tauri/gen/schemas/windows-schema.json +++ b/src-tauri/gen/schemas/windows-schema.json @@ -584,6 +584,12 @@ "const": "allow-reset-stats", "markdownDescription": "Enables the reset_stats command without any pre-configured scope." }, + { + "description": "Enables the resolve_download_options command without any pre-configured scope.", + "type": "string", + "const": "allow-resolve-download-options", + "markdownDescription": "Enables the resolve_download_options command without any pre-configured scope." + }, { "description": "Enables the restart_app command without any pre-configured scope.", "type": "string", @@ -860,6 +866,12 @@ "const": "deny-reset-stats", "markdownDescription": "Denies the reset_stats command without any pre-configured scope." }, + { + "description": "Denies the resolve_download_options command without any pre-configured scope.", + "type": "string", + "const": "deny-resolve-download-options", + "markdownDescription": "Denies the resolve_download_options command without any pre-configured scope." + }, { "description": "Denies the restart_app command without any pre-configured scope.", "type": "string", diff --git a/src-tauri/permissions/autogenerated/resolve_download_options.toml b/src-tauri/permissions/autogenerated/resolve_download_options.toml new file mode 100644 index 00000000..c54c169b --- /dev/null +++ b/src-tauri/permissions/autogenerated/resolve_download_options.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-resolve-download-options" +description = "Enables the resolve_download_options command without any pre-configured scope." +commands.allow = ["resolve_download_options"] + +[[permission]] +identifier = "deny-resolve-download-options" +description = "Denies the resolve_download_options command without any pre-configured scope." +commands.deny = ["resolve_download_options"] diff --git a/src-tauri/src/coordinator.rs b/src-tauri/src/coordinator.rs new file mode 100644 index 00000000..8f4f9f8d --- /dev/null +++ b/src-tauri/src/coordinator.rs @@ -0,0 +1,745 @@ +//! Single owner of queue transitions and of session result routing. +//! +//! One thread receives every command in arrival order. It applies each queue +//! transition (admission, start, stop, cancel, clear, item results, claims) +//! to the queue state, publishes the queue, and answers the caller over a +//! reply channel. It also routes each session's terminal result to the sink +//! registered for that session id, at most once. +//! +//! The thread never waits on child processes, disk, settings, or another +//! thread's reply. Work that needs those stays with the caller: +//! - session cancellation runs on a helper thread (stop) or the caller's +//! thread (cancel, clear), and reports back as a command; +//! - settings reads, request resolution, and activity records stay in the +//! Tauri handlers and the runner thread; +//! - durable writes stay with the queue writer, which asks for snapshots here. +//! +//! Only this thread mutates `QueueState`. Readers take its lock briefly. + +use crate::constants::MAX_QUEUE_SIZE; +use crate::downloader; +use crate::ipc::{self, IpcResult, INTERNAL_ERROR, NOT_AVAILABLE, VALIDATION_ERROR}; +use crate::queue::{self, AddResult, QueueState, Started}; +use crate::types::{ + DownloadCompletion, DownloadRequestOptions, Owner, QueueItem, QueueProgress, + QueueSnapshot, QueueStatus, +}; +use serde::Serialize; +use std::collections::{HashMap, HashSet}; +use std::sync::mpsc::{channel, Receiver, RecvTimeoutError, Sender}; +use std::sync::{MutexGuard, OnceLock}; +use std::time::{Duration, Instant}; + +/// Longest a start waits for the previous runner to exit after its run drained. +/// The runner exits within a loop turn, so this only bounds a stuck runner. +const RUNNER_EXIT_WAIT: Duration = Duration::from_secs(2); + +pub enum Command { + Register { + session_id: u64, + sink: Sender, + }, + /// The session's terminal result. Routing it finalizes the session and + /// releases every await that was waiting on it. + Terminal { + session_id: u64, + completion: Box, + }, + /// Replies once the named session is finalized (`Some`), or once every + /// session registered at the time of the request is finalized (`None`). + /// A session that is not registered counts as already finalized. + AwaitFinalized { + session_id: Option, + reply: Sender<()>, + }, + Queue(QueueCommand), +} + +pub enum QueueCommand { + Admit { + pending: Vec, + skipped: usize, + reply: Sender>, + }, + Remove { + id: String, + reply: Sender>, + }, + Retry { + id: String, + reply: Sender>, + }, + Reorder { + id: String, + up: bool, + reply: Sender>, + }, + ClearFinished { + reply: Sender, + }, + Start { + reply: Sender>, + }, + /// Cancels the active session, then answers once the runner has exited and + /// the interrupted item is back to pending. + Stop { + reply: Sender<()>, + }, + /// The stop helper finished cancelling and killing processes. + StopCancelSettled, + /// Marks the queue cancelled. Replies whether an item is active, so the + /// caller cancels its session before recording the pending items. + CancelBegin { + reply: Sender, + }, + CancelApply { + completions: Vec<(String, DownloadCompletion)>, + reply: Sender<()>, + }, + /// Marks a running queue cancelled. Replies whether it was running, so the + /// caller cancels the session before the items are removed. + ClearBegin { + reply: Sender, + }, + ClearItems { + reply: Sender<()>, + }, + Snapshot { + bump: bool, + reply: Sender<(u64, Vec)>, + }, + /// The runner's next item, or `None` when the run is over. + ClaimNext { + reply: Sender>, + }, + Prepare { + item_id: String, + request: Box, + reply: Sender, + }, + /// Whether the runner may still start this item. + Attempt { + item_id: String, + reply: Sender, + }, + /// The runner's session is visible. Replies with the cancellation the + /// runner must apply to it, if a cancel landed while it was starting. + SessionStarted { + reply: Sender>, + }, + ItemFinished { + item_id: String, + completion: Box, + reply: Sender<()>, + }, + /// Replies whether the item was still downloading and got the outcome. + ItemUnstarted { + item_id: String, + completion: Box, + reply: Sender, + }, + RunnerExited, +} + +#[derive(Default)] +struct StopState { + waiters: Vec>, + interrupted: Option, + cancels_outstanding: usize, +} + +#[derive(Default)] +struct Coordinator { + sinks: HashMap>, + /// Sessions each pending await still waits on, with the reply to send once + /// that set is empty. + awaits: Vec<(HashSet, Sender<()>)>, + starts: Vec<(Sender>, Instant)>, + stop: StopState, +} + +fn commands() -> &'static Sender { + static COORDINATOR: OnceLock> = OnceLock::new(); + COORDINATOR.get_or_init(|| { + let (sender, receiver) = channel(); + std::thread::spawn(move || run(receiver)); + sender + }) +} + +fn run(receiver: Receiver) { + let mut coordinator = Coordinator::default(); + loop { + let next_deadline = coordinator.starts.iter().map(|(_, deadline)| *deadline).min(); + let received = match next_deadline { + Some(deadline) => { + receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) + } + None => receiver.recv().map_err(|_| RecvTimeoutError::Disconnected), + }; + match received { + Ok(command) => coordinator.handle(command), + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return, + } + coordinator.settle_starts(Instant::now()); + } +} + +/// Send a command and wait for its reply. `None` means the coordinator is not +/// running. Never call this from the coordinator thread. +pub fn request(build: impl FnOnce(Sender) -> Command) -> Option { + let (reply, answer) = channel(); + commands().send(build(reply)).ok()?; + answer.recv().ok() +} + +/// `request` for Tauri handlers: a stopped coordinator is an internal error. +fn request_ipc( + build: impl FnOnce(Sender>) -> Command, +) -> IpcResult { + request(build).unwrap_or_else(|| ipc::err(INTERNAL_ERROR, "Queue coordinator is not running.")) +} + +/// Send a command with no reply. +pub fn submit(command: Command) { + let _ = commands().send(command); +} + +/// Register the caller for a session. Called before the session becomes +/// visible to cancellation, so its terminal result always finds the sink. +pub fn register(session_id: u64, sink: Sender) { + submit(Command::Register { session_id, sink }); +} + +/// Deliver a session's terminal result to its caller, at most once. +pub fn terminal(session_id: u64, completion: DownloadCompletion) { + submit(Command::Terminal { + session_id, + completion: Box::new(completion), + }); +} + +/// Block until the session is finalized (`Some`) or until every session that +/// is registered now is finalized (`None`). Returns at once when there is +/// nothing to wait for. Never call this from the coordinator thread. +pub fn await_finalized(session_id: Option) { + let _ = request(|reply| Command::AwaitFinalized { session_id, reply }); +} + +/// Publish the queue after a transition. The guard is released before the +/// event is emitted, so the emit never runs under the state lock. +fn commit(mut queue: MutexGuard<'_, QueueState>) { + let (revision, items) = queue::revisioned_snapshot(&mut queue, true); + drop(queue); + publish(revision, items); +} + +/// Only this thread commits, and it publishes each commit before the next +/// command, so `queue-update` revisions reach the renderer in increasing order. +fn publish(revision: u64, items: Vec) { + crate::app_state::emit("queue-update", QueueSnapshot { revision, items }); + queue::schedule_persist(); +} + +/// Whether `start_queue` should wait for a runner that is still exiting after +/// its run drained. A stop in progress is never waited on. +pub(crate) fn start_waits_for_exit(queue: &QueueState) -> bool { + queue.runner_alive && !queue.running && !queue.stopping +} + +/// Decide a start. `None` keeps the caller waiting for the runner to exit. +fn evaluate_start(queue: &mut QueueState, timed_out: bool) -> Option> { + if !timed_out && start_waits_for_exit(queue) { + return None; + } + if !queue + .items + .iter() + .any(|item| item.status == QueueStatus::Pending) + { + return Some(ipc::err(NOT_AVAILABLE, "No pending items in queue.")); + } + if queue.stopping { + return Some(ipc::err(NOT_AVAILABLE, "Queue is stopping.")); + } + if queue.running { + return Some(ipc::err(VALIDATION_ERROR, "Queue is already running.")); + } + if queue.runner_alive { + return Some(ipc::err( + NOT_AVAILABLE, + "Queue is still finishing. Try again shortly.", + )); + } + if !downloader::can_start(Owner::Queue) { + return Some(ipc::err( + NOT_AVAILABLE, + "A manual download is already in progress.", + )); + } + queue.running = true; + queue.cancelled = false; + queue.runner_alive = true; + queue.run_started_at = crate::app_state::now_ms(); + std::thread::spawn(queue::run_queue); + Some(ipc::ok(Started { started: true })) +} + +fn admit(pending: Vec, mut skipped: usize) -> IpcResult { + let mut queue = queue::state(); + let nonterminal: HashSet = queue + .items + .iter() + .filter(|item| matches!(item.status, QueueStatus::Pending | QueueStatus::Downloading)) + .map(|item| item.url.clone()) + .collect(); + let mut batch = HashSet::new(); + let mut accepted = Vec::with_capacity(pending.len()); + for item in pending { + if nonterminal.contains(&item.url) || batch.contains(&item.url) { + skipped += 1; + continue; + } + batch.insert(item.url.clone()); + accepted.push(item); + } + let added = accepted.len(); + if queue.items.len() + added > MAX_QUEUE_SIZE { + return ipc::err( + VALIDATION_ERROR, + format!("Queue limit reached (max {MAX_QUEUE_SIZE} items)."), + ); + } + if added > 0 { + let candidate: Vec<&QueueItem> = queue.items.iter().chain(accepted.iter()).collect(); + match crate::fs_util::encode_list(&candidate) { + Ok(encoded) if encoded.len() <= queue::MAX_QUEUE_ADMISSION_BYTES => {} + Ok(_) => { + return ipc::err( + VALIDATION_ERROR, + "Queue storage limit reached. Remove items or shorten URLs before adding this batch.", + ) + } + Err(_) => { + return ipc::err( + VALIDATION_ERROR, + "Could not encode the queue; no items were added.", + ) + } + } + queue.items.extend(accepted); + commit(queue); + } + ipc::ok(AddResult { added, skipped }) +} + +fn remove(id: &str) -> IpcResult<()> { + let mut queue = queue::state(); + let Some(index) = queue.items.iter().position(|item| item.id == id) else { + return ipc::err(NOT_AVAILABLE, "Queue item not found."); + }; + if queue.items[index].status == QueueStatus::Downloading { + return ipc::err( + VALIDATION_ERROR, + "Cannot remove an actively downloading item.", + ); + } + queue.items.remove(index); + commit(queue); + ipc::ok(()) +} + +fn retry(id: &str) -> IpcResult<()> { + let mut queue = queue::state(); + let Some(item) = queue.items.iter_mut().find(|item| item.id == id) else { + return ipc::err(NOT_AVAILABLE, "Queue item not found."); + }; + if item.status != QueueStatus::Failed && item.status != QueueStatus::Cancelled { + return ipc::err( + VALIDATION_ERROR, + "Only failed or cancelled queue items can be retried.", + ); + } + queue::clear_attempt(item); + item.status = QueueStatus::Pending; + commit(queue); + ipc::ok(()) +} + +fn reorder(id: &str, up: bool) -> IpcResult<()> { + let mut queue = queue::state(); + let Some(index) = queue.items.iter().position(|item| item.id == id) else { + return ipc::err(NOT_AVAILABLE, "Queue item not found."); + }; + if queue.items[index].status != QueueStatus::Pending { + return ipc::err( + VALIDATION_ERROR, + "Only pending queue items can be reordered.", + ); + } + let pending: Vec = queue + .items + .iter() + .enumerate() + .filter(|(_, item)| item.status == QueueStatus::Pending) + .map(|(position, _)| position) + .collect(); + let position = pending + .iter() + .position(|candidate| *candidate == index) + .unwrap_or(0); + let destination = if up { + position.checked_sub(1) + } else { + Some(position + 1) + } + .and_then(|slot| pending.get(slot).copied()); + let Some(destination) = destination else { + return ipc::err( + NOT_AVAILABLE, + format!("Queue item cannot move {}.", if up { "up" } else { "down" }), + ); + }; + queue.items.swap(index, destination); + commit(queue); + ipc::ok(()) +} + +fn clear_finished() -> usize { + let mut queue = queue::state(); + let before = queue.items.len(); + queue + .items + .retain(|item| matches!(item.status, QueueStatus::Pending | QueueStatus::Downloading)); + let removed = before - queue.items.len(); + if removed > 0 { + commit(queue); + } + removed +} + +impl Coordinator { + fn handle(&mut self, command: Command) { + match command { + Command::Register { session_id, sink } => { + self.sinks.insert(session_id, sink); + } + Command::Terminal { + session_id, + completion, + } => { + match self.sinks.remove(&session_id) { + Some(sink) => { + let _ = sink.send(*completion); + } + None => crate::logging::warn(&format!( + "Ignored a terminal result for session {session_id} with no registered caller." + )), + } + self.release_awaits(session_id); + } + Command::AwaitFinalized { session_id, reply } => { + let pending: HashSet = match session_id { + Some(id) if self.sinks.contains_key(&id) => HashSet::from([id]), + Some(_) => HashSet::new(), + None => self.sinks.keys().copied().collect(), + }; + if pending.is_empty() { + let _ = reply.send(()); + } else { + self.awaits.push((pending, reply)); + } + } + Command::Queue(command) => self.handle_queue(command), + } + } + + /// Drop a finalized session from every pending await and acknowledge the + /// awaits that now have nothing left to wait for. + fn release_awaits(&mut self, session_id: u64) { + let mut waiting = Vec::new(); + for (mut pending, reply) in std::mem::take(&mut self.awaits) { + pending.remove(&session_id); + if pending.is_empty() { + let _ = reply.send(()); + } else { + waiting.push((pending, reply)); + } + } + self.awaits = waiting; + } + + fn handle_queue(&mut self, command: QueueCommand) { + match command { + QueueCommand::Admit { + pending, + skipped, + reply, + } => { + let _ = reply.send(admit(pending, skipped)); + } + QueueCommand::Remove { id, reply } => { + let _ = reply.send(remove(&id)); + } + QueueCommand::Retry { id, reply } => { + let _ = reply.send(retry(&id)); + } + QueueCommand::Reorder { id, up, reply } => { + let _ = reply.send(reorder(&id, up)); + } + QueueCommand::ClearFinished { reply } => { + let _ = reply.send(clear_finished()); + } + QueueCommand::Start { reply } => { + let answer = evaluate_start(&mut queue::state(), false); + match answer { + Some(result) => { + let _ = reply.send(result); + } + None => self.starts.push((reply, Instant::now() + RUNNER_EXIT_WAIT)), + } + } + QueueCommand::Stop { reply } => self.stop(reply), + QueueCommand::StopCancelSettled => { + self.stop.cancels_outstanding = self.stop.cancels_outstanding.saturating_sub(1); + self.finish_stop_if_ready(); + } + QueueCommand::CancelBegin { reply } => { + let mut queue = queue::state(); + queue.cancelled = true; + queue.running = false; + let active = queue.active_item_id.is_some(); + drop(queue); + let _ = reply.send(active); + } + QueueCommand::CancelApply { completions, reply } => { + let mut queue = queue::state(); + for (id, completion) in &completions { + if let Some(item) = queue + .items + .iter_mut() + .find(|item| &item.id == id && item.status == QueueStatus::Pending) + { + queue::apply_completion(item, completion); + } + } + queue.active_item_id = None; + commit(queue); + let _ = reply.send(()); + } + QueueCommand::ClearBegin { reply } => { + let mut queue = queue::state(); + let running = queue.running; + if running { + queue.cancelled = true; + queue.running = false; + queue.active_item_id = None; + } + drop(queue); + let _ = reply.send(running); + } + QueueCommand::ClearItems { reply } => { + let mut queue = queue::state(); + queue.items.clear(); + commit(queue); + let _ = reply.send(()); + } + QueueCommand::Snapshot { bump, reply } => { + let mut queue = queue::state(); + let snapshot = queue::revisioned_snapshot(&mut queue, bump); + drop(queue); + let _ = reply.send(snapshot); + } + QueueCommand::ClaimNext { reply } => { + let mut queue = queue::state(); + let next = queue::claim_next_in_state(&mut queue); + commit(queue); + let _ = reply.send(next); + } + QueueCommand::Prepare { + item_id, + request, + reply, + } => { + let mut queue = queue::state(); + if let Some(current) = queue.items.iter_mut().find(|entry| entry.id == item_id) { + current.request = Some(*request); + } + let progress = queue::progress_for(&queue, &item_id); + drop(queue); + let _ = reply.send(progress); + } + QueueCommand::Attempt { item_id, reply } => { + let queue = queue::state(); + let wanted = queue.running + && !queue.cancelled + && queue.items.iter().any(|entry| { + entry.id == item_id && entry.status == QueueStatus::Downloading + }); + drop(queue); + let _ = reply.send(wanted); + } + QueueCommand::SessionStarted { reply } => { + let queue = queue::state(); + let cancel = queue.cancelled.then_some(!queue.stopping); + drop(queue); + let _ = reply.send(cancel); + } + QueueCommand::ItemFinished { + item_id, + completion, + reply, + } => { + let mut queue = queue::state(); + queue::apply_completion_in_state(&mut queue, &item_id, &completion); + commit(queue); + let _ = reply.send(()); + } + QueueCommand::ItemUnstarted { + item_id, + completion, + reply, + } => { + let recorded = item_unstarted(&item_id, &completion); + let _ = reply.send(recorded); + } + QueueCommand::RunnerExited => { + queue::state().runner_alive = false; + self.finish_stop_if_ready(); + } + } + } + + fn stop(&mut self, reply: Sender<()>) { + let interrupted = { + let mut queue = queue::state(); + queue.cancelled = true; + queue.running = false; + queue.stopping = true; + queue.active_item_id.take() + }; + if interrupted.is_some() { + self.stop.interrupted = interrupted; + } + self.stop.waiters.push(reply); + self.stop.cancels_outstanding += 1; + // Process waits happen off this thread. The helper reports back once + // the cancel and the kill are done. + std::thread::spawn(|| { + downloader::cancel_active_session(false); + downloader::kill_all_processes(); + submit(Command::Queue(QueueCommand::StopCancelSettled)); + }); + self.finish_stop_if_ready(); + } + + /// A stop is acknowledged once its cancel has settled and the runner has + /// exited. The interrupted item then goes back to pending. + fn finish_stop_if_ready(&mut self) { + if self.stop.waiters.is_empty() || self.stop.cancels_outstanding > 0 { + return; + } + let mut queue = queue::state(); + if queue.runner_alive { + return; + } + let interrupted = self.stop.interrupted.take(); + let requeued = interrupted.is_some_and(|id| { + queue + .items + .iter_mut() + .find(|item| item.id == id && item.status == QueueStatus::Cancelled) + .map(|item| { + queue::clear_attempt(item); + item.status = QueueStatus::Pending; + }) + .is_some() + }); + queue.stopping = false; + if requeued { + commit(queue); + } else { + drop(queue); + } + for waiter in self.stop.waiters.drain(..) { + let _ = waiter.send(()); + } + } + + /// Answer deferred starts whose runner has exited, or whose wait timed out. + fn settle_starts(&mut self, now: Instant) { + if self.starts.is_empty() { + return; + } + let mut still_waiting = Vec::new(); + for (reply, deadline) in std::mem::take(&mut self.starts) { + let answer = evaluate_start(&mut queue::state(), now >= deadline); + match answer { + Some(result) => { + let _ = reply.send(result); + } + None => still_waiting.push((reply, deadline)), + } + } + self.starts = still_waiting; + } +} + +/// Record a cancelled outcome for an item the runner claimed but never +/// started. Only an item still downloading takes it; a cleared queue records +/// nothing. Returns whether it was applied. +fn item_unstarted(item_id: &str, completion: &DownloadCompletion) -> bool { + let mut queue = queue::state(); + if queue.active_item_id.as_deref() == Some(item_id) { + queue.active_item_id = None; + } + let Some(entry) = queue + .items + .iter_mut() + .find(|entry| entry.id == item_id && entry.status == QueueStatus::Downloading) + else { + return false; + }; + queue::apply_completion(entry, completion); + queue::end_run_if_drained(&mut queue); + commit(queue); + true +} + +/// Admit already-built queue items. Duplicates of non-terminal URLs are +/// skipped here too, against the state as it is now. +pub fn admit_items(pending: Vec, skipped: usize) -> IpcResult { + request_ipc(|reply| { + Command::Queue(QueueCommand::Admit { + pending, + skipped, + reply, + }) + }) +} + +/// Remove finished items. `None` means the coordinator is not running. +pub fn clear_finished_items() -> Option { + request(|reply| Command::Queue(QueueCommand::ClearFinished { reply })) +} + +pub fn remove_item(id: String) -> IpcResult<()> { + request_ipc(|reply| Command::Queue(QueueCommand::Remove { id, reply })) +} + +pub fn retry_item(id: String) -> IpcResult<()> { + request_ipc(|reply| Command::Queue(QueueCommand::Retry { id, reply })) +} + +pub fn reorder_item(id: String, up: bool) -> IpcResult<()> { + request_ipc(|reply| Command::Queue(QueueCommand::Reorder { id, up, reply })) +} + +pub fn start() -> IpcResult { + request_ipc(|reply| Command::Queue(QueueCommand::Start { reply })) +} + +pub fn stop() { + let _ = request(|reply| Command::Queue(QueueCommand::Stop { reply })); +} diff --git a/src-tauri/src/download_options.rs b/src-tauri/src/download_options.rs new file mode 100644 index 00000000..a4c7f135 --- /dev/null +++ b/src-tauri/src/download_options.rs @@ -0,0 +1,238 @@ +//! Shared precedence, validation, and snapshot logic for manual and queued +//! downloads. + +use crate::ipc::{self, DownloadRequestInput, FalliblePayload, IpcError, IpcResult}; +use crate::types::{DownloadProfile, DownloadRequestOptions, GpuType, PlaylistSelection, Settings}; +use crate::validation::{validate_download_path, validate_download_request}; +use serde_json::{Map, Value}; + +#[derive(Clone, Debug)] +pub struct ResolvedDownloadOptions { + pub request: DownloadRequestOptions, + pub effective_settings: Settings, +} + +fn to_map(value: &impl serde::Serialize) -> Map { + match serde_json::to_value(value) { + Ok(Value::Object(map)) => map, + _ => Map::new(), + } +} + +fn apply_request_to_settings(settings: &Settings, options: &DownloadRequestOptions) -> Settings { + let mut effective = settings.clone(); + // IPC validation admits only known names, so an unknown value cannot reach here. + if let Some(profile) = options.profile.as_deref().and_then(DownloadProfile::parse) { + effective.download_mode = profile; + } + effective.advanced_options = effective.download_mode == DownloadProfile::Custom; + effective.audio_only = effective.download_mode == DownloadProfile::Audio; + effective.best_quality = effective.download_mode == DownloadProfile::BestVideo; + if let Some(value) = options.advanced_options { + effective.advanced_options = value; + } + if let Some(value) = options.audio_only { + effective.audio_only = value; + } + if let Some(value) = options.best_quality { + effective.best_quality = value; + } + if let Some(value) = &options.audio_output_format { + effective.audio_format = value.clone(); + } + if let Some(value) = options.convert_enabled { + effective.convert_enabled = value; + } + if let Some(format) = &options.convert_format { + if !format.trim().is_empty() { + effective.convert_format = format.clone(); + if options.convert_enabled.is_none() { + effective.convert_enabled = true; + } + } else if options.convert_enabled.is_none() { + effective.convert_enabled = false; + } + } + if let Some(value) = options.keep_original { + effective.keep_original_after_convert = value; + } + if let Some(value) = options.hook_browser { + effective.hook_browser = value; + } + if let Some(value) = options + .browser_choice + .as_ref() + .filter(|value| !value.is_empty()) + { + effective.browser_choice = value.clone(); + } + if let Some(value) = options.gpu_acceleration { + effective.gpu_acceleration = value; + } + if let Some(value) = options.gpu_type.as_deref().and_then(GpuType::parse) { + effective.gpu_type = value; + } + if let Some(value) = options.write_subtitles { + effective.write_subtitles = value; + } + if let Some(value) = options + .subtitle_langs + .as_ref() + .filter(|value| !value.is_empty()) + { + effective.subtitle_langs = value.clone(); + } + if let Some(value) = options.embed_thumbnail { + effective.embed_thumbnail = value; + } + if let Some(value) = options.embed_metadata { + effective.embed_metadata = value; + } + if let Some(value) = options.sponsorblock_remove { + effective.sponsorblock_remove = value; + } + if let Some(value) = &options.ffmpeg_path { + effective.ffmpeg_path = value.clone(); + } + effective +} + +fn snapshot(options: &DownloadRequestOptions, effective: &Settings) -> DownloadRequestOptions { + DownloadRequestOptions { + url: options.url.trim().to_string(), + output_path: options.output_path.clone(), + // Keep an empty path in the snapshot too: it means the app default, + // not "read a possibly changed settings value when replaying". + ffmpeg_path: Some(effective.ffmpeg_path.clone()), + convert_enabled: Some(effective.convert_enabled), + convert_format: Some(effective.convert_format.clone()), + keep_original: Some(effective.keep_original_after_convert), + video_format: options.video_format.clone(), + audio_format: options.audio_format.clone(), + playlist: Some(options.playlist.clone().unwrap_or(PlaylistSelection { + mode: "current".into(), + start: None, + end: None, + })), + profile: Some(effective.download_mode.as_str().to_string()), + preset_id: options.preset_id.clone(), + preset_name: options.preset_name.clone(), + best_quality: Some(effective.best_quality), + advanced_options: Some(effective.advanced_options), + audio_only: Some(effective.audio_only), + audio_output_format: Some(effective.audio_format.clone()), + hook_browser: Some(effective.hook_browser), + browser_choice: Some(effective.browser_choice.clone()), + gpu_acceleration: Some(effective.gpu_acceleration), + gpu_type: Some(effective.gpu_type.as_str().to_string()), + write_subtitles: Some(effective.write_subtitles), + subtitle_langs: Some(effective.subtitle_langs.clone()), + embed_thumbnail: Some(effective.embed_thumbnail), + embed_metadata: Some(effective.embed_metadata), + sponsorblock_remove: Some(effective.sponsorblock_remove), + } +} + +fn finish_resolution( + options: DownloadRequestOptions, + effective_settings: Settings, +) -> ResolvedDownloadOptions { + let request = snapshot(&options, &effective_settings); + ResolvedDownloadOptions { + request, + effective_settings, + } +} + +/// Resolve a request that has already passed `validate_download_request`. +/// Resolve an already validated stored request. No preset is consulted: the +/// stored values are authoritative, and any field the snapshot left absent +/// falls back to current settings only. +pub fn resolve_validated( + settings: &Settings, + options: DownloadRequestOptions, +) -> ResolvedDownloadOptions { + let effective = apply_request_to_settings(settings, &options); + finish_resolution(options, effective) +} + +/// Build a settings-default < preset < explicit-override request and validate +/// it. The returned snapshot is what the download runner and queue store. +pub fn resolve_value( + settings: &Settings, + value: &Value, + forced_url: Option<&str>, +) -> Result { + let Some(overrides) = value.as_object() else { + return validate_download_request(value) + .map(|request| resolve_validated(settings, request)); + }; + let url_hint = forced_url + .or_else(|| overrides.get("url").and_then(Value::as_str)) + .unwrap_or_default(); + let mut candidate = to_map(&request_from_settings(url_hint, settings)); + let preset_id = overrides + .get("presetId") + .and_then(Value::as_str) + .map(str::trim); + if let Some(preset) = + preset_id.and_then(|id| settings.download_presets.iter().find(|p| p.id == id)) + { + candidate.extend(crate::settings::preset_to_request_options(preset)); + } + for (key, value) in overrides { + if !value.is_null() { + candidate.insert(key.clone(), value.clone()); + } + } + if let Some(url) = forced_url { + candidate.insert("url".into(), Value::String(url.to_string())); + } + let request = validate_download_request(&Value::Object(candidate))?; + let effective = apply_request_to_settings(settings, &request); + Ok(finish_resolution(request, effective)) +} + +fn resolve_output_path(settings: &Settings) -> String { + let configured = settings.download_folder.trim(); + if !configured.is_empty() { + if let Ok(path) = validate_download_path(configured) { + if !path.is_empty() { + return path; + } + } + } + crate::app_state::downloads_dir() + .to_string_lossy() + .into_owned() +} + +/// Settings-derived defaults shared by manual and queued requests. Both paths +/// start here, so the output path and playlist fallbacks cannot diverge. +pub fn request_from_settings(url: &str, settings: &Settings) -> DownloadRequestOptions { + DownloadRequestOptions { + url: url.to_string(), + output_path: resolve_output_path(settings), + ..DownloadRequestOptions::default() + } +} + +pub fn resolve_queue_request( + settings: &Settings, + url: &str, + overrides: Option<&Map>, +) -> Result { + let value = Value::Object(overrides.cloned().unwrap_or_default()); + resolve_value(settings, &value, Some(url)).map(|resolved| resolved.request) +} + +#[tauri::command] +pub fn resolve_download_options( + options: FalliblePayload, +) -> IpcResult { + let settings = crate::settings::load(); + match resolve_value(&settings, &options.into_value(), None) { + Ok(resolved) => ipc::ok(resolved.request), + Err(error) => ipc::from_error(error), + } +} diff --git a/src-tauri/src/downloader.rs b/src-tauri/src/downloader.rs index a856194e..ca9323bf 100644 --- a/src-tauri/src/downloader.rs +++ b/src-tauri/src/downloader.rs @@ -7,43 +7,43 @@ //! publication with replacing the active session so older terminal events //! cannot arrive after a newer session becomes current. //! -//! Lock order, outermost first. A path may skip links but never reverses one: +//! Lifecycle waits go through the coordinator (coordinator.rs): a session is +//! registered in the same critical section that installs it in `ACTIVE`, and +//! its terminal result acks every `await_finalized` on it. Events for a stale +//! session are dropped under `EVENT_PUBLISH`, since `with_session` matches only +//! the current session. //! -//! - Session chain: `STARTUP` -> `EVENT_PUBLISH` -> `ACTIVE` -> `FINALIZING`. -//! - Queue chain: `START_GUARD` (queue.rs) is taken before `STARTUP`, `ACTIVE` -//! and `QUEUE`. `QUEUE` is not held across `start_download` or -//! `cancel_active_session`; `start_queue` is the one place that calls into -//! the session lock while holding it (`QUEUE` -> `ACTIVE`, via `can_start`). -//! - `QUEUE_PUBLICATION` -> `QUEUE` (queue.rs `broadcast`). `PERSIST_SIGNAL` is a leaf. -//! - Completion callbacks run after `EVENT_PUBLISH` and `ACTIVE` are released, -//! with the session still listed in `FINALIZING`. The queue callback then -//! takes `QUEUE`, then `QUEUE_PUBLICATION`. -//! - Condvars release their lock while waiting: `SESSION_CHANGED` with `ACTIVE`, -//! `FINALIZATION_CHANGED` with `FINALIZING`, `RUNNER_CHANGED` with `QUEUE`. +//! Lock order, outermost first: +//! +//! - Session chain: `STARTUP` -> `EVENT_PUBLISH` -> `ACTIVE`. `STARTUP` only +//! serializes starts; no completion path takes it. +//! - Queue chain: only the coordinator thread takes `QUEUE` and `ACTIVE` (via +//! `can_start`), and it never waits on a process or an ack. +//! - `PERSIST_SIGNAL` is a leaf. +//! - Registration and terminal results are non-blocking sends to the +//! coordinator. use crate::command_builders::{ build_ffmpeg_args, build_ytdlp_args, resolve_video_encoder, YtdlpArgsInput, }; use crate::constants::*; -use crate::ipc::{self, IpcResult, NOT_AVAILABLE}; +use crate::ipc::{self, DownloadRequestInput, FalliblePayload, IpcResult, NOT_AVAILABLE}; use crate::progress::{self, Metrics, Reporter}; use crate::staging::{ file_identity, install_no_replace, reserve_download_stage, reserve_path_output_file, sync_staged_file, DownloadStage, FileIdentity, }; use crate::types::{ - DownloadCompletion, DownloadProfile, DownloadRequestOptions, GpuType, JobProgressEvent, - Outcome, Owner, Phase, QueueProgress, Settings, + DownloadCompletion, DownloadRequestOptions, JobProgressEvent, Outcome, Owner, Phase, + QueueProgress, Settings, }; use crate::validation::{is_path_within, is_safe_http_url, resolve_path}; -use serde_json::{Map, Value}; use std::collections::{HashSet, VecDeque}; use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard}; - -pub type CompletionCallback = Box; +use std::sync::mpsc::Sender; +use std::sync::{Arc, Mutex, MutexGuard}; const CANCELLED_STATUS: &str = "⏹️ Cancelled."; const CANCELLED_PROGRESS: &str = "⏹️ Download/Conversion cancelled by user."; @@ -63,7 +63,6 @@ struct Session { ytdlp_exit_pending: bool, conversion_pending: bool, ffmpeg: Option>, - on_complete: Option, ytdlp_postprocess: bool, ytdlp_download_finished: bool, conversion_format: Option, @@ -75,54 +74,12 @@ struct Session { reporter: Reporter, } +/// The session slot. It holds session data only; lifecycle waits go through +/// the coordinator's await acks. static ACTIVE: Mutex> = Mutex::new(None); /// Mirrors whether ACTIVE holds a session, so the main thread can ask without /// waiting on the session lock. static ACTIVE_PRESENT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -static SESSION_CHANGED: Condvar = Condvar::new(); -static FINALIZING: Mutex> = Mutex::new(Vec::new()); -static FINALIZATION_CHANGED: Condvar = Condvar::new(); - -struct CompletionFinalizer(u64); - -impl CompletionFinalizer { - fn begin(id: u64) -> Self { - FINALIZING - .lock() - .unwrap_or_else(|p| p.into_inner()) - .push(id); - Self(id) - } -} - -impl Drop for CompletionFinalizer { - fn drop(&mut self) { - FINALIZING - .lock() - .unwrap_or_else(|p| p.into_inner()) - .retain(|id| *id != self.0); - FINALIZATION_CHANGED.notify_all(); - SESSION_CHANGED.notify_all(); - } -} - -fn finalizing_ids() -> Vec { - FINALIZING - .lock() - .unwrap_or_else(|p| p.into_inner()) - .iter() - .copied() - .collect() -} - -fn wait_for_finalizations(ids: &[u64]) { - let mut pending = FINALIZING.lock().unwrap_or_else(|p| p.into_inner()); - while ids.iter().any(|id| pending.contains(id)) { - pending = FINALIZATION_CHANGED - .wait(pending) - .unwrap_or_else(|p| p.into_inner()); - } -} static STARTUP: Mutex<()> = Mutex::new(()); static EVENT_PUBLISH: Mutex<()> = Mutex::new(()); @@ -134,17 +91,6 @@ fn lock() -> MutexGuard<'static, Option> { .unwrap_or_else(|poisoned| poisoned.into_inner()) } -fn wait_for_session_completion(id: u64) { - let mut active = lock(); - while active.as_ref().is_some_and(|session| session.id == id) { - active = SESSION_CHANGED - .wait(active) - .unwrap_or_else(|poisoned| poisoned.into_inner()); - } - drop(active); - wait_for_finalizations(&[id]); -} - fn with_session(id: u64, f: impl FnOnce(&mut Session) -> R) -> Option { let mut guard = lock(); match guard.as_mut() { @@ -165,6 +111,15 @@ pub fn can_start(owner: Owner) -> bool { lock().as_ref().is_none_or(|session| session.owner == owner) } +/// The active session's id when another owner holds the slot. Callers wait on +/// it with `coordinator::await_finalized` instead of polling. +pub fn blocking_session(owner: Owner) -> Option { + lock() + .as_ref() + .filter(|session| session.owner != owner) + .map(|session| session.id) +} + fn send_progress(id: u64, message: impl Into) { let _publish = EVENT_PUBLISH .lock() @@ -443,19 +398,20 @@ fn complete_session(id: u64, status_message: &str, outcome: Outcome, meta: Compl let publish = EVENT_PUBLISH .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); + // The session stays registered with the coordinator until its terminal + // result is routed below, so awaits on it are not released early. let session = { let mut guard = lock(); match guard.as_ref() { Some(session) if session.id == id => { - let finalizer = CompletionFinalizer::begin(id); - let taken = guard.take().map(|session| (session, finalizer)); + let taken = guard.take(); ACTIVE_PRESENT.store(false, Ordering::SeqCst); taken } _ => None, } }; - let Some((mut session, _finalizer)) = session else { + let Some(mut session) = session else { return; }; let mut outcome = outcome; @@ -539,10 +495,7 @@ fn complete_session(id: u64, status_message: &str, outcome: Outcome, meta: Compl Outcome::Success => crate::stats::record(outcome, meta.format.as_deref(), size_bytes), _ => crate::stats::record(outcome, None, None), } - if let Some(callback) = session.on_complete.take() { - callback(completion); - } - SESSION_CHANGED.notify_all(); + crate::coordinator::terminal(session.id, completion); } /// Cancel the active session. `notify` controls whether the user-facing @@ -565,11 +518,11 @@ fn cancel_session(notify: bool, notify_manual: bool, ytdlp_first: bool) { let (id, children, partial, wait_for_ytdlp, show) = { let mut guard = lock(); let Some(session) = guard.as_mut() else { - // Snapshot under ACTIVE so completion cannot clear the slot before - // registering its pending callback. Do not wait on future sessions. - let pending = finalizing_ids(); + // Registration happens in the same critical section that installs a + // session, so every session still awaiting finalization is already + // registered. A session started after this point is not awaited. drop(guard); - wait_for_finalizations(&pending); + crate::coordinator::await_finalized(None); return; }; session.cancelled = true; @@ -598,7 +551,8 @@ fn cancel_session(notify: bool, notify_manual: bool, ytdlp_first: bool) { crate::process_util::terminate_tree(&child); } if wait_for_ytdlp { - wait_for_session_completion(id); + // The reader thread finalizes the session once yt-dlp has exited. + crate::coordinator::await_finalized(Some(id)); return; } complete_session( @@ -613,159 +567,6 @@ fn cancel_session(notify: bool, notify_manual: bool, ytdlp_first: bool) { ); } -fn to_map(value: &impl serde::Serialize) -> Map { - match serde_json::to_value(value) { - Ok(Value::Object(map)) => map, - _ => Map::new(), - } -} - -fn resolve_preset_options( - settings: &Settings, - options: DownloadRequestOptions, -) -> DownloadRequestOptions { - let Some(preset) = options.preset_id.as_deref().and_then(|id| { - settings - .download_presets - .iter() - .find(|preset| preset.id == id) - }) else { - return options; - }; - let mut merged = crate::settings::preset_to_request_options(preset); - for (key, value) in to_map(&options) { - merged.insert(key, value); - } - if options.preset_name.is_none() { - merged.insert("presetName".into(), Value::String(preset.name.clone())); - } - serde_json::from_value(Value::Object(merged)).unwrap_or(options) -} - -fn apply_request_to_settings(settings: &Settings, options: &DownloadRequestOptions) -> Settings { - let mut effective = settings.clone(); - // IPC validation admits only known names, so an unknown value cannot reach here. - if let Some(profile) = options.profile.as_deref().and_then(DownloadProfile::parse) { - effective.download_mode = profile; - } - effective.advanced_options = effective.download_mode == DownloadProfile::Custom; - effective.audio_only = effective.download_mode == DownloadProfile::Audio; - effective.best_quality = effective.download_mode == DownloadProfile::BestVideo; - if let Some(value) = options.advanced_options { - effective.advanced_options = value; - } - if let Some(value) = options.audio_only { - effective.audio_only = value; - } - if let Some(value) = options.best_quality { - effective.best_quality = value; - } - if let Some(value) = &options.audio_output_format { - effective.audio_format = value.clone(); - } - if let Some(value) = options.convert_enabled { - effective.convert_enabled = value; - } - if let Some(format) = &options.convert_format { - if !format.trim().is_empty() { - effective.convert_format = format.clone(); - if options.convert_enabled.is_none() { - effective.convert_enabled = true; - } - } else if options.convert_enabled.is_none() { - effective.convert_enabled = false; - } - } - if let Some(value) = options.keep_original { - effective.keep_original_after_convert = value; - } - if let Some(value) = options.hook_browser { - effective.hook_browser = value; - } - if let Some(value) = options - .browser_choice - .as_ref() - .filter(|value| !value.is_empty()) - { - effective.browser_choice = value.clone(); - } - if let Some(value) = options.gpu_acceleration { - effective.gpu_acceleration = value; - } - if let Some(value) = options.gpu_type.as_deref().and_then(GpuType::parse) { - effective.gpu_type = value; - } - if let Some(value) = options.write_subtitles { - effective.write_subtitles = value; - } - if let Some(value) = options - .subtitle_langs - .as_ref() - .filter(|value| !value.is_empty()) - { - effective.subtitle_langs = value.clone(); - } - if let Some(value) = options.embed_thumbnail { - effective.embed_thumbnail = value; - } - if let Some(value) = options.embed_metadata { - effective.embed_metadata = value; - } - if let Some(value) = options.sponsorblock_remove { - effective.sponsorblock_remove = value; - } - if let Some(value) = &options.ffmpeg_path { - effective.ffmpeg_path = value.clone(); - } - effective -} - -fn resolved_snapshot( - options: &DownloadRequestOptions, - effective: &Settings, -) -> DownloadRequestOptions { - DownloadRequestOptions { - url: options.url.trim().to_string(), - output_path: options.output_path.clone(), - ffmpeg_path: options - .ffmpeg_path - .clone() - .filter(|path| !path.is_empty()) - .or_else(|| Some(effective.ffmpeg_path.clone()).filter(|path| !path.is_empty())), - convert_enabled: Some(effective.convert_enabled), - convert_format: Some(effective.convert_format.clone()), - keep_original: Some(effective.keep_original_after_convert), - video_format: options.video_format.clone(), - audio_format: options.audio_format.clone(), - playlist: Some( - options - .playlist - .clone() - .unwrap_or(crate::types::PlaylistSelection { - mode: "current".into(), - start: None, - end: None, - }), - ), - profile: Some(effective.download_mode.as_str().to_string()), - preset_id: options.preset_id.clone(), - preset_name: options.preset_name.clone(), - best_quality: Some(effective.best_quality), - advanced_options: Some(effective.advanced_options), - audio_only: Some(effective.audio_only), - audio_output_format: Some(effective.audio_format.clone()), - hook_browser: Some(effective.hook_browser), - browser_choice: Some(effective.browser_choice.clone()), - gpu_acceleration: Some(effective.gpu_acceleration), - gpu_type: Some(effective.gpu_type.as_str().to_string()), - write_subtitles: Some(effective.write_subtitles), - subtitle_langs: Some(effective.subtitle_langs.clone()), - embed_thumbnail: Some(effective.embed_thumbnail), - embed_metadata: Some(effective.embed_metadata), - sponsorblock_remove: Some(effective.sponsorblock_remove), - } -} - /// Stream lines (split on `\n` and `\r`) from a child pipe. fn read_lines( reader: Option, @@ -902,37 +703,39 @@ fn append_bounded(buffer: &Mutex, line: &str, limit: usize, keep_tail: b text.push('\n'); } -/// Returned when another owner holds the session slot. The unused completion -/// callback is handed back so the caller can retry later. +/// Returned when another owner holds the session slot. The caller keeps its +/// completion sender and can retry later. pub struct OwnerConflict { pub message: String, - pub on_complete: CompletionCallback, + /// The session holding the slot, for the caller to await. + pub session_id: u64, } /// Start a download. Validation failures are reported through the normal /// completion path; `Err` only means another owner holds the session slot. pub fn start_download( - options: DownloadRequestOptions, + options: crate::download_options::ResolvedDownloadOptions, owner: Owner, queue_progress: Option, - on_complete: CompletionCallback, + completion: Sender, ) -> Result { - let settings = crate::settings::load(); - let request = resolve_preset_options(&settings, options); - let effective = apply_request_to_settings(&settings, &request); - let snapshot = resolved_snapshot(&request, &effective); + let request = options.request; + let effective = options.effective_settings; + let snapshot = request.clone(); let plan = progress::resolve_plan(&effective); let startup = STARTUP .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - let existing_owner = lock().as_ref().map(|session| session.owner); - match existing_owner { - Some(current) if current != owner => { + let existing = lock().as_ref().map(|session| (session.id, session.owner)); + match existing { + Some((session_id, current)) if current != owner => { return Err(OwnerConflict { message: "Download session already active with a different owner.".to_string(), - on_complete, + session_id, }) } + // Waits for the previous session's finalization ack before this one + // installs, so the slot is never shared. Some(_) => cancel_active_session(false), None => {} } @@ -951,7 +754,6 @@ pub fn start_download( ytdlp_exit_pending: false, conversion_pending: false, ffmpeg: None, - on_complete: Some(on_complete), ytdlp_postprocess: false, ytdlp_download_finished: false, conversion_format: None, @@ -965,7 +767,12 @@ pub fn start_download( let _publish = EVENT_PUBLISH .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); - *lock() = Some(session); + let mut guard = lock(); + // Registration is a non-blocking send made under the same lock that + // installs the session. Any cancel that can see the session is + // therefore ordered after its registration. + crate::coordinator::register(id, completion); + *guard = Some(session); ACTIVE_PRESENT.store(true, Ordering::SeqCst); } let mut startup = Some(startup); @@ -974,7 +781,7 @@ pub fn start_download( .ffmpeg_path .clone() .filter(|path| !path.is_empty()) - .unwrap_or_else(|| settings.ffmpeg_path.clone()); + .unwrap_or_else(|| effective.ffmpeg_path.clone()); let ffmpeg_command = crate::sidecars::effective_ffmpeg(Some(&requested_ffmpeg)); let ytdlp = crate::sidecars::ytdlp_path(); let url = request.url.clone(); @@ -1735,7 +1542,6 @@ fn on_ytdlp_exit(mut exit: YtdlpExit) { (session.cancelled, session.cancel_notify) }) else { let _ = std::fs::remove_file(&exit.path_output_file); - SESSION_CHANGED.notify_all(); return; }; let path_output_file = exit.path_output_file.clone(); @@ -3309,9 +3115,11 @@ pub struct Started { } #[tauri::command(async)] -pub fn download_video(options: Value) -> IpcResult { - let request = match crate::validation::validate_download_request(&options) { - Ok(request) => request, +pub fn download_video(options: FalliblePayload) -> IpcResult { + let settings = crate::settings::load(); + let resolved = match crate::download_options::resolve_value(&settings, &options.into_value(), None) + { + Ok(resolved) => resolved, Err(error) => return ipc::from_error(error), }; // The runner briefly holds no session between items, so the session slot @@ -3319,9 +3127,13 @@ pub fn download_video(options: Value) -> IpcResult { if !can_start(Owner::Manual) || crate::queue::is_running() { return ipc::err(NOT_AVAILABLE, "A queue download is already in progress."); } - let on_complete: CompletionCallback = - Box::new(|completion| crate::activity::record(&completion)); - match start_download(request, Owner::Manual, None, on_complete) { + let (completion, recorded) = std::sync::mpsc::channel::(); + std::thread::spawn(move || { + if let Ok(completion) = recorded.recv() { + crate::activity::record(&completion); + } + }); + match start_download(resolved, Owner::Manual, None, completion) { Ok(session_id) => ipc::ok(Started { started: true, session_id, @@ -3347,7 +3159,7 @@ mod audit4_tests { use std::time::Duration; static SERIAL: Mutex<()> = Mutex::new(()); - fn session(callback: CompletionCallback) -> Session { + fn session() -> Session { Session { id: u64::MAX, completion_id: "audit4".into(), @@ -3361,7 +3173,6 @@ mod audit4_tests { ytdlp_exit_pending: false, conversion_pending: false, ffmpeg: None, - on_complete: Some(callback), ytdlp_postprocess: false, ytdlp_download_finished: false, conversion_format: None, @@ -3373,47 +3184,12 @@ mod audit4_tests { } } - #[test] - fn cancellation_waits_for_callback_after_active_slot_is_empty() { - let _serial = SERIAL.lock().unwrap(); - let (entered_tx, entered_rx) = mpsc::channel(); - let (release_tx, release_rx) = mpsc::channel(); - *lock() = Some(session(Box::new(move |_| { - entered_tx.send(()).unwrap(); - release_rx.recv().unwrap(); - }))); - let completion = std::thread::spawn(|| { - complete_session( - u64::MAX, - "Done", - Outcome::Success, - CompletionMeta::default(), - ) - }); - entered_rx.recv_timeout(Duration::from_secs(5)).unwrap(); - assert!(lock().is_none()); - let (cancel_tx, cancel_rx) = mpsc::channel(); - let cancel = std::thread::spawn(move || { - cancel_active_session(false); - cancel_tx.send(()).unwrap(); - }); - let early = cancel_rx.recv_timeout(Duration::from_millis(100)).is_ok(); - release_tx.send(()).unwrap(); - completion.join().unwrap(); - cancel.join().unwrap(); - assert!( - !early, - "Cancellation returned before completion callback finished" - ); - } - #[test] fn cancellation_retains_explicit_recovery_error() { let _serial = SERIAL.lock().unwrap(); let (tx, rx) = mpsc::channel(); - *lock() = Some(session(Box::new(move |completion| { - tx.send(completion).unwrap(); - }))); + crate::coordinator::register(u64::MAX, tx); + *lock() = Some(session()); complete_session( u64::MAX, "Cancelled", @@ -3424,7 +3200,7 @@ mod audit4_tests { }, ); assert_eq!( - rx.recv().unwrap().error.as_deref(), + rx.recv_timeout(Duration::from_secs(5)).unwrap().error.as_deref(), Some("Recovery at /tmp/staging") ); } diff --git a/src-tauri/src/ipc.rs b/src-tauri/src/ipc.rs index 13e9b77e..d6afca56 100644 --- a/src-tauri/src/ipc.rs +++ b/src-tauri/src/ipc.rs @@ -1,6 +1,105 @@ //! `{ ok, data } | { ok: false, error }` envelopes shared with the frontend. -use serde::Serialize; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// A typed-first adapter for IPC payloads. Invalid shapes are retained as JSON +/// so command validators can return ROSI's normal error envelope instead of +/// letting Tauri reject the invocation during argument extraction. +#[derive(Clone, Debug, Deserialize)] +#[serde(untagged)] +pub enum FalliblePayload { + Typed(T), + Invalid(Value), +} + +impl FalliblePayload { + pub fn into_value(self) -> Value { + match self { + Self::Typed(value) => serde_json::to_value(value).unwrap_or(Value::Null), + Self::Invalid(value) => value, + } + } +} + +/// Validly shaped manual/preview request fields. Values are checked again by +/// `validate_download_request` for URL, path and allow-list policy. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(test, derive(ts_rs::TS))] +#[cfg_attr(test, ts(optional_fields = nullable))] +pub struct DownloadRequestOverrides { + #[serde(skip_serializing_if = "Option::is_none")] + pub output_path: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub ffmpeg_path: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub convert_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub convert_format: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub keep_original: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub video_format: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub audio_format: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub playlist: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub preset_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub preset_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub best_quality: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub advanced_options: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub audio_only: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub audio_output_format: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub hook_browser: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub browser_choice: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu_acceleration: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub gpu_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub write_subtitles: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub subtitle_langs: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub embed_thumbnail: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub embed_metadata: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sponsorblock_remove: Option, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(test, derive(ts_rs::TS))] +#[cfg_attr(test, ts(optional_fields = nullable))] +pub struct DownloadRequestInput { + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, + #[serde(flatten)] + pub options: DownloadRequestOverrides, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum QueueUrlInput { + Text(String), + Other(Value), +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(transparent)] +pub struct QueueUrlsInput(pub Vec); #[derive(Clone, Debug, Serialize, PartialEq)] #[cfg_attr(test, derive(ts_rs::TS))] diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 09ef254d..50c0366e 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -5,7 +5,9 @@ mod app_menu; mod app_state; mod command_builders; mod constants; +mod coordinator; mod deno; +mod download_options; mod downloader; mod ffmpeg_guard; mod fs_util; @@ -61,6 +63,7 @@ fn report_missing_ytdlp(app: &tauri::AppHandle) -> bool { fn e2e_emit_stale_download_events( window: tauri::WebviewWindow, current_session_id: u64, + stale_queue_snapshot: Option, ) -> Result<(), String> { if window.label() != app_state::MAIN_WINDOW { return Err("Only the main window may emit E2E download events.".into()); @@ -68,6 +71,15 @@ fn e2e_emit_stale_download_events( if !(2..=1_000_000_000).contains(¤t_session_id) { return Err("The E2E session ID is outside the permitted range.".into()); } + if stale_queue_snapshot.unwrap_or(false) { + // The coordinator starts revisions at 1, so revision 0 is older than + // any snapshot the renderer has seen. Applying it would drop every row. + app_state::emit( + "queue-update", + serde_json::json!({ "revision": 0, "items": [] }), + ); + return Ok(()); + } let stale_session_id = current_session_id - 1; app_state::emit( "complete", @@ -139,6 +151,7 @@ macro_rules! generate_app_handler { media_info::cancel_video_info, downloader::download_video, downloader::cancel_download, + download_options::resolve_download_options, queue::add_to_queue, queue::remove_from_queue, queue::retry_queue_item, diff --git a/src-tauri/src/media_info.rs b/src-tauri/src/media_info.rs index 6bc918be..9889731d 100644 --- a/src-tauri/src/media_info.rs +++ b/src-tauri/src/media_info.rs @@ -3,7 +3,7 @@ use crate::constants::*; use crate::ipc::{self, IpcResult, INTERNAL_ERROR, INVALID_URL, NOT_AVAILABLE, VALIDATION_ERROR}; use crate::process_util::{TrackedError, TrackedReservation, TrackedSlot}; -use crate::types::VideoInfo; +use crate::types::{FormatEntry, FormatList, StreamKind, VideoInfo}; use crate::validation::{is_safe_http_url, is_syntactically_safe_http_url}; use serde_json::{Map, Value}; @@ -74,6 +74,139 @@ pub fn parse_video_info(json: &str, entry_limit: usize) -> Option { }) } +enum CodecMetadata { + Missing, + NoStream, + Codec(String), +} + +fn codec_metadata(value: Option<&Value>) -> CodecMetadata { + let Some(codec) = value.and_then(Value::as_str).map(str::trim) else { + return CodecMetadata::Missing; + }; + if codec.is_empty() { + CodecMetadata::Missing + } else if codec.eq_ignore_ascii_case("none") { + CodecMetadata::NoStream + } else { + CodecMetadata::Codec(codec.to_string()) + } +} + +fn codec_name(metadata: &CodecMetadata) -> Option { + match metadata { + CodecMetadata::Codec(codec) => Some(codec.clone()), + CodecMetadata::Missing | CodecMetadata::NoStream => None, + } +} + +fn pick_file_size(value: Option<&Value>) -> Option { + value.and_then(|value| { + value.as_u64().or_else(|| { + value + .as_f64() + .filter(|size| size.is_finite() && *size >= 0.0 && *size <= u64::MAX as f64) + .map(|size| size.round() as u64) + }) + }) +} + +fn pick_resolution(data: &Map) -> Option { + pick_string(data.get("resolution")) + .filter(|resolution| { + !resolution.eq_ignore_ascii_case("unknown") + && !resolution.eq_ignore_ascii_case("audio only") + }) + .or_else(|| { + let width = data.get("width").and_then(Value::as_u64)?; + let height = data.get("height").and_then(Value::as_u64)?; + (width > 0 && height > 0).then(|| format!("{width}x{height}")) + }) +} + +fn is_non_media_format(data: &Map) -> bool { + let ext = pick_string(data.get("ext")); + let note = pick_string(data.get("format_note")); + ext.is_some_and(|ext| ext.eq_ignore_ascii_case("mhtml")) + || note.is_some_and(|note| { + let note = note.to_ascii_lowercase(); + note.contains("storyboard") || note.contains("images only") || note.contains("image only") + }) +} + +fn fallback_stream_kind(data: &Map) -> Option { + let ext = pick_string(data.get("ext"))?.to_ascii_lowercase(); + match ext.as_str() { + "aac" | "ac3" | "alac" | "eac3" | "flac" | "m4a" | "m4b" | "mp3" | "opus" + | "wav" | "wma" => Some(StreamKind::Audio), + "3gp" | "avi" | "flv" | "m2ts" | "m4v" | "mkv" | "mov" | "mp4" | "mpd" + | "m3u8" | "mts" | "mxf" | "ts" | "vob" | "webm" | "wmv" => { + Some(StreamKind::AudioVideo) + } + _ => None, + } +} + +fn parse_format_entry(value: &Value) -> Option { + let data = value.as_object()?; + let format_id = pick_string(data.get("format_id"))?; + if !is_format_id(&format_id) || is_non_media_format(data) { + return None; + } + let vcodec_metadata = codec_metadata(data.get("vcodec")); + let acodec_metadata = codec_metadata(data.get("acodec")); + let vcodec = codec_name(&vcodec_metadata); + let acodec = codec_name(&acodec_metadata); + let stream_kind = match (&vcodec_metadata, &acodec_metadata) { + (CodecMetadata::Codec(_), CodecMetadata::Codec(_)) => StreamKind::AudioVideo, + (CodecMetadata::Codec(_), CodecMetadata::NoStream | CodecMetadata::Missing) + | (CodecMetadata::Missing | CodecMetadata::NoStream, CodecMetadata::Codec(_)) => { + if vcodec.is_some() { + StreamKind::Video + } else { + StreamKind::Audio + } + } + (CodecMetadata::NoStream, CodecMetadata::NoStream) => return None, + (CodecMetadata::NoStream, CodecMetadata::Missing) => StreamKind::Audio, + (CodecMetadata::Missing, CodecMetadata::NoStream) => StreamKind::Video, + (CodecMetadata::Missing, CodecMetadata::Missing) => fallback_stream_kind(data)?, + }; + Some(FormatEntry { + format_id, + stream_kind, + vcodec, + acodec, + resolution: pick_resolution(data), + fps: pick_number(data.get("fps")).filter(|fps| *fps > 0.0), + file_size_bytes: pick_file_size(data.get("filesize")), + estimated_size_bytes: pick_file_size(data.get("filesize_approx")), + }) +} + +pub fn parse_format_list(json: &str) -> Result { + let parsed: Value = + serde_json::from_str(json).map_err(|_| "Could not parse format metadata.".to_string())?; + let data = parsed + .as_object() + .ok_or_else(|| "Could not parse format metadata.".to_string())?; + if data.get("_type").and_then(Value::as_str) == Some("playlist") + || data.get("entries").and_then(Value::as_array).is_some() + { + return Err( + "Format lookup needs a single video URL. Open a specific playlist item and try again." + .into(), + ); + } + let formats = data + .get("formats") + .and_then(Value::as_array) + .ok_or_else(|| "Could not parse format metadata.".to_string())?; + Ok(FormatList { + formats: formats.iter().filter_map(parse_format_entry).collect(), + }) +} + fn resolve_playlist_mode(url: &str, requested: Option<&str>) -> &'static str { match requested { Some("all") => return "all", @@ -133,7 +266,7 @@ fn error_result(message: String) -> IpcResult { } } -fn fetch_formats(url: String, reservation: TrackedReservation<'static>) -> Result { +fn fetch_formats(url: String, reservation: TrackedReservation<'static>) -> Result { if reservation.is_cancelled() { return Err("Format fetch cancelled.".into()); } @@ -170,20 +303,25 @@ fn fetch_formats(url: String, reservation: TrackedReservation<'static>) -> Resul if reservation.is_cancelled() { return Err("Format fetch cancelled.".into()); } - let mut args = vec!["-F".into(), "--".into(), url]; + let mut args = vec![ + "--dump-single-json".into(), + "--no-playlist".into(), + "--no-warnings".into(), + "--skip-download".into(), + "--".into(), + url, + ]; insert_common_args(&mut args, &settings, &guard, &ffmpeg_guard); let command = ytdlp_command(args); match FORMATS.run_reserved_with( reservation, command, FORMAT_FETCH_TIMEOUT, - MAX_OUTPUT_BUFFER, + MAX_OUTPUT_BUFFER * 4, MAX_ERROR_BUFFER, |output| { if output.code == Some(0) { - Ok(output - .stdout - .replace(guard.proxy_url(), "")) + parse_format_list(&output.stdout) } else { Err(format!( "yt-dlp exited with code {}.\nOutput:\n{}\nError:\n{}", @@ -321,7 +459,7 @@ fn fetch_video_info( } #[tauri::command] -pub async fn get_formats(url: Value) -> IpcResult { +pub async fn get_formats(url: Value) -> IpcResult { let reservation = FORMATS.reserve(); let Some(url) = url .as_str() diff --git a/src-tauri/src/network_security.rs b/src-tauri/src/network_security.rs index 43e2b388..3d8608be 100644 --- a/src-tauri/src/network_security.rs +++ b/src-tauri/src/network_security.rs @@ -4,8 +4,8 @@ //! URL once before launching the process is not a network security boundary. //! Every HTTP request and HTTPS CONNECT sent through this short-lived proxy is //! resolved and checked again here, then connected to the exact vetted -//! address. The proxy uses a fixed worker pool and closes active sockets when -//! its owning operation ends. +//! address. Client networking runs as bounded tasks on Tauri's Tokio runtime; +//! DNS uses an independent fixed-size resolver and drops cancelled queued jobs. //! //! When the user configures an upstream HTTP proxy, the vetted destination is //! reached through it instead: CONNECT for HTTPS, and absolute-form requests @@ -16,17 +16,18 @@ use crate::constants::MAX_UPSTREAM_PROXY_BYTES; use crate::ip_policy::is_public_ip; use reqwest::redirect::Policy; use reqwest::Client; -use std::collections::{HashMap, VecDeque}; +use std::collections::VecDeque; +#[cfg(feature = "e2e")] use std::io::{self, Read, Write}; -use std::net::{ - IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs, -}; +#[cfg(feature = "e2e")] +use std::net::TcpStream; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; use std::sync::mpsc::{self, Receiver, SyncSender}; use std::sync::{ atomic::{AtomicBool, AtomicU64, Ordering}, Arc, Condvar, Mutex, OnceLock, }; -use std::thread::{self, JoinHandle}; +use std::thread; use std::time::{Duration, Instant}; const MAX_PROXY_HEADER_BYTES: usize = 64 * 1024; @@ -39,16 +40,9 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(4); /// Budget for all addresses of one destination. const CONNECT_TOTAL_TIMEOUT: Duration = Duration::from_secs(12); const IO_TIMEOUT: Duration = Duration::from_secs(20); -/// yt-dlp keeps finished HTTPS connections open in its pool, and each open -/// tunnel holds a worker. Size the pool above yt-dlp's per-process pool count -/// and close idle tunnels, so pooled connections cannot starve new ones. -const PROXY_WORKERS: usize = 32; -const MAX_PENDING_PROXY_CLIENTS: usize = 64; /// A tunnel with no traffic in either direction for this long is closed. -/// yt-dlp reopens a dropped pooled connection on its next request. This stays -/// below yt-dlp's 20 s socket timeout so a queued connection is served first. +/// yt-dlp reopens a dropped pooled connection on its next request. const TUNNEL_IDLE_TIMEOUT: Duration = Duration::from_secs(15); -const RELAY_MAX_IDLE_SLEEP: Duration = Duration::from_millis(25); const RELAY_BUFFER_BYTES: usize = 16 * 1024; const DNS_RESOLVER_WORKERS: usize = 4; const MAX_PENDING_DNS_QUERIES: usize = 16; @@ -104,10 +98,53 @@ struct PendingDnsJob { id: u64, cancelled: Arc, response: Receiver>>, + shared: Arc, + finished: bool, +} + +impl PendingDnsJob { + fn finish(&mut self) { + self.finished = true; + } + + fn cancel(&mut self) { + if self.finished { + return; + } + self.finished = true; + if self.cancelled.swap(true, Ordering::AcqRel) { + return; + } + let mut state = self + .shared + .state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let queued_len = state.queue.len(); + state.queue.retain(|job| job.id != self.id); + #[cfg(feature = "e2e")] + { + state.cancelled_waits = state.cancelled_waits.saturating_add(1); + } + if state.queue.len() != queued_len { + drop(state); + self.shared.queue_ready.notify_one(); + } + } +} + +impl Drop for PendingDnsJob { + fn drop(&mut self) { + self.cancel(); + } } type ParsedHttpRequest = (String, String, String, Vec<(String, String)>); +#[path = "network_security_async.rs"] +mod async_proxy; +pub use async_proxy::NetworkSecurityGuard; + /// A validated upstream HTTP proxy. The host is kept without IPv6 brackets. #[derive(Clone, Debug, PartialEq, Eq)] pub struct UpstreamProxy { @@ -309,26 +346,13 @@ impl DnsResolverPool { id, cancelled, response: response_receiver, + shared: Arc::clone(&self.shared), + finished: false, }) } - fn cancel(&self, pending: &PendingDnsJob) { - pending.cancelled.store(true, Ordering::Release); - let mut state = self - .shared - .state - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let queued_len = state.queue.len(); - state.queue.retain(|job| job.id != pending.id); - #[cfg(feature = "e2e")] - { - state.cancelled_waits = state.cancelled_waits.saturating_add(1); - } - if state.queue.len() != queued_len { - drop(state); - self.shared.queue_ready.notify_one(); - } + fn cancel(&self, pending: &mut PendingDnsJob) { + pending.cancel(); } #[cfg(feature = "e2e")] @@ -448,427 +472,6 @@ fn resolve_dns_addresses( Some(resolved) } -struct ProxyShared { - stopped: AtomicBool, - operation_cancelled: Option>, - upstream: Option, - queued: Mutex>, - queue_ready: Condvar, - active: Mutex>>, - next_id: AtomicU64, -} - -impl ProxyShared { - fn new(operation_cancelled: Option>, upstream: Option) -> Self { - Self { - stopped: AtomicBool::new(false), - operation_cancelled, - upstream, - queued: Mutex::new(VecDeque::new()), - queue_ready: Condvar::new(), - active: Mutex::new(HashMap::new()), - next_id: AtomicU64::new(1), - } - } - - fn enqueue(&self, mut stream: TcpStream) { - let mut queued = self - .queued - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - if self.stopped.load(Ordering::Acquire) || self.operation_is_cancelled() { - let _ = stream.shutdown(Shutdown::Both); - return; - } - if queued.len() >= MAX_PENDING_PROXY_CLIENTS { - drop(queued); - let _ = stream.set_write_timeout(Some(Duration::from_millis(100))); - write_proxy_error(&mut stream, 503, "Proxy Busy"); - let _ = stream.shutdown(Shutdown::Both); - return; - } - queued.push_back(stream); - self.queue_ready.notify_one(); - } - - fn stop(&self) { - self.stopped.store(true, Ordering::Release); - let mut queued = self - .queued - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - for stream in queued.drain(..) { - let _ = stream.shutdown(Shutdown::Both); - } - drop(queued); - let active = self - .active - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - for sockets in active.values() { - for socket in sockets { - let _ = socket.shutdown(Shutdown::Both); - } - } - self.queue_ready.notify_all(); - } - - fn next_client(&self) -> Option { - let mut queued = self - .queued - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - loop { - if self.stopped.load(Ordering::Acquire) { - return None; - } - if self.operation_is_cancelled() { - drop(queued); - self.stop(); - return None; - } - if let Some(stream) = queued.pop_front() { - return Some(stream); - } - queued = self - .queue_ready - .wait(queued) - .unwrap_or_else(|poisoned| poisoned.into_inner()); - } - } - - fn operation_is_cancelled(&self) -> bool { - self.operation_cancelled - .as_ref() - .is_some_and(|cancelled| cancelled.load(Ordering::Acquire)) - } -} - -struct ActiveSockets { - shared: Arc, - id: u64, -} - -impl ActiveSockets { - fn register(&self, stream: &TcpStream) -> io::Result<()> { - let clone = stream.try_clone()?; - let mut active = self - .shared - .active - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - if self.shared.stopped.load(Ordering::Acquire) || self.shared.operation_is_cancelled() { - let _ = clone.shutdown(Shutdown::Both); - return Err(io::Error::new( - io::ErrorKind::Interrupted, - "network operation was cancelled", - )); - } - active.entry(self.id).or_default().push(clone); - Ok(()) - } -} - -impl Drop for ActiveSockets { - fn drop(&mut self) { - self.shared - .active - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .remove(&self.id); - } -} - -/// Owns the per-operation loopback proxy. Retain it until the process or HTTP -/// operation finishes; dropping it closes the listener, queued sockets, and -/// both ends of every active connection. -pub struct NetworkSecurityGuard { - proxy_url: String, - bind_addr: SocketAddr, - shared: Arc, - listener_thread: Option>, -} - -impl NetworkSecurityGuard { - /// Starts an authenticated loopback proxy. Any bind, entropy, or thread - /// startup failure is returned; callers must not fall back to direct I/O. - #[cfg(feature = "e2e")] - pub fn start() -> Result { - Self::start_inner(None, None) - } - - /// Starts a proxy that shuts down its listener and active sockets when - /// the owning tracked operation is cancelled. `upstream_proxy` is the - /// `upstreamProxy` setting, read once here: an empty value connects - /// directly, and an invalid value fails the start instead of going direct. - pub fn start_with_cancellation( - operation_cancelled: Arc, - upstream_proxy: &str, - ) -> Result { - let upstream = parse_upstream_proxy(upstream_proxy)?; - Self::start_inner(Some(operation_cancelled), upstream) - } - - fn start_inner( - operation_cancelled: Option>, - upstream: Option, - ) -> Result { - if operation_cancelled - .as_ref() - .is_some_and(|cancelled| cancelled.load(Ordering::Acquire)) - { - return Err("The network operation was cancelled.".into()); - } - let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) - .map_err(|error| format!("Could not start the secure network proxy: {error}"))?; - listener - .set_nonblocking(true) - .map_err(|error| format!("Could not configure the secure network proxy: {error}"))?; - let bind_addr = listener - .local_addr() - .map_err(|error| format!("Could not inspect the secure network proxy: {error}"))?; - - let mut token = [0u8; 24]; - getrandom::fill(&mut token) - .map_err(|error| format!("Could not create secure proxy credentials: {error}"))?; - let token = token - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); - let expected_auth = Arc::::from(format!( - "Basic {}", - base64_encode(format!("rosi:{token}").as_bytes()) - )); - let proxy_url = format!("http://rosi:{token}@{bind_addr}"); - let shared = Arc::new(ProxyShared::new(operation_cancelled, upstream)); - - for worker in 0..PROXY_WORKERS { - let worker_shared = Arc::clone(&shared); - let worker_auth = Arc::clone(&expected_auth); - if let Err(error) = thread::Builder::new() - .name(format!("rosi-network-worker-{worker}")) - .spawn(move || proxy_worker(worker_shared, worker_auth)) - { - shared.stop(); - return Err(format!( - "Could not start the secure network proxy workers: {error}" - )); - } - } - - let listener_shared = Arc::clone(&shared); - let listener_thread = match thread::Builder::new() - .name("rosi-network-listener".into()) - .spawn(move || { - while !listener_shared.stopped.load(Ordering::Acquire) { - if listener_shared.operation_is_cancelled() { - listener_shared.stop(); - break; - } - match listener.accept() { - Ok((stream, _)) => listener_shared.enqueue(stream), - Err(error) if error.kind() == io::ErrorKind::WouldBlock => { - thread::sleep(Duration::from_millis(10)); - } - Err(_) => break, - } - } - }) { - Ok(thread) => thread, - Err(error) => { - shared.stop(); - return Err(format!("Could not start the secure network proxy: {error}")); - } - }; - - Ok(Self { - proxy_url, - bind_addr, - shared, - listener_thread: Some(listener_thread), - }) - } - - /// Credential-bearing proxy URL for a subprocess or HTTP client. Treat it - /// as an ephemeral secret and do not log it. - pub fn proxy_url(&self) -> &str { - &self.proxy_url - } -} - -impl Drop for NetworkSecurityGuard { - fn drop(&mut self) { - self.shared.stop(); - // The listener is nonblocking. Wake it and join only that bounded - // accept loop; request workers are fixed-count and exit asynchronously. - let _ = TcpStream::connect_timeout(&self.bind_addr, Duration::from_millis(100)); - if let Some(listener_thread) = self.listener_thread.take() { - let _ = listener_thread.join(); - } - } -} - -fn proxy_worker(shared: Arc, expected_auth: Arc) { - while let Some(mut client) = shared.next_client() { - if configure_proxy_client_socket(&client).is_err() { - let _ = client.shutdown(Shutdown::Both); - continue; - } - let id = shared.next_id.fetch_add(1, Ordering::Relaxed); - let active = ActiveSockets { - shared: Arc::clone(&shared), - id, - }; - if active.register(&client).is_err() { - continue; - } - handle_proxy_client(&mut client, &expected_auth, &active); - } -} - -fn configure_proxy_client_socket(client: &TcpStream) -> io::Result<()> { - // Windows accepted sockets inherit the listener's nonblocking mode. HTTP - // parsing and body copying use blocking reads bounded by these timeouts. - client.set_nonblocking(false)?; - client.set_read_timeout(Some(IO_TIMEOUT))?; - client.set_write_timeout(Some(IO_TIMEOUT))?; - Ok(()) -} - -fn handle_proxy_client(client: &mut TcpStream, expected_auth: &str, active: &ActiveSockets) { - let Ok((header, buffered)) = read_request_header(client) else { - return; - }; - let Ok(header_text) = std::str::from_utf8(&header) else { - write_proxy_error(client, 400, "Bad Request"); - return; - }; - let Some((method, target, version, headers)) = parse_request(header_text) else { - write_proxy_error(client, 400, "Bad Request"); - return; - }; - let auth_values: Vec<&str> = headers - .iter() - .filter(|(name, _)| name.eq_ignore_ascii_case("proxy-authorization")) - .map(|(_, value)| value.trim()) - .collect(); - if auth_values.len() != 1 || auth_values[0] != expected_auth { - write_proxy_error(client, 407, "Proxy Authentication Required"); - return; - } - - if method.eq_ignore_ascii_case("CONNECT") { - let Ok((host, port, is_literal_loopback)) = parse_connect_target(&target) else { - write_proxy_error(client, 400, "Bad CONNECT Target"); - return; - }; - let Some(addresses) = vet_destination(&host, port, is_literal_loopback, active) else { - write_proxy_error(client, 403, "Destination Blocked"); - return; - }; - let (mut upstream, tunnel_leftover) = match &active.shared.upstream { - None => match connect_addresses(addresses, active) { - Some(stream) => (stream, Vec::new()), - None => { - write_proxy_error(client, 403, "Destination Blocked"); - return; - } - }, - Some(proxy) => match connect_via_upstream(proxy, &host, port, active) { - Ok(tunnel) => tunnel, - Err(()) => { - write_proxy_error(client, 502, "Upstream Proxy Failed"); - return; - } - }, - }; - if active.shared.stopped.load(Ordering::Acquire) { - return; - } - if client - .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n") - .is_err() - { - return; - } - if !tunnel_leftover.is_empty() && client.write_all(&tunnel_leftover).is_err() { - return; - } - let _ = relay_bidirectional(client, &mut upstream, &active.shared, &buffered); - return; - } - - let Ok(url) = url::Url::parse(&target) else { - write_proxy_error(client, 400, "Absolute URL Required"); - return; - }; - if url.scheme() != "http" || !url.username().is_empty() || url.password().is_some() { - write_proxy_error(client, 403, "Destination Blocked"); - return; - } - let Some(url_host) = url.host() else { - write_proxy_error(client, 400, "Missing Host"); - return; - }; - let host = host_string(&url_host); - let Some(port) = url.port_or_known_default() else { - write_proxy_error(client, 400, "Missing Port"); - return; - }; - let literal_loopback = host_is_loopback(&url_host); - let Some(addresses) = vet_destination(&host, port, literal_loopback, active) else { - write_proxy_error(client, 403, "Destination Blocked"); - return; - }; - // Through an upstream proxy the request goes there in absolute form, so - // the upstream can route it; the vetted address is not used. - let mut upstream = match &active.shared.upstream { - None => match connect_addresses(addresses, active) { - Some(stream) => stream, - None => { - write_proxy_error(client, 403, "Destination Blocked"); - return; - } - }, - Some(proxy) => match connect_to_upstream_proxy(proxy, active) { - Some(stream) => stream, - None => { - write_proxy_error(client, 502, "Upstream Proxy Failed"); - return; - } - }, - }; - let absolute_form = active.shared.upstream.is_some(); - - let Some((forwarded, body_mode, expect_continue)) = - build_forwarded_request(&method, &version, &url, &headers, absolute_form) - else { - write_proxy_error(client, 400, "Unsupported HTTP Request"); - return; - }; - if upstream.write_all(&forwarded).is_err() { - return; - } - if expect_continue && client.write_all(b"HTTP/1.1 100 Continue\r\n\r\n").is_err() { - return; - } - let copied = match body_mode { - HttpBodyMode::None => Ok(()), - HttpBodyMode::ContentLength(length) => { - copy_fixed_body(client, &mut upstream, &buffered, length, active) - } - HttpBodyMode::Chunked => copy_chunked_body(client, &mut upstream, &buffered, active), - }; - if copied.is_err() || active.shared.stopped.load(Ordering::Acquire) { - return; - } - // The forwarded request already has `Connection: close`, and this proxy - // handles one request per upstream socket. Do not send a TCP FIN before - // reading the response: some HTTP servers treat a peer half-close as a - // signal to close their write side before a delayed or streamed body ends. - let _ = io::copy(&mut upstream, client); -} - fn parse_request(header_text: &str) -> Option { let mut lines = header_text.split("\r\n"); let request_line = lines.next()?; @@ -1030,202 +633,6 @@ fn build_forwarded_request( Some((request, body_mode, expect_continue)) } -fn copy_fixed_body( - client: &mut TcpStream, - upstream: &mut TcpStream, - buffered: &[u8], - mut remaining: u64, - active: &ActiveSockets, -) -> io::Result<()> { - let prefix_count = buffered.len().min(remaining as usize); - if prefix_count > 0 { - upstream.write_all(&buffered[..prefix_count])?; - remaining -= prefix_count as u64; - } - let mut chunk = [0u8; RELAY_BUFFER_BYTES]; - while remaining > 0 { - if active.shared.stopped.load(Ordering::Acquire) { - return Err(io::Error::new( - io::ErrorKind::Interrupted, - "network operation was cancelled", - )); - } - let limit = chunk.len().min(remaining as usize); - let count = client.read(&mut chunk[..limit])?; - if count == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "HTTP request body ended early", - )); - } - upstream.write_all(&chunk[..count])?; - remaining -= count as u64; - } - Ok(()) -} - -struct PrefixReader<'a> { - client: &'a mut TcpStream, - prefix: &'a [u8], - position: usize, -} - -impl PrefixReader<'_> { - fn read_some(&mut self, output: &mut [u8]) -> io::Result { - if self.position < self.prefix.len() { - let count = output.len().min(self.prefix.len() - self.position); - output[..count].copy_from_slice(&self.prefix[self.position..self.position + count]); - self.position += count; - Ok(count) - } else { - self.client.read(output) - } - } - - fn read_exact_bytes(&mut self, mut output: &mut [u8]) -> io::Result<()> { - while !output.is_empty() { - let count = self.read_some(output)?; - if count == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "chunked HTTP request body ended early", - )); - } - output = &mut output[count..]; - } - Ok(()) - } - - fn read_crlf_line(&mut self) -> io::Result> { - let mut line = Vec::with_capacity(64); - let mut byte = [0u8; 1]; - loop { - if line.len() >= 8192 { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "chunk metadata line is too large", - )); - } - self.read_exact_bytes(&mut byte)?; - line.push(byte[0]); - if line.ends_with(b"\r\n") { - return Ok(line); - } - if byte[0] == b'\n' { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "invalid chunk metadata terminator", - )); - } - } - } -} - -fn copy_chunked_body( - client: &mut TcpStream, - upstream: &mut TcpStream, - buffered: &[u8], - active: &ActiveSockets, -) -> io::Result<()> { - let mut reader = PrefixReader { - client, - prefix: buffered, - position: 0, - }; - let mut total = 0u64; - loop { - if active.shared.stopped.load(Ordering::Acquire) { - return Err(io::Error::new( - io::ErrorKind::Interrupted, - "network operation was cancelled", - )); - } - let line = reader.read_crlf_line()?; - let line_without_crlf = line - .strip_suffix(b"\r\n") - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size line"))?; - let size_text = line_without_crlf - .split(|byte| *byte == b';') - .next() - .unwrap_or_default(); - let size_text = std::str::from_utf8(size_text) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; - let size = u64::from_str_radix(size_text.trim(), 16) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; - if size > MAX_HTTP_REQUEST_BODY_BYTES.saturating_sub(total) { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "HTTP request body exceeds the configured limit", - )); - } - upstream.write_all(&line)?; - if size == 0 { - loop { - let trailer = reader.read_crlf_line()?; - upstream.write_all(&trailer)?; - if trailer == b"\r\n" { - return Ok(()); - } - } - } - let mut remaining = size; - let mut chunk = [0u8; RELAY_BUFFER_BYTES]; - while remaining > 0 { - if active.shared.stopped.load(Ordering::Acquire) { - return Err(io::Error::new( - io::ErrorKind::Interrupted, - "network operation was cancelled", - )); - } - let count = chunk.len().min(remaining as usize); - reader.read_exact_bytes(&mut chunk[..count])?; - upstream.write_all(&chunk[..count])?; - remaining -= count as u64; - } - let mut terminator = [0u8; 2]; - reader.read_exact_bytes(&mut terminator)?; - if &terminator != b"\r\n" { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "invalid chunk terminator", - )); - } - upstream.write_all(&terminator)?; - total += size; - } -} - -fn read_request_header(stream: &mut TcpStream) -> io::Result<(Vec, Vec)> { - let mut bytes = Vec::with_capacity(4096); - let mut chunk = [0u8; 4096]; - loop { - if bytes.len() >= MAX_PROXY_HEADER_BYTES { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "proxy header too large", - )); - } - let count = stream.read(&mut chunk)?; - if count == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "proxy header ended", - )); - } - if bytes.len() + count > MAX_PROXY_HEADER_BYTES { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "proxy header too large", - )); - } - bytes.extend_from_slice(&chunk[..count]); - if let Some(index) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { - let split = index + 4; - return Ok((bytes[..split].to_vec(), bytes[split..].to_vec())); - } - } -} - fn parse_connect_target(target: &str) -> Result<(String, u16, bool), ()> { let url = url::Url::parse(&format!("https://{target}/")).map_err(|_| ())?; if !url.username().is_empty() @@ -1262,126 +669,6 @@ fn host_is_loopback(host: &url::Host<&str>) -> bool { /// Resolves a destination and applies the policy. Returns the vetted addresses /// only when every one is allowed; the caller must connect to those exact /// addresses (direct) or hand the hostname to the upstream proxy. -fn vet_destination( - host: &str, - port: u16, - allow_literal_loopback: bool, - active: &ActiveSockets, -) -> Option> { - let addresses = resolve_connection_destination(host, port, &active.shared.stopped)?; - let allowed = !addresses.is_empty() - && addresses.iter().all(|address| { - is_public_ip(address.ip()) - || (allow_literal_loopback && e2e_allows_literal_loopback(host, address.ip())) - }); - #[cfg(feature = "e2e")] - record_proxy_decision("connection", host, &addresses, allowed); - if !allowed || active.shared.stopped.load(Ordering::Acquire) { - return None; - } - Some(addresses) -} - -/// Connects to the addresses in order, bounded by the total connect budget. -fn connect_addresses(addresses: Vec, active: &ActiveSockets) -> Option { - // Each address gets its own attempt budget, with address families - // interleaved, so an unreachable IPv6 route cannot consume the time an - // IPv4 fallback needs (a simplified Happy Eyeballs, RFC 8305). - let deadline = Instant::now() + CONNECT_TOTAL_TIMEOUT; - for address in interleave_address_families(addresses) { - if active.shared.stopped.load(Ordering::Acquire) { - return None; - } - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - break; - } - if let Ok(stream) = TcpStream::connect_timeout(&address, remaining.min(CONNECT_TIMEOUT)) { - let _ = stream.set_read_timeout(Some(IO_TIMEOUT)); - let _ = stream.set_write_timeout(Some(IO_TIMEOUT)); - if active.register(&stream).is_err() { - let _ = stream.shutdown(Shutdown::Both); - return None; - } - return Some(stream); - } - } - None -} - -/// Opens a TCP connection to the upstream proxy itself. The upstream is -/// trusted and not vetted, so a private or loopback address is allowed. -fn connect_to_upstream_proxy(proxy: &UpstreamProxy, active: &ActiveSockets) -> Option { - let addresses = - resolve_connection_destination(&proxy.host, proxy.port, &active.shared.stopped)?; - connect_addresses(addresses, active) -} - -/// Opens a CONNECT tunnel through the upstream proxy to a destination that -/// has already been vetted. The hostname is sent as given, so the upstream -/// resolves it. Any failure is an error, which the caller reports as 502. -/// Returns the tunnel and any bytes the upstream sent after its headers. -fn connect_via_upstream( - proxy: &UpstreamProxy, - host: &str, - port: u16, - active: &ActiveSockets, -) -> Result<(TcpStream, Vec), ()> { - let mut stream = connect_to_upstream_proxy(proxy, active).ok_or(())?; - let authority = authority_for(host, port); - let request = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n\r\n"); - stream.write_all(request.as_bytes()).map_err(|_| ())?; - let (status, leftover) = read_upstream_response_head(&mut stream, &active.shared.stopped)?; - if !(200..300).contains(&status) { - return Err(()); - } - Ok((stream, leftover)) -} - -fn authority_for(host: &str, port: u16) -> String { - if host.contains(':') { - format!("[{host}]:{port}") - } else { - format!("{host}:{port}") - } -} - -/// Reads the upstream's status line and headers, bounded by -/// `MAX_UPSTREAM_RESPONSE_HEADER_BYTES` and by one `IO_TIMEOUT` for the whole -/// block, so a slow or endless header cannot hold a worker per read. Bytes -/// after the blank line belong to the tunnel and are returned with the status. -fn read_upstream_response_head( - stream: &mut TcpStream, - stopped: &AtomicBool, -) -> Result<(u16, Vec), ()> { - let deadline = Instant::now() + IO_TIMEOUT; - let mut bytes = Vec::with_capacity(512); - let mut chunk = [0u8; 1024]; - loop { - if let Some(end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { - if end + 4 > MAX_UPSTREAM_RESPONSE_HEADER_BYTES { - return Err(()); - } - let status = parse_status_code(&bytes[..end]).ok_or(())?; - return Ok((status, bytes[end + 4..].to_vec())); - } - if bytes.len() >= MAX_UPSTREAM_RESPONSE_HEADER_BYTES || stopped.load(Ordering::Acquire) { - return Err(()); - } - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - return Err(()); - } - stream.set_read_timeout(Some(remaining)).map_err(|_| ())?; - let count = stream.read(&mut chunk).map_err(|_| ())?; - if count == 0 { - return Err(()); - } - bytes.extend_from_slice(&chunk[..count]); - } -} - -/// The status code of an `HTTP/1.0` or `HTTP/1.1` status line. fn parse_status_code(head: &[u8]) -> Option { let line_end = head .windows(2) @@ -1435,21 +722,6 @@ fn resolve_destination(host: &str, port: u16) -> Option> { resolve_system_dns(host, port) } -fn resolve_connection_destination( - host: &str, - port: u16, - cancelled: &AtomicBool, -) -> Option> { - if let Some(ip) = parse_ip_host(host) { - return Some(vec![SocketAddr::new(ip, port)]); - } - #[cfg(feature = "e2e")] - if let Some(mapped) = e2e_proxy_dns_override(host) { - return Some(vec![SocketAddr::new(mapped, port)]); - } - resolve_system_dns_with_cancel(host, port, Some(cancelled)) -} - fn resolve_system_dns(host: &str, port: u16) -> Option> { resolve_system_dns_with_cancel(host, port, None) } @@ -1463,26 +735,32 @@ fn resolve_system_dns_with_cancel( return None; } let resolver = shared_dns_resolver()?; - let pending = resolver.enqueue(host, port)?; + let mut pending = resolver.enqueue(host, port)?; let deadline = Instant::now() + DNS_RESOLUTION_TIMEOUT; loop { if cancelled.is_some_and(|flag| flag.load(Ordering::Acquire)) { - resolver.cancel(&pending); + resolver.cancel(&mut pending); return None; } let remaining = deadline.saturating_duration_since(Instant::now()); if remaining.is_zero() { - resolver.cancel(&pending); + resolver.cancel(&mut pending); return None; } match pending .response .recv_timeout(remaining.min(DNS_RESOLUTION_POLL_INTERVAL)) { - Ok(result) => return result, + Ok(result) => { + pending.finish(); + return result; + } Err(mpsc::RecvTimeoutError::Timeout) => {} - Err(mpsc::RecvTimeoutError::Disconnected) => return None, + Err(mpsc::RecvTimeoutError::Disconnected) => { + pending.finish(); + return None; + } } } } @@ -1703,142 +981,6 @@ fn base64_encode(bytes: &[u8]) -> String { encoded } -fn write_proxy_error(stream: &mut TcpStream, code: u16, reason: &str) { - let body = format!("{code} {reason}\n"); - let response = format!( - "HTTP/1.1 {code} {reason}\r\nConnection: close\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}", - body.len() - ); - let _ = stream.write_all(response.as_bytes()); -} - -fn relay_bidirectional( - client: &mut TcpStream, - upstream: &mut TcpStream, - shared: &ProxyShared, - initial_client_data: &[u8], -) -> io::Result<()> { - if shared.stopped.load(Ordering::Acquire) { - return Err(io::Error::new( - io::ErrorKind::Interrupted, - "network operation was cancelled", - )); - } - upstream.write_all(initial_client_data)?; - client.set_nonblocking(true)?; - upstream.set_nonblocking(true)?; - - let mut client_to_upstream = [0u8; RELAY_BUFFER_BYTES]; - let mut client_to_upstream_len = 0usize; - let mut client_to_upstream_offset = 0usize; - let mut upstream_to_client = [0u8; RELAY_BUFFER_BYTES]; - let mut upstream_to_client_len = 0usize; - let mut upstream_to_client_offset = 0usize; - let mut client_read_open = true; - let mut upstream_read_open = true; - let mut last_activity = Instant::now(); - let mut idle_sleep = Duration::from_millis(1); - - loop { - if shared.stopped.load(Ordering::Acquire) { - return Err(io::Error::new( - io::ErrorKind::Interrupted, - "network operation was cancelled", - )); - } - let mut progressed = false; - if client_to_upstream_offset < client_to_upstream_len { - match upstream - .write(&client_to_upstream[client_to_upstream_offset..client_to_upstream_len]) - { - Ok(0) => return Err(io::ErrorKind::WriteZero.into()), - Ok(count) => { - client_to_upstream_offset += count; - progressed = true; - } - Err(error) if error.kind() == io::ErrorKind::WouldBlock => {} - Err(error) if error.kind() == io::ErrorKind::Interrupted => {} - Err(error) => return Err(error), - } - if client_to_upstream_offset == client_to_upstream_len { - client_to_upstream_len = 0; - client_to_upstream_offset = 0; - } - } - if upstream_to_client_offset < upstream_to_client_len { - match client - .write(&upstream_to_client[upstream_to_client_offset..upstream_to_client_len]) - { - Ok(0) => return Err(io::ErrorKind::WriteZero.into()), - Ok(count) => { - upstream_to_client_offset += count; - progressed = true; - } - Err(error) if error.kind() == io::ErrorKind::WouldBlock => {} - Err(error) if error.kind() == io::ErrorKind::Interrupted => {} - Err(error) => return Err(error), - } - if upstream_to_client_offset == upstream_to_client_len { - upstream_to_client_len = 0; - upstream_to_client_offset = 0; - } - } - - if client_read_open && client_to_upstream_len == 0 { - match client.read(&mut client_to_upstream) { - Ok(0) => { - client_read_open = false; - let _ = upstream.shutdown(Shutdown::Write); - progressed = true; - } - Ok(count) => { - client_to_upstream_len = count; - progressed = true; - } - Err(error) if error.kind() == io::ErrorKind::WouldBlock => {} - Err(error) if error.kind() == io::ErrorKind::Interrupted => {} - Err(error) => return Err(error), - } - } - if upstream_read_open && upstream_to_client_len == 0 { - match upstream.read(&mut upstream_to_client) { - Ok(0) => { - upstream_read_open = false; - let _ = client.shutdown(Shutdown::Write); - progressed = true; - } - Ok(count) => { - upstream_to_client_len = count; - progressed = true; - } - Err(error) if error.kind() == io::ErrorKind::WouldBlock => {} - Err(error) if error.kind() == io::ErrorKind::Interrupted => {} - Err(error) => return Err(error), - } - } - if !client_read_open - && !upstream_read_open - && client_to_upstream_len == 0 - && upstream_to_client_len == 0 - { - return Ok(()); - } - if progressed { - last_activity = Instant::now(); - idle_sleep = Duration::from_millis(1); - } else { - if last_activity.elapsed() >= TUNNEL_IDLE_TIMEOUT { - let _ = client.shutdown(Shutdown::Both); - let _ = upstream.shutdown(Shutdown::Both); - return Ok(()); - } - // Back off while idle so open pooled tunnels do not spin. - thread::sleep(idle_sleep); - idle_sleep = (idle_sleep * 2).min(RELAY_MAX_IDLE_SLEEP); - } - } -} - #[cfg(feature = "e2e")] fn e2e_dns_cancellation_probe() -> Result { const BATCHES: usize = 3; @@ -2126,11 +1268,13 @@ pub fn e2e_pipelining_probe() -> Result { "uniqueLocalBracketedIsPrivate": parse_ip_host("[fd00::1]").is_some_and(|address| !is_public_ip(address)), }); let policy_matrix = e2e_policy_matrix(); + let async_proxy = async_proxy::e2e_capacity_probe()?; Ok(serde_json::json!({ "requests": requests, "responseStatus": response_status, "responseBody": response_body, "secondTargetForwarded": requests.iter().any(|line| line.contains("/blocked") || line.contains("private.test")), + "asyncProxy": async_proxy, "dnsResolution": dns_resolution, "ipv6Classification": ipv6_classification, "policyMatrix": policy_matrix, diff --git a/src-tauri/src/network_security_async.rs b/src-tauri/src/network_security_async.rs new file mode 100644 index 00000000..c42c1f80 --- /dev/null +++ b/src-tauri/src/network_security_async.rs @@ -0,0 +1,1427 @@ +//! Bounded asynchronous implementation of the per-operation loopback proxy. +//! +//! The public guard remains synchronous because download and metadata callers +//! own it for a blocking subprocess or request. Its listener and all sockets +//! are serviced on Tauri's Tokio runtime; DNS stays in the separate fixed-size +//! resolver pool owned by `network_security`. + +use super::{ + HttpBodyMode, UpstreamProxy, CONNECT_TIMEOUT, CONNECT_TOTAL_TIMEOUT, DNS_RESOLUTION_TIMEOUT, + IO_TIMEOUT, MAX_HTTP_REQUEST_BODY_BYTES, MAX_PROXY_HEADER_BYTES, + MAX_UPSTREAM_RESPONSE_HEADER_BYTES, RELAY_BUFFER_BYTES, TUNNEL_IDLE_TIMEOUT, +}; +use crate::ip_policy::is_public_ip; +use std::collections::VecDeque; +use std::io; +#[cfg(feature = "e2e")] +use std::io::{Read, Write}; +#[cfg(feature = "e2e")] +use std::net::TcpStream as StdTcpStream; +use std::net::{Ipv4Addr, SocketAddr, TcpListener as StdTcpListener}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +#[cfg(feature = "e2e")] +use std::sync::OnceLock; +use std::sync::{mpsc, Arc}; +use std::time::{Duration, Instant as StdInstant}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::{watch, Semaphore}; +use tokio::task::JoinSet; +use tokio::time::{self, Instant}; + +const MAX_ACTIVE_PROXY_CLIENTS: usize = 256; +const MAX_PENDING_PROXY_CLIENTS: usize = 128; +const PENDING_ADMISSION_TIMEOUT: Duration = Duration::from_secs(5); +const PROXY_START_TIMEOUT: Duration = Duration::from_secs(2); +const OVERLOAD_WRITE_TIMEOUT: Duration = Duration::from_millis(100); +const EXTERNAL_CANCELLATION_POLL: Duration = Duration::from_millis(25); +const MAX_CHUNK_METADATA_LINE_BYTES: usize = 8192; + +fn io_timeout_error() -> io::Error { + io::Error::new(io::ErrorKind::TimedOut, "proxy I/O timed out") +} + +struct ProxyMetrics { + active_connections: AtomicUsize, + peak_active_connections: AtomicUsize, + active_tunnels: AtomicUsize, + peak_active_tunnels: AtomicUsize, + pending_admissions: AtomicUsize, + peak_pending_admissions: AtomicUsize, + overload_rejections: AtomicUsize, +} + +impl ProxyMetrics { + fn new() -> Self { + Self { + active_connections: AtomicUsize::new(0), + peak_active_connections: AtomicUsize::new(0), + active_tunnels: AtomicUsize::new(0), + peak_active_tunnels: AtomicUsize::new(0), + pending_admissions: AtomicUsize::new(0), + peak_pending_admissions: AtomicUsize::new(0), + overload_rejections: AtomicUsize::new(0), + } + } + + fn track(self: &Arc, kind: MetricKind) -> MetricGuard { + let (current, peak) = match kind { + MetricKind::Connection => (&self.active_connections, &self.peak_active_connections), + MetricKind::Tunnel => (&self.active_tunnels, &self.peak_active_tunnels), + }; + let active = current.fetch_add(1, Ordering::AcqRel) + 1; + update_peak(peak, active); + MetricGuard { + metrics: Arc::clone(self), + kind, + } + } + + fn track_pending(self: &Arc) -> PendingMetricGuard { + let active = self.pending_admissions.fetch_add(1, Ordering::AcqRel) + 1; + update_peak(&self.peak_pending_admissions, active); + PendingMetricGuard { + metrics: Arc::clone(self), + } + } + + #[cfg(feature = "e2e")] + fn snapshot(&self) -> ProxyMetricsSnapshot { + ProxyMetricsSnapshot { + active_connections: self.active_connections.load(Ordering::Acquire), + peak_active_connections: self.peak_active_connections.load(Ordering::Acquire), + active_tunnels: self.active_tunnels.load(Ordering::Acquire), + peak_active_tunnels: self.peak_active_tunnels.load(Ordering::Acquire), + pending_admissions: self.pending_admissions.load(Ordering::Acquire), + peak_pending_admissions: self.peak_pending_admissions.load(Ordering::Acquire), + overload_rejections: self.overload_rejections.load(Ordering::Acquire), + } + } +} + +fn update_peak(peak: &AtomicUsize, observed: usize) { + let mut current = peak.load(Ordering::Relaxed); + while observed > current { + match peak.compare_exchange_weak(current, observed, Ordering::Release, Ordering::Relaxed) { + Ok(_) => break, + Err(actual) => current = actual, + } + } +} + +#[derive(Clone, Copy)] +enum MetricKind { + Connection, + Tunnel, +} + +struct MetricGuard { + metrics: Arc, + kind: MetricKind, +} + +impl Drop for MetricGuard { + fn drop(&mut self) { + let current = match self.kind { + MetricKind::Connection => &self.metrics.active_connections, + MetricKind::Tunnel => &self.metrics.active_tunnels, + }; + current.fetch_sub(1, Ordering::AcqRel); + } +} + +struct PendingMetricGuard { + metrics: Arc, +} + +impl Drop for PendingMetricGuard { + fn drop(&mut self) { + self.metrics + .pending_admissions + .fetch_sub(1, Ordering::AcqRel); + } +} + +#[cfg(feature = "e2e")] +#[derive(Clone, Copy)] +struct ProxyMetricsSnapshot { + active_connections: usize, + peak_active_connections: usize, + active_tunnels: usize, + peak_active_tunnels: usize, + pending_admissions: usize, + peak_pending_admissions: usize, + overload_rejections: usize, +} + +struct ProxyShared { + stopped: AtomicBool, + operation_cancelled: Option>, + shutdown: watch::Sender, + upstream: Option, + metrics: Arc, +} + +impl ProxyShared { + fn is_cancelled(&self) -> bool { + self.stopped.load(Ordering::Acquire) + || self + .operation_cancelled + .as_ref() + .is_some_and(|flag| flag.load(Ordering::Acquire)) + } + + async fn cancelled(&self) { + let mut shutdown = self.shutdown.subscribe(); + loop { + if self.is_cancelled() { + return; + } + tokio::select! { + _ = shutdown.changed() => {}, + _ = time::sleep(EXTERNAL_CANCELLATION_POLL) => {}, + } + } + } + + async fn shutdown_notified(&self) { + let mut shutdown = self.shutdown.subscribe(); + loop { + if *shutdown.borrow() { + return; + } + if shutdown.changed().await.is_err() { + return; + } + } + } + + fn stop(&self) { + self.stopped.store(true, Ordering::Release); + self.shutdown.send_replace(true); + } +} + +struct PendingClient { + stream: TcpStream, + accepted_at: Instant, + _metrics: PendingMetricGuard, +} + +/// Synchronous compatibility facade. The listener and every client task run on +/// Tauri's runtime. Dropping the guard signals shutdown; the listener and all +/// tracked client tasks then finish without the caller joining them. +pub struct NetworkSecurityGuard { + proxy_url: String, + shared: Arc, +} + +impl NetworkSecurityGuard { + #[cfg(feature = "e2e")] + pub fn start() -> Result { + Self::start_inner(None, None) + } + + pub fn start_with_cancellation( + operation_cancelled: Arc, + upstream_proxy: &str, + ) -> Result { + let upstream = super::parse_upstream_proxy(upstream_proxy)?; + Self::start_inner(Some(operation_cancelled), upstream) + } + + fn start_inner( + operation_cancelled: Option>, + upstream: Option, + ) -> Result { + if operation_cancelled + .as_ref() + .is_some_and(|flag| flag.load(Ordering::Acquire)) + { + return Err("The network operation was cancelled.".into()); + } + + let listener = StdTcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .map_err(|error| format!("Could not start the secure network proxy: {error}"))?; + listener + .set_nonblocking(true) + .map_err(|error| format!("Could not configure the secure network proxy: {error}"))?; + let bind_addr = listener + .local_addr() + .map_err(|error| format!("Could not inspect the secure network proxy: {error}"))?; + + let mut token = [0u8; 24]; + getrandom::fill(&mut token) + .map_err(|error| format!("Could not create secure proxy credentials: {error}"))?; + let token = token + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + let expected_auth = Arc::::from(format!( + "Basic {}", + super::base64_encode(format!("rosi:{token}").as_bytes()) + )); + let proxy_url = format!("http://rosi:{token}@{bind_addr}"); + let (shutdown, _) = watch::channel(false); + let shared = Arc::new(ProxyShared { + stopped: AtomicBool::new(false), + operation_cancelled, + shutdown, + upstream, + metrics: Arc::new(ProxyMetrics::new()), + }); + let task_shared = Arc::clone(&shared); + let (ready_sender, ready_receiver) = mpsc::sync_channel(1); + // The listener runs Tauri's runtime on a dedicated thread. A task + // spawned from a runtime worker can sit in that worker's LIFO slot + // while the worker blocks in this synchronous constructor, so the + // readiness wait must not depend on the worker pool. + let spawned = std::thread::Builder::new() + .name("rosi-network-proxy".into()) + .spawn(move || { + tauri::async_runtime::block_on(async move { + let listener = match TcpListener::from_std(listener) { + Ok(listener) => listener, + Err(error) => { + let _ = ready_sender.send(Err(error.to_string())); + return; + } + }; + let _ = ready_sender.send(Ok(())); + run_proxy(listener, task_shared, expected_auth).await; + }); + }); + if let Err(error) = spawned { + shared.stop(); + return Err(format!( + "Could not start the secure network proxy: {error}" + )); + } + match ready_receiver.recv_timeout(PROXY_START_TIMEOUT) { + Ok(Ok(())) => Ok(Self { proxy_url, shared }), + Ok(Err(error)) => { + shared.stop(); + Err(format!("Could not start the secure network proxy: {error}")) + } + Err(error) => { + shared.stop(); + Err(format!("Could not start the secure network proxy: {error}")) + } + } + } + + pub fn proxy_url(&self) -> &str { + &self.proxy_url + } +} + +impl Drop for NetworkSecurityGuard { + fn drop(&mut self) { + self.shared.stop(); + } +} + +async fn run_proxy(listener: TcpListener, shared: Arc, expected_auth: Arc) { + let semaphore = Arc::new(Semaphore::new(MAX_ACTIVE_PROXY_CLIENTS)); + let mut handlers = JoinSet::new(); + let mut pending = VecDeque::::new(); + + loop { + if shared.is_cancelled() { + break; + } + while handlers.try_join_next().is_some() {} + + while let Some(next) = pending.front() { + if next.accepted_at.elapsed() >= PENDING_ADMISSION_TIMEOUT { + let Some(expired) = pending.pop_front() else { + break; + }; + let mut stream = expired.stream; + reject_client(&mut stream, 503, "Proxy Admission Timeout").await; + continue; + } + let Ok(permit) = Arc::clone(&semaphore).try_acquire_owned() else { + break; + }; + let Some(admitted) = pending.pop_front() else { + break; + }; + drop(admitted._metrics); + spawn_client( + admitted.stream, + permit, + Arc::clone(&shared), + Arc::clone(&expected_auth), + &mut handlers, + ); + } + + let admission_deadline = pending + .front() + .map(|item| item.accepted_at + PENDING_ADMISSION_TIMEOUT); + tokio::select! { + _ = shared.cancelled() => break, + joined = handlers.join_next(), if !handlers.is_empty() => { + let _ = joined; + } + accepted = listener.accept() => { + let (client, _) = match accepted { + Ok(accepted) => accepted, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => break, + }; + if shared.is_cancelled() { + drop(client); + break; + } + if pending.is_empty() { + if let Ok(permit) = Arc::clone(&semaphore).try_acquire_owned() { + spawn_client( + client, + permit, + Arc::clone(&shared), + Arc::clone(&expected_auth), + &mut handlers, + ); + } else if pending.len() < MAX_PENDING_PROXY_CLIENTS { + pending.push_back(PendingClient { + stream: client, + accepted_at: Instant::now(), + _metrics: shared.metrics.track_pending(), + }); + } else { + shared.metrics.overload_rejections.fetch_add(1, Ordering::AcqRel); + let mut client = client; + reject_client(&mut client, 503, "Proxy Busy").await; + } + } else if pending.len() < MAX_PENDING_PROXY_CLIENTS { + pending.push_back(PendingClient { + stream: client, + accepted_at: Instant::now(), + _metrics: shared.metrics.track_pending(), + }); + } else { + shared.metrics.overload_rejections.fetch_add(1, Ordering::AcqRel); + let mut client = client; + reject_client(&mut client, 503, "Proxy Busy").await; + } + } + _ = wait_for_admission_expiry(admission_deadline), if admission_deadline.is_some() => {} + } + } + + pending.clear(); + handlers.abort_all(); + while handlers.join_next().await.is_some() {} +} + +async fn wait_for_admission_expiry(deadline: Option) { + if let Some(deadline) = deadline { + time::sleep_until(deadline).await; + } else { + std::future::pending::<()>().await; + } +} + +fn spawn_client( + client: TcpStream, + permit: tokio::sync::OwnedSemaphorePermit, + shared: Arc, + expected_auth: Arc, + handlers: &mut JoinSet<()>, +) { + let metrics = Arc::clone(&shared.metrics); + handlers.spawn(async move { + let _permit = permit; + let _connection = metrics.track(MetricKind::Connection); + tokio::select! { + _ = shared.shutdown_notified() => {}, + _ = handle_client(client, expected_auth, Arc::clone(&shared)) => {}, + } + }); +} + +async fn handle_client(mut client: TcpStream, expected_auth: Arc, shared: Arc) { + let (header, buffered) = match time::timeout(IO_TIMEOUT, read_request_header(&mut client)).await + { + Ok(Ok(result)) => result, + _ => return, + }; + let Ok(header_text) = std::str::from_utf8(&header) else { + reject_client(&mut client, 400, "Bad Request").await; + return; + }; + let Some((method, target, version, headers)) = super::parse_request(header_text) else { + reject_client(&mut client, 400, "Bad Request").await; + return; + }; + let auth_values: Vec<&str> = headers + .iter() + .filter(|(name, _)| name.eq_ignore_ascii_case("proxy-authorization")) + .map(|(_, value)| value.trim()) + .collect(); + if auth_values.len() != 1 || auth_values[0] != expected_auth.as_ref() { + reject_client(&mut client, 407, "Proxy Authentication Required").await; + return; + } + + if method.eq_ignore_ascii_case("CONNECT") { + let Ok((host, port, is_literal_loopback)) = super::parse_connect_target(&target) else { + reject_client(&mut client, 400, "Bad CONNECT Target").await; + return; + }; + let Some(addresses) = vet_destination(&host, port, is_literal_loopback, &shared).await + else { + reject_client(&mut client, 403, "Destination Blocked").await; + return; + }; + let (mut upstream, tunnel_leftover) = match shared.upstream.as_ref() { + None => match connect_addresses(addresses).await { + Some(stream) => (stream, Vec::new()), + None => { + reject_client(&mut client, 403, "Destination Blocked").await; + return; + } + }, + Some(proxy) => match connect_via_upstream(proxy, &host, port).await { + Ok(tunnel) => tunnel, + Err(()) => { + reject_client(&mut client, 502, "Upstream Proxy Failed").await; + return; + } + }, + }; + if shared.is_cancelled() { + return; + } + if !matches!( + time::timeout( + IO_TIMEOUT, + client.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n"), + ) + .await, + Ok(Ok(())) + ) { + return; + } + if !tunnel_leftover.is_empty() + && !matches!( + time::timeout(IO_TIMEOUT, client.write_all(&tunnel_leftover)).await, + Ok(Ok(())) + ) + { + return; + } + if !buffered.is_empty() + && !matches!( + time::timeout(IO_TIMEOUT, upstream.write_all(&buffered)).await, + Ok(Ok(())) + ) + { + return; + } + let _tunnel = shared.metrics.track(MetricKind::Tunnel); + let _ = relay_bidirectional(client, upstream, Arc::clone(&shared)).await; + return; + } + + let Ok(url) = url::Url::parse(&target) else { + reject_client(&mut client, 400, "Absolute URL Required").await; + return; + }; + if url.scheme() != "http" || !url.username().is_empty() || url.password().is_some() { + reject_client(&mut client, 403, "Destination Blocked").await; + return; + } + let Some(url_host) = url.host() else { + reject_client(&mut client, 400, "Missing Host").await; + return; + }; + let host = super::host_string(&url_host); + let Some(port) = url.port_or_known_default() else { + reject_client(&mut client, 400, "Missing Port").await; + return; + }; + let literal_loopback = super::host_is_loopback(&url_host); + let Some(addresses) = vet_destination(&host, port, literal_loopback, &shared).await else { + reject_client(&mut client, 403, "Destination Blocked").await; + return; + }; + let absolute_form = shared.upstream.is_some(); + let mut upstream = match shared.upstream.as_ref() { + None => match connect_addresses(addresses).await { + Some(stream) => stream, + None => { + reject_client(&mut client, 403, "Destination Blocked").await; + return; + } + }, + Some(proxy) => match connect_to_upstream_proxy(proxy).await { + Some(stream) => stream, + None => { + reject_client(&mut client, 502, "Upstream Proxy Failed").await; + return; + } + }, + }; + let Some((forwarded, body_mode, expect_continue)) = + super::build_forwarded_request(&method, &version, &url, &headers, absolute_form) + else { + reject_client(&mut client, 400, "Unsupported HTTP Request").await; + return; + }; + if !matches!( + time::timeout(IO_TIMEOUT, upstream.write_all(&forwarded)).await, + Ok(Ok(())) + ) { + return; + } + if expect_continue + && !matches!( + time::timeout( + IO_TIMEOUT, + client.write_all(b"HTTP/1.1 100 Continue\r\n\r\n") + ) + .await, + Ok(Ok(())) + ) + { + return; + } + let copied = match body_mode { + HttpBodyMode::None => Ok(()), + HttpBodyMode::ContentLength(length) => { + copy_fixed_body(&mut client, &mut upstream, &buffered, length).await + } + HttpBodyMode::Chunked => copy_chunked_body(&mut client, &mut upstream, &buffered).await, + }; + if copied.is_err() || shared.is_cancelled() { + return; + } + let _ = copy_response(&mut upstream, &mut client).await; +} + +async fn read_request_header(stream: &mut TcpStream) -> io::Result<(Vec, Vec)> { + let mut bytes = Vec::with_capacity(4096); + let mut chunk = [0u8; 4096]; + loop { + if bytes.len() >= MAX_PROXY_HEADER_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "proxy header too large", + )); + } + let count = stream.read(&mut chunk).await?; + if count == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "proxy header ended", + )); + } + if bytes.len() + count > MAX_PROXY_HEADER_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "proxy header too large", + )); + } + bytes.extend_from_slice(&chunk[..count]); + if let Some(index) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { + let split = index + 4; + return Ok((bytes[..split].to_vec(), bytes[split..].to_vec())); + } + } +} + +async fn reject_client(stream: &mut TcpStream, code: u16, reason: &str) { + let body = format!("{code} {reason}\n"); + let response = format!( + "HTTP/1.1 {code} {reason}\r\nConnection: close\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + let _ = time::timeout( + OVERLOAD_WRITE_TIMEOUT, + stream.write_all(response.as_bytes()), + ) + .await; + let _ = stream.shutdown().await; +} + +async fn vet_destination( + host: &str, + port: u16, + allow_literal_loopback: bool, + shared: &ProxyShared, +) -> Option> { + let addresses = time::timeout(DNS_RESOLUTION_TIMEOUT, resolve_destination(host, port)) + .await + .ok()??; + let allowed = !addresses.is_empty() + && addresses.iter().all(|address| { + is_public_ip(address.ip()) + || (allow_literal_loopback + && super::e2e_allows_literal_loopback(host, address.ip())) + }); + #[cfg(feature = "e2e")] + super::record_proxy_decision("connection", host, &addresses, allowed); + if !allowed || shared.is_cancelled() { + return None; + } + Some(addresses) +} + +async fn resolve_destination(host: &str, port: u16) -> Option> { + if let Some(ip) = super::parse_ip_host(host) { + return Some(vec![SocketAddr::new(ip, port)]); + } + #[cfg(feature = "e2e")] + if let Some(ip) = super::e2e_proxy_dns_override(host) { + return Some(vec![SocketAddr::new(ip, port)]); + } + + let resolver = super::shared_dns_resolver()?; + let mut pending = resolver.enqueue(host, port)?; + let started = StdInstant::now(); + loop { + match pending.response.try_recv() { + Ok(addresses) => { + pending.finish(); + return addresses; + } + Err(mpsc::TryRecvError::Disconnected) => { + pending.finish(); + return None; + } + Err(mpsc::TryRecvError::Empty) => {} + } + let remaining = DNS_RESOLUTION_TIMEOUT.saturating_sub(started.elapsed()); + if remaining.is_zero() { + return None; + } + time::sleep(remaining.min(Duration::from_millis(25))).await; + } +} + +async fn connect_addresses(addresses: Vec) -> Option { + let deadline = Instant::now() + CONNECT_TOTAL_TIMEOUT; + for address in super::interleave_address_families(addresses) { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break; + } + if let Ok(Ok(stream)) = + time::timeout(remaining.min(CONNECT_TIMEOUT), TcpStream::connect(address)).await + { + return Some(stream); + } + } + None +} + +/// Connects to the user's upstream proxy without applying public-IP policy to +/// that proxy. Its hostname is still resolved by the bounded DNS resolver. +async fn connect_to_upstream_proxy(proxy: &UpstreamProxy) -> Option { + let addresses = time::timeout( + DNS_RESOLUTION_TIMEOUT, + resolve_destination(&proxy.host, proxy.port), + ) + .await + .ok()??; + connect_addresses(addresses).await +} + +async fn connect_via_upstream( + proxy: &UpstreamProxy, + host: &str, + port: u16, +) -> Result<(TcpStream, Vec), ()> { + let mut stream = connect_to_upstream_proxy(proxy).await.ok_or(())?; + let authority = authority_for(host, port); + let request = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n\r\n"); + time::timeout(IO_TIMEOUT, stream.write_all(request.as_bytes())) + .await + .map_err(|_| ())? + .map_err(|_| ())?; + let (status, leftover) = read_upstream_response_head(&mut stream).await?; + if !(200..300).contains(&status) { + return Err(()); + } + Ok((stream, leftover)) +} + +fn authority_for(host: &str, port: u16) -> String { + if host.contains(':') { + format!("[{host}]:{port}") + } else { + format!("{host}:{port}") + } +} + +async fn read_upstream_response_head(stream: &mut TcpStream) -> Result<(u16, Vec), ()> { + time::timeout(IO_TIMEOUT, async { + let mut bytes = Vec::with_capacity(512); + let mut chunk = [0u8; 1024]; + loop { + if let Some(end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { + if end + 4 > MAX_UPSTREAM_RESPONSE_HEADER_BYTES { + return Err(()); + } + let status = super::parse_status_code(&bytes[..end]).ok_or(())?; + return Ok((status, bytes[end + 4..].to_vec())); + } + if bytes.len() >= MAX_UPSTREAM_RESPONSE_HEADER_BYTES { + return Err(()); + } + let count = stream.read(&mut chunk).await.map_err(|_| ())?; + if count == 0 { + return Err(()); + } + bytes.extend_from_slice(&chunk[..count]); + } + }) + .await + .map_err(|_| ())? +} + +async fn copy_fixed_body( + client: &mut TcpStream, + upstream: &mut TcpStream, + buffered: &[u8], + length: u64, +) -> io::Result<()> { + let mut reader = AsyncPrefixReader { + stream: client, + prefix: buffered, + position: 0, + }; + let mut remaining = length; + let mut chunk = [0u8; RELAY_BUFFER_BYTES]; + while remaining > 0 { + let count = chunk.len().min(remaining.min(usize::MAX as u64) as usize); + let read = time::timeout(IO_TIMEOUT, reader.read_some(&mut chunk[..count])) + .await + .map_err(|_| io_timeout_error())?; + let read = read?; + if read == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "HTTP request body ended early", + )); + } + time::timeout(IO_TIMEOUT, upstream.write_all(&chunk[..read])) + .await + .map_err(|_| io_timeout_error())??; + remaining -= read as u64; + } + Ok(()) +} + +struct AsyncPrefixReader<'a> { + stream: &'a mut TcpStream, + prefix: &'a [u8], + position: usize, +} + +impl AsyncPrefixReader<'_> { + async fn read_some(&mut self, output: &mut [u8]) -> io::Result { + if self.position < self.prefix.len() { + let count = output.len().min(self.prefix.len() - self.position); + output[..count].copy_from_slice(&self.prefix[self.position..self.position + count]); + self.position += count; + Ok(count) + } else { + self.stream.read(output).await + } + } + + async fn read_exact_bytes(&mut self, mut output: &mut [u8]) -> io::Result<()> { + while !output.is_empty() { + let count = time::timeout(IO_TIMEOUT, self.read_some(output)) + .await + .map_err(|_| io_timeout_error())??; + if count == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "chunked HTTP request body ended early", + )); + } + output = &mut output[count..]; + } + Ok(()) + } + + async fn read_crlf_line(&mut self) -> io::Result> { + let mut line = Vec::with_capacity(64); + let mut byte = [0u8; 1]; + loop { + if line.len() >= MAX_CHUNK_METADATA_LINE_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "chunk metadata line is too large", + )); + } + self.read_exact_bytes(&mut byte).await?; + line.push(byte[0]); + if line.ends_with(b"\r\n") { + return Ok(line); + } + if byte[0] == b'\n' { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid chunk metadata terminator", + )); + } + } + } +} + +async fn copy_chunked_body( + client: &mut TcpStream, + upstream: &mut TcpStream, + buffered: &[u8], +) -> io::Result<()> { + let mut reader = AsyncPrefixReader { + stream: client, + prefix: buffered, + position: 0, + }; + let mut total = 0u64; + loop { + let line = reader.read_crlf_line().await?; + let line_without_crlf = line + .strip_suffix(b"\r\n") + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size line"))?; + let size_text = line_without_crlf + .split(|byte| *byte == b';') + .next() + .unwrap_or_default(); + let size_text = std::str::from_utf8(size_text) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; + let size = u64::from_str_radix(size_text.trim(), 16) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; + if size > MAX_HTTP_REQUEST_BODY_BYTES.saturating_sub(total) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "HTTP request body exceeds the configured limit", + )); + } + time::timeout(IO_TIMEOUT, upstream.write_all(&line)) + .await + .map_err(|_| io_timeout_error())??; + if size == 0 { + loop { + let trailer = reader.read_crlf_line().await?; + time::timeout(IO_TIMEOUT, upstream.write_all(&trailer)) + .await + .map_err(|_| io_timeout_error())??; + if trailer == b"\r\n" { + return Ok(()); + } + } + } + let mut remaining = size; + let mut chunk = [0u8; RELAY_BUFFER_BYTES]; + while remaining > 0 { + let count = chunk.len().min(remaining.min(usize::MAX as u64) as usize); + reader.read_exact_bytes(&mut chunk[..count]).await?; + time::timeout(IO_TIMEOUT, upstream.write_all(&chunk[..count])) + .await + .map_err(|_| io_timeout_error())??; + remaining -= count as u64; + } + let mut terminator = [0u8; 2]; + reader.read_exact_bytes(&mut terminator).await?; + if &terminator != b"\r\n" { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid chunk terminator", + )); + } + time::timeout(IO_TIMEOUT, upstream.write_all(&terminator)) + .await + .map_err(|_| io_timeout_error())??; + total += size; + } +} + +async fn copy_response(upstream: &mut TcpStream, client: &mut TcpStream) -> io::Result<()> { + let mut buffer = [0u8; RELAY_BUFFER_BYTES]; + loop { + let count = time::timeout(IO_TIMEOUT, upstream.read(&mut buffer)) + .await + .map_err(|_| io_timeout_error())??; + if count == 0 { + return Ok(()); + } + time::timeout(IO_TIMEOUT, client.write_all(&buffer[..count])) + .await + .map_err(|_| io_timeout_error())??; + } +} + +struct Activity { + started: Instant, + last_activity_ms: AtomicU64, + changed: tokio::sync::Notify, +} + +impl Activity { + fn new() -> Self { + Self { + started: Instant::now(), + last_activity_ms: AtomicU64::new(0), + changed: tokio::sync::Notify::new(), + } + } + + fn record(&self) { + let elapsed = self.started.elapsed().as_millis().min(u64::MAX as u128) as u64; + self.last_activity_ms.store(elapsed, Ordering::Release); + self.changed.notify_one(); + } + + fn deadline(&self) -> Instant { + self.started + + Duration::from_millis(self.last_activity_ms.load(Ordering::Acquire)) + + TUNNEL_IDLE_TIMEOUT + } + + async fn idle(&self, deadline: Instant) { + tokio::select! { + _ = time::sleep_until(deadline) => {}, + _ = self.changed.notified() => {}, + } + } +} + +struct ActivityStream { + inner: T, + activity: Arc, +} + +impl AsyncRead for ActivityStream { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buffer: &mut ReadBuf<'_>, + ) -> std::task::Poll> { + let this = self.as_mut().get_mut(); + let before = buffer.filled().len(); + let result = std::pin::Pin::new(&mut this.inner).poll_read(cx, buffer); + if matches!(&result, std::task::Poll::Ready(Ok(()))) && buffer.filled().len() > before { + this.activity.record(); + } + result + } +} + +impl AsyncWrite for ActivityStream { + fn poll_write( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buffer: &[u8], + ) -> std::task::Poll> { + let this = self.as_mut().get_mut(); + let result = std::pin::Pin::new(&mut this.inner).poll_write(cx, buffer); + if matches!(&result, std::task::Poll::Ready(Ok(count)) if *count > 0) { + this.activity.record(); + } + result + } + + fn poll_flush( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.as_mut().get_mut().inner).poll_flush(cx) + } + + fn poll_shutdown( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.as_mut().get_mut().inner).poll_shutdown(cx) + } +} + +async fn relay_bidirectional( + client: TcpStream, + upstream: TcpStream, + shared: Arc, +) -> io::Result<()> { + let activity = Arc::new(Activity::new()); + let mut client = ActivityStream { + inner: client, + activity: Arc::clone(&activity), + }; + let mut upstream = ActivityStream { + inner: upstream, + activity: Arc::clone(&activity), + }; + let relay = tokio::io::copy_bidirectional(&mut client, &mut upstream); + tokio::pin!(relay); + loop { + let idle_deadline = activity.deadline(); + tokio::select! { + result = &mut relay => return result.map(|_| ()), + _ = shared.shutdown_notified() => { + return Err(io::Error::new(io::ErrorKind::Interrupted, "network operation was cancelled")); + } + _ = activity.idle(idle_deadline) => { + if activity.deadline() <= Instant::now() { + return Ok(()); + } + } + } + } +} + +#[cfg(feature = "e2e")] +struct CapacityClients { + active: Vec, + pending: Vec, +} + +#[cfg(feature = "e2e")] +pub(super) fn e2e_capacity_probe() -> Result { + static RESULT: OnceLock> = OnceLock::new(); + RESULT.get_or_init(run_e2e_capacity_probe).clone() +} + +#[cfg(feature = "e2e")] +fn run_e2e_capacity_probe() -> Result { + let cancellation = Arc::new(AtomicBool::new(false)); + let guard = NetworkSecurityGuard::start_with_cancellation(Arc::clone(&cancellation), "")?; + let metrics = Arc::clone(&guard.shared.metrics); + let origin = StdTcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .map_err(|error| format!("could not bind async proxy origin: {error}"))?; + origin + .set_nonblocking(true) + .map_err(|error| format!("could not configure async proxy origin: {error}"))?; + let origin_port = origin + .local_addr() + .map_err(|error| format!("could not inspect async proxy origin: {error}"))? + .port(); + let (origin_count_sender, origin_count_receiver) = mpsc::sync_channel(1); + let (origin_release_sender, origin_release_receiver) = mpsc::sync_channel(1); + let origin_cancellation = Arc::clone(&cancellation); + let origin_thread = std::thread::Builder::new() + .name("rosi-e2e-async-proxy-origin".into()) + .spawn(move || { + let mut streams = Vec::with_capacity(MAX_ACTIVE_PROXY_CLIENTS); + let deadline = StdInstant::now() + Duration::from_secs(20); + while streams.len() < MAX_ACTIVE_PROXY_CLIENTS + && StdInstant::now() < deadline + && !origin_cancellation.load(Ordering::Acquire) + { + match origin.accept() { + Ok((stream, _)) => streams.push(stream), + Err(error) if error.kind() == io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(2)); + } + Err(_) => break, + } + } + let accepted = streams.len(); + let _ = origin_count_sender.send(accepted); + let _ = origin_release_receiver.recv_timeout(Duration::from_secs(10)); + let mut closed = 0usize; + for mut stream in streams { + let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); + let mut byte = [0u8; 1]; + match stream.read(&mut byte) { + Ok(0) | Err(_) => closed += 1, + Ok(_) => {} + } + } + (accepted, closed) + }) + .map_err(|error| format!("could not start async proxy origin: {error}"))?; + + let capacity_phase = run_capacity_phase(&guard, origin_port, origin_count_receiver); + let cancellation_started = StdInstant::now(); + cancellation.store(true, Ordering::Release); + let cancellation_drained = + wait_for_proxy_metrics(&metrics, Duration::from_secs(5), |snapshot| { + snapshot.active_connections == 0 + && snapshot.active_tunnels == 0 + && snapshot.pending_admissions == 0 + }); + let after_cancel = metrics.snapshot(); + drop(guard); + let _ = origin_release_sender.send(()); + let origin_result = origin_thread + .join() + .map_err(|_| "async proxy E2E origin thread panicked".to_owned()); + let (capacity, clients) = capacity_phase?; + let (origin_accepted, origin_closed) = origin_result?; + let closed_clients = clients + .active + .into_iter() + .chain(clients.pending) + .filter(|mut stream| { + let _ = stream.set_read_timeout(Some(Duration::from_secs(2))); + let mut byte = [0u8; 1]; + socket_closed(stream.read(&mut byte)) + }) + .count(); + if !cancellation_drained { + return Err(format!( + "operation cancellation did not drain proxy tasks: active={} tunnels={} pending={}", + after_cancel.active_connections, + after_cancel.active_tunnels, + after_cancel.pending_admissions + )); + } + if closed_clients != MAX_ACTIVE_PROXY_CLIENTS + MAX_PENDING_PROXY_CLIENTS { + return Err(format!( + "operation cancellation closed {closed_clients} client sockets; expected {}", + MAX_ACTIVE_PROXY_CLIENTS + MAX_PENDING_PROXY_CLIENTS + )); + } + if origin_accepted != MAX_ACTIVE_PROXY_CLIENTS || origin_closed != MAX_ACTIVE_PROXY_CLIENTS { + return Err(format!( + "operation cancellation closed {origin_closed}/{origin_accepted} origin sockets; expected {}", + MAX_ACTIVE_PROXY_CLIENTS + )); + } + + let drop = e2e_guard_drop_probe()?; + Ok(serde_json::json!({ + "capacity": capacity, + "cancellation": { + "activeConnectionsAfterCancel": after_cancel.active_connections, + "activeTunnelsAfterCancel": after_cancel.active_tunnels, + "pendingAdmissionsAfterCancel": after_cancel.pending_admissions, + "closedClientSockets": closed_clients, + "expectedClientSockets": MAX_ACTIVE_PROXY_CLIENTS + MAX_PENDING_PROXY_CLIENTS, + "closedOriginSockets": origin_closed, + "expectedOriginSockets": MAX_ACTIVE_PROXY_CLIENTS, + "elapsedMs": cancellation_started.elapsed().as_millis(), + }, + "drop": drop, + })) +} + +#[cfg(feature = "e2e")] +fn run_capacity_phase( + guard: &NetworkSecurityGuard, + origin_port: u16, + origin_count_receiver: mpsc::Receiver, +) -> Result<(serde_json::Value, CapacityClients), String> { + let (proxy_address, authorization) = proxy_e2e_credentials(guard.proxy_url())?; + let connect_request = format!( + "CONNECT 127.0.0.1:{origin_port} HTTP/1.1\r\nHost: 127.0.0.1:{origin_port}\r\nProxy-Authorization: Basic {authorization}\r\n\r\n" + ); + let mut active = Vec::with_capacity(MAX_ACTIVE_PROXY_CLIENTS); + for index in 0..MAX_ACTIVE_PROXY_CLIENTS { + let mut client = connect_e2e_client(proxy_address)?; + client + .write_all(connect_request.as_bytes()) + .map_err(|error| format!("could not open E2E tunnel {index}: {error}"))?; + let (status, _) = read_e2e_response_head(&mut client)?; + if status != 200 { + return Err(format!( + "E2E tunnel {index} received HTTP {status}, expected 200" + )); + } + active.push(client); + } + + let origin_accepted = origin_count_receiver + .recv_timeout(Duration::from_secs(10)) + .map_err(|error| format!("async proxy origin did not accept tunnels: {error}"))?; + if origin_accepted != MAX_ACTIVE_PROXY_CLIENTS { + return Err(format!( + "origin accepted {origin_accepted} tunnels, expected {MAX_ACTIVE_PROXY_CLIENTS}" + )); + } + if !wait_for_proxy_metrics(&guard.shared.metrics, Duration::from_secs(5), |snapshot| { + snapshot.active_tunnels >= MAX_ACTIVE_PROXY_CLIENTS + }) { + let snapshot = guard.shared.metrics.snapshot(); + return Err(format!( + "only {} of {} concurrent tunnels became active", + snapshot.active_tunnels, MAX_ACTIVE_PROXY_CLIENTS + )); + } + let at_capacity = guard.shared.metrics.snapshot(); + + let mut pending = Vec::with_capacity(MAX_PENDING_PROXY_CLIENTS); + for index in 0..MAX_PENDING_PROXY_CLIENTS { + let mut client = connect_e2e_client(proxy_address)?; + client + .write_all(connect_request.as_bytes()) + .map_err(|error| format!("could not queue E2E client {index}: {error}"))?; + let expected_pending = index + 1; + if !wait_for_proxy_metrics(&guard.shared.metrics, Duration::from_secs(2), |snapshot| { + snapshot.pending_admissions >= expected_pending + }) { + return Err(format!( + "pending admission queue stopped at {} of {MAX_PENDING_PROXY_CLIENTS}", + guard.shared.metrics.snapshot().pending_admissions + )); + } + pending.push(client); + } + + let mut overload = connect_e2e_client(proxy_address)?; + overload + .write_all(connect_request.as_bytes()) + .map_err(|error| format!("could not submit overloaded E2E request: {error}"))?; + let (overload_status, mut response_tail) = read_e2e_response_head(&mut overload)?; + overload + .read_to_end(&mut response_tail) + .map_err(|error| format!("could not read overload response: {error}"))?; + if overload_status != 503 || !String::from_utf8_lossy(&response_tail).contains("Proxy Busy") { + return Err(format!( + "overload response was HTTP {overload_status} without the bounded Proxy Busy response" + )); + } + let full_queue = guard.shared.metrics.snapshot(); + if full_queue.pending_admissions != MAX_PENDING_PROXY_CLIENTS + || full_queue.peak_pending_admissions != MAX_PENDING_PROXY_CLIENTS + || full_queue.overload_rejections == 0 + { + return Err(format!( + "overload metrics mismatch: pending={} peak={} rejected={}", + full_queue.pending_admissions, + full_queue.peak_pending_admissions, + full_queue.overload_rejections + )); + } + + Ok(( + serde_json::json!({ + "requestedTunnels": MAX_ACTIVE_PROXY_CLIENTS, + "activeLimit": MAX_ACTIVE_PROXY_CLIENTS, + "activeAtCapacity": at_capacity.active_tunnels, + "peakActiveTunnels": at_capacity.peak_active_tunnels, + "peakActiveConnections": at_capacity.peak_active_connections, + "pendingLimit": MAX_PENDING_PROXY_CLIENTS, + "pendingHighWater": full_queue.peak_pending_admissions, + "overloadStatus": overload_status, + "overloadRejections": full_queue.overload_rejections, + }), + CapacityClients { active, pending }, + )) +} + +#[cfg(feature = "e2e")] +fn proxy_e2e_credentials(proxy_url: &str) -> Result<(SocketAddr, String), String> { + let url = url::Url::parse(proxy_url) + .map_err(|error| format!("could not inspect E2E proxy URL: {error}"))?; + let host = url.host_str().ok_or("E2E proxy URL has no host")?; + let port = url + .port_or_known_default() + .ok_or("E2E proxy URL has no port")?; + let address = format!("{host}:{port}") + .parse::() + .map_err(|error| format!("E2E proxy bind address is invalid: {error}"))?; + let password = url.password().ok_or("E2E proxy URL has no token")?; + let authorization = super::base64_encode(format!("rosi:{password}").as_bytes()); + Ok((address, authorization)) +} + +#[cfg(feature = "e2e")] +fn connect_e2e_client(address: SocketAddr) -> Result { + let stream = StdTcpStream::connect_timeout(&address, Duration::from_secs(3)) + .map_err(|error| format!("could not connect to E2E proxy: {error}"))?; + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .map_err(|error| format!("could not configure E2E client timeout: {error}"))?; + stream + .set_write_timeout(Some(Duration::from_secs(5))) + .map_err(|error| format!("could not configure E2E client timeout: {error}"))?; + Ok(stream) +} + +#[cfg(feature = "e2e")] +fn read_e2e_response_head(stream: &mut StdTcpStream) -> Result<(u16, Vec), String> { + let mut bytes = Vec::with_capacity(1024); + let mut chunk = [0u8; 1024]; + loop { + if bytes.len() >= 16 * 1024 { + return Err("E2E proxy response header exceeded 16 KiB".into()); + } + let count = stream + .read(&mut chunk) + .map_err(|error| format!("could not read E2E proxy response: {error}"))?; + if count == 0 { + return Err("E2E proxy closed before completing its response header".into()); + } + bytes.extend_from_slice(&chunk[..count]); + if let Some(end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { + let status = std::str::from_utf8(&bytes[..end]) + .ok() + .and_then(|head| head.lines().next()) + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|status| status.parse::().ok()) + .ok_or_else(|| "E2E proxy returned an invalid HTTP status line".to_owned())?; + let split = end + 4; + return Ok((status, bytes[split..].to_vec())); + } + } +} + +#[cfg(feature = "e2e")] +fn wait_for_proxy_metrics( + metrics: &ProxyMetrics, + timeout: Duration, + predicate: impl Fn(ProxyMetricsSnapshot) -> bool, +) -> bool { + let deadline = StdInstant::now() + timeout; + loop { + if predicate(metrics.snapshot()) { + return true; + } + if StdInstant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_millis(2)); + } +} + +#[cfg(feature = "e2e")] +fn e2e_guard_drop_probe() -> Result { + let guard = NetworkSecurityGuard::start()?; + let metrics = Arc::clone(&guard.shared.metrics); + let (address, _) = proxy_e2e_credentials(guard.proxy_url())?; + let mut client = connect_e2e_client(address)?; + if !wait_for_proxy_metrics(&metrics, Duration::from_secs(2), |snapshot| { + snapshot.active_connections == 1 + }) { + return Err("drop E2E client was not admitted".into()); + } + let started = StdInstant::now(); + drop(guard); + let active_after_drop = wait_for_proxy_metrics(&metrics, Duration::from_secs(5), |snapshot| { + snapshot.active_connections == 0 + }); + let _ = client.set_read_timeout(Some(Duration::from_secs(2))); + let mut byte = [0u8; 1]; + let closed_client = socket_closed(client.read(&mut byte)); + if !active_after_drop || !closed_client { + return Err(format!( + "guard drop cleanup failed: active={} clientClosed={closed_client}", + metrics.snapshot().active_connections + )); + } + Ok(serde_json::json!({ + "activeConnectionsAfterDrop": metrics.snapshot().active_connections, + "closedClientSocket": closed_client, + "elapsedMs": started.elapsed().as_millis(), + })) +} + +#[cfg(feature = "e2e")] +fn socket_closed(result: io::Result) -> bool { + match result { + Ok(0) => true, + Ok(_) => false, + Err(error) => !matches!( + error.kind(), + io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted + ), + } +} diff --git a/src-tauri/src/queue.rs b/src-tauri/src/queue.rs index 22526935..9dcd197d 100644 --- a/src-tauri/src/queue.rs +++ b/src-tauri/src/queue.rs @@ -2,61 +2,53 @@ //! that feeds queued items to the downloader one at a time. use crate::constants::MAX_QUEUE_SIZE; -use crate::downloader::{self, CompletionCallback}; -use crate::ipc::{self, IpcResult, NOT_AVAILABLE, VALIDATION_ERROR}; +use crate::coordinator::{self, Command, QueueCommand}; +use crate::downloader; +use crate::ipc::{ + self, DownloadRequestOverrides, FalliblePayload, IpcResult, QueueUrlInput, QueueUrlsInput, + VALIDATION_ERROR, +}; use crate::types::{ - DownloadCompletion, DownloadRequestOptions, Outcome, Owner, PlaylistSelection, QueueItem, - QueueProgress, QueueStatus, Settings, + DownloadCompletion, DownloadRequestOptions, Outcome, Owner, QueueItem, QueueProgress, + QueueStatus, Settings, }; use crate::validation::{ - normalize_queue_url, validate_download_path, validate_download_request, validate_file_location, - validate_queue_item_id, validate_queue_reorder, + normalize_queue_url, validate_file_location, validate_queue_item_id, validate_queue_reorder, }; use serde_json::{Map, Value}; use std::collections::HashSet; use std::path::{Path, PathBuf}; -use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; +use std::sync::{Mutex, MutexGuard, OnceLock}; use std::time::Duration; #[derive(Default)] -struct QueueState { - items: Vec, - revision: u64, - running: bool, - cancelled: bool, - active_item_id: Option, - runner_alive: bool, +pub(crate) struct QueueState { + pub(crate) items: Vec, + pub(crate) revision: u64, + pub(crate) running: bool, + pub(crate) cancelled: bool, + pub(crate) active_item_id: Option, + pub(crate) runner_alive: bool, /// When the current run started. Progress weighting counts only items /// finished during this run, not results kept from earlier runs. - run_started_at: u64, + pub(crate) run_started_at: u64, /// Set while `stop()` waits for the runner to exit, so a start cannot /// replace that runner and leave `stop()` waiting on the new one. - stopping: bool, + pub(crate) stopping: bool, } static QUEUE: OnceLock> = OnceLock::new(); -/// Serialize queue snapshots through their event emission. This is acquired -/// before the queue lock and never while holding queue state. -static QUEUE_PUBLICATION: Mutex<()> = Mutex::new(()); const MAX_QUEUE_FILE_BYTES: usize = 32 * 1024 * 1024; // Reserve space for completion paths, filenames, and error messages. -const MAX_QUEUE_ADMISSION_BYTES: usize = 24 * 1024 * 1024; +pub(crate) const MAX_QUEUE_ADMISSION_BYTES: usize = 24 * 1024 * 1024; const MAX_QUEUE_URL_BYTES: usize = 64 * 1024; -/// Serializes the runner's "is the queue still running? then start" step -/// against cancel/clear/stop, so a cancel can never land between the check and -/// `start_download`. Never acquired while holding the queue lock. -static START_GUARD: Mutex<()> = Mutex::new(()); -static RUNNER_CHANGED: Condvar = Condvar::new(); - struct RunnerFinished; impl Drop for RunnerFinished { fn drop(&mut self) { - state().runner_alive = false; - RUNNER_CHANGED.notify_all(); + coordinator::submit(Command::Queue(QueueCommand::RunnerExited)); } } -static PERSIST_SIGNAL: (Mutex, Condvar) = (Mutex::new(false), Condvar::new()); fn queue_path() -> std::path::PathBuf { crate::app_state::data_dir().join("download-queue.json") @@ -191,15 +183,14 @@ fn persistence() -> &'static QueuePersistence { }) } -fn revisioned_snapshot(increment_revision: bool) -> (u64, Vec) { - let mut queue = state(); +pub(crate) fn revisioned_snapshot(queue: &mut QueueState, increment_revision: bool) -> (u64, Vec) { if increment_revision { queue.revision = queue.revision.saturating_add(1); } (queue.revision, queue.items.clone()) } -fn state() -> MutexGuard<'static, QueueState> { +pub(crate) fn state() -> MutexGuard<'static, QueueState> { QUEUE .get_or_init(|| { Mutex::new(QueueState { @@ -319,42 +310,97 @@ fn load_persisted() -> Vec { Vec::new() } -/// Debounced (300 ms) background persistence. -fn schedule_persist() { - static WORKER: OnceLock<()> = OnceLock::new(); - WORKER.get_or_init(|| { - std::thread::spawn(|| loop { - { - let (lock, signal) = &PERSIST_SIGNAL; - let mut pending = lock.lock().unwrap_or_else(|p| p.into_inner()); - while !*pending { - pending = signal.wait(pending).unwrap_or_else(|p| p.into_inner()); +/// Commands for the single queue writer. `Debounced` asks for a write after +/// the settle window; `Flush` writes now and acknowledges the durable revision. +enum WriteRequest { + Debounced, + Flush(std::sync::mpsc::SyncSender>), +} + +const PERSIST_DEBOUNCE: Duration = Duration::from_millis(300); + +/// The one thread that writes queue files. Writes never overlap: debounced +/// requests are coalesced, and a flush is served from the latest state. +fn writer() -> &'static std::sync::mpsc::Sender { + static WRITER: OnceLock> = OnceLock::new(); + WRITER.get_or_init(|| { + let (sender, receiver) = std::sync::mpsc::channel::(); + std::thread::spawn(move || writer_loop(receiver)); + sender + }) +} + +fn writer_loop(receiver: std::sync::mpsc::Receiver) { + while let Ok(first) = receiver.recv() { + let mut flushes = Vec::new(); + match first { + WriteRequest::Flush(ack) => flushes.push(ack), + WriteRequest::Debounced => { + // A flush arriving inside the window ends it early. + let deadline = std::time::Instant::now() + PERSIST_DEBOUNCE; + loop { + let remaining = deadline.saturating_duration_since(std::time::Instant::now()); + match receiver.recv_timeout(remaining) { + Ok(WriteRequest::Flush(ack)) => { + flushes.push(ack); + break; + } + Ok(WriteRequest::Debounced) => {} + Err(_) => break, + } } } - std::thread::sleep(Duration::from_millis(300)); - { - let (lock, _) = &PERSIST_SIGNAL; - *lock.lock().unwrap_or_else(|p| p.into_inner()) = false; + } + while let Ok(next) = receiver.try_recv() { + if let WriteRequest::Flush(ack) = next { + flushes.push(ack); } - let (revision, snapshot) = revisioned_snapshot(false); + } + if flushes.is_empty() { + let Some((revision, snapshot)) = coordinator::request(|reply| { + Command::Queue(QueueCommand::Snapshot { bump: false, reply }) + }) else { + continue; + }; if let Err(error) = persistence().persist(revision, snapshot) { crate::logging::error(&format!( "Failed to persist queue revision {revision}: {error}" )); } - }); - }); - let (lock, signal) = &PERSIST_SIGNAL; - *lock.lock().unwrap_or_else(|p| p.into_inner()) = true; - signal.notify_one(); + continue; + } + let Some((revision, snapshot)) = coordinator::request(|reply| { + Command::Queue(QueueCommand::Snapshot { bump: true, reply }) + }) else { + for ack in flushes { + let _ = ack.send(Err("Queue coordinator is not running.".into())); + } + continue; + }; + let result = persistence().flush(revision, snapshot).map(|()| revision); + for ack in flushes { + let _ = ack.send(result.clone()); + } + } +} + +/// Debounced (300 ms) background persistence. +pub(crate) fn schedule_persist() { + let _ = writer().send(WriteRequest::Debounced); } /// Durably write the latest queue. A queue file owned by a newer ROSI version /// is never rewritten; it is already the preserved state, so its refusal does /// not block closing, restarting, or installing an update. pub fn flush() -> Result<(), String> { - let (revision, snapshot) = revisioned_snapshot(true); - match persistence().flush(revision, snapshot) { + let (ack, acknowledged) = std::sync::mpsc::sync_channel(1); + let result = match writer().send(WriteRequest::Flush(ack)) { + Ok(()) => acknowledged + .recv() + .unwrap_or_else(|_| Err("Queue writer stopped before saving.".into())), + Err(_) => Err("Queue writer is not running.".into()), + }; + match result { Err(_) if crate::fs_util::is_newer_schema_file(&queue_path(), MAX_QUEUE_FILE_BYTES as u64) => { @@ -363,7 +409,7 @@ pub fn flush() -> Result<(), String> { ); Ok(()) } - result => result, + result => result.map(|_| ()), } } @@ -382,90 +428,12 @@ pub fn init() { drop(state()); } -fn broadcast() { - let publication = QUEUE_PUBLICATION - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let (_, items) = revisioned_snapshot(true); - crate::app_state::emit("queue-update", items); - drop(publication); - schedule_persist(); -} - -fn resolve_output_path(settings: &Settings) -> String { - let configured = settings.download_folder.trim(); - if !configured.is_empty() { - if let Ok(path) = validate_download_path(configured) { - if !path.is_empty() { - return path; - } - } - } - crate::app_state::downloads_dir() - .to_string_lossy() - .into_owned() -} - -fn request_from_settings(url: &str, settings: &Settings) -> DownloadRequestOptions { - DownloadRequestOptions { - url: url.to_string(), - output_path: resolve_output_path(settings), - ffmpeg_path: Some(settings.ffmpeg_path.clone()).filter(|path| !path.is_empty()), - convert_enabled: Some(settings.convert_enabled), - convert_format: Some(settings.convert_format.clone()), - keep_original: Some(settings.keep_original_after_convert), - playlist: Some(PlaylistSelection { - mode: "current".into(), - start: None, - end: None, - }), - profile: Some(settings.download_mode.as_str().to_string()), - best_quality: Some(settings.best_quality), - advanced_options: Some(settings.advanced_options), - audio_only: Some(settings.audio_only), - audio_output_format: Some(settings.audio_format.clone()), - hook_browser: Some(settings.hook_browser), - browser_choice: Some(settings.browser_choice.clone()), - gpu_acceleration: Some(settings.gpu_acceleration), - gpu_type: Some(settings.gpu_type.as_str().to_string()), - write_subtitles: Some(settings.write_subtitles), - subtitle_langs: Some(settings.subtitle_langs.clone()), - embed_thumbnail: Some(settings.embed_thumbnail), - embed_metadata: Some(settings.embed_metadata), - sponsorblock_remove: Some(settings.sponsorblock_remove), - ..DownloadRequestOptions::default() - } -} - fn build_request( url: &str, settings: &Settings, overrides: Option<&Map>, ) -> Result { - let mut candidate = match serde_json::to_value(request_from_settings(url, settings)) { - Ok(Value::Object(map)) => map, - _ => Map::new(), - }; - let preset_id = overrides - .and_then(|map| map.get("presetId")) - .and_then(Value::as_str) - .map(str::trim); - if let Some(preset) = - preset_id.and_then(|id| settings.download_presets.iter().find(|p| p.id == id)) - { - candidate.extend(crate::settings::preset_to_request_options(preset)); - } - if let Some(overrides) = overrides { - for (key, value) in overrides { - if !value.is_null() { - candidate.insert(key.clone(), value.clone()); - } - } - } - candidate.insert("url".into(), Value::String(url.to_string())); - // Always validate: a snapshot that cannot be re-validated later would be - // silently discarded on reload and would never reach the activity log. - validate_download_request(&Value::Object(candidate)) + crate::download_options::resolve_queue_request(settings, url, overrides) } fn resolve_request(item: &QueueItem) -> DownloadRequestOptions { @@ -489,12 +457,12 @@ fn resolve_request(item: &QueueItem) -> DownloadRequestOptions { "Running queued {} from unvalidated settings-derived options.", item.url )); - request_from_settings(&item.url, &settings) + crate::download_options::request_from_settings(&item.url, &settings) } } } -fn clear_attempt(item: &mut QueueItem) { +pub(crate) fn clear_attempt(item: &mut QueueItem) { item.started_at = None; item.completed_at = None; item.filename = None; @@ -534,7 +502,7 @@ fn synthetic_completion( } } -fn apply_completion(item: &mut QueueItem, completion: &DownloadCompletion) { +pub(crate) fn apply_completion(item: &mut QueueItem, completion: &DownloadCompletion) { item.status = match completion.outcome { Outcome::Success => QueueStatus::Completed, Outcome::Failed => QueueStatus::Failed, @@ -552,7 +520,7 @@ fn apply_completion(item: &mut QueueItem, completion: &DownloadCompletion) { /// Apply a completion to the matching item (if still present). Returns true /// when this completion ended the run. -fn apply_completion_in_state( +pub(crate) fn apply_completion_in_state( queue: &mut QueueState, item_id: &str, completion: &DownloadCompletion, @@ -570,7 +538,7 @@ fn apply_completion_in_state( /// the same lock as the completion, so a retry after this point sees the run /// as over and leaves its item pending. The runner thread exits on its own. /// Returns true when this call ended the run. -fn end_run_if_drained(queue: &mut QueueState) -> bool { +pub(crate) fn end_run_if_drained(queue: &mut QueueState) -> bool { let has_work = queue .items .iter() @@ -585,7 +553,7 @@ fn end_run_if_drained(queue: &mut QueueState) -> bool { /// Claim the next pending item for the runner. When nothing can be claimed, /// the runner's run is over, so the state is reset and `None` is returned. -fn claim_next_in_state(queue: &mut QueueState) -> Option { +pub(crate) fn claim_next_in_state(queue: &mut QueueState) -> Option { let next_index = queue .items .iter() @@ -609,87 +577,82 @@ fn claim_next_in_state(queue: &mut QueueState) -> Option { } } -/// Whether `start_queue` should wait for a runner that is still exiting after -/// its run drained. A stop in progress is never waited on: `stop()` waits for -/// the runner to exit too, and a start must not replace that runner first. -fn start_waits_for_exit(queue: &QueueState) -> bool { - queue.runner_alive && !queue.running && !queue.stopping -} - -/// Apply a completion to the matching item (if still present) and record it. +/// Record a session's terminal result for its item. The coordinator applies it +/// and publishes the queue; the activity record follows. fn finish_item(item_id: &str, completion: DownloadCompletion) { - { - let mut queue = state(); - apply_completion_in_state(&mut queue, item_id, &completion); - } + let _ = coordinator::request(|reply| { + Command::Queue(QueueCommand::ItemFinished { + item_id: item_id.to_string(), + completion: Box::new(completion.clone()), + reply, + }) + }); crate::activity::record(&completion); - broadcast(); } -/// Record a cancelled outcome for an item the runner claimed but never -/// started, if the item is still in the queue (a cleared queue records nothing). -fn finish_unstarted_item(item: &QueueItem, request: &DownloadRequestOptions) { - let completion = synthetic_completion(item, request, Outcome::Cancelled, "⏹️ Cancelled."); - { - let mut queue = state(); - if queue.active_item_id.as_deref() == Some(item.id.as_str()) { - queue.active_item_id = None; - } - let Some(entry) = queue - .items - .iter_mut() - .find(|entry| entry.id == item.id && entry.status == QueueStatus::Downloading) - else { - return; - }; - apply_completion(entry, &completion); - end_run_if_drained(&mut queue); +/// Progress for an item the runner is about to start: items finished during +/// this run plus everything still pending or downloading. +pub(crate) fn progress_for(queue: &QueueState, item_id: &str) -> QueueProgress { + let run_started_at = queue.run_started_at; + let finished_this_run = |entry: &&QueueItem| { + matches!( + entry.status, + QueueStatus::Completed | QueueStatus::Failed | QueueStatus::Cancelled + ) && entry + .completed_at + .is_some_and(|completed| completed >= run_started_at) + }; + let completed_items = queue.items.iter().filter(finished_this_run).count(); + let remaining = queue + .items + .iter() + .filter(|entry| { + matches!( + entry.status, + QueueStatus::Pending | QueueStatus::Downloading + ) + }) + .count(); + QueueProgress { + completed_items, + queue_total: completed_items + remaining, + queue_item_id: Some(item_id.to_string()), } - crate::activity::record(&completion); - broadcast(); } -fn run_queue() { +/// Non-terminal URLs, checked before building requests so duplicates are +/// skipped without reading settings. The coordinator checks again at admission. +fn nonterminal_urls() -> HashSet { + state() + .items + .iter() + .filter(|item| matches!(item.status, QueueStatus::Pending | QueueStatus::Downloading)) + .map(|item| item.url.clone()) + .collect() +} + +/// Runner thread for one queue run. It does the settings, request, and +/// download waits; every queue transition is a coordinator request. +pub(crate) fn run_queue() { let _finished = RunnerFinished; loop { - let next = claim_next_in_state(&mut state()); - let Some(item) = next else { - broadcast(); + let Some(Some(item)) = + coordinator::request(|reply| Command::Queue(QueueCommand::ClaimNext { reply })) + else { return; }; - broadcast(); - let request = resolve_request(&item); - let progress = { - let mut queue = state(); - if let Some(current) = queue.items.iter_mut().find(|entry| entry.id == item.id) { - current.request = Some(request.clone()); - } - let run_started_at = queue.run_started_at; - let finished_this_run = |entry: &&QueueItem| { - matches!( - entry.status, - QueueStatus::Completed | QueueStatus::Failed | QueueStatus::Cancelled - ) && entry - .completed_at - .is_some_and(|completed| completed >= run_started_at) - }; - let completed_items = queue.items.iter().filter(finished_this_run).count(); - let remaining = queue - .items - .iter() - .filter(|entry| { - matches!( - entry.status, - QueueStatus::Pending | QueueStatus::Downloading - ) - }) - .count(); - QueueProgress { - completed_items, - queue_total: completed_items + remaining, - queue_item_id: Some(item.id.clone()), - } + let resolved = + crate::download_options::resolve_validated(&crate::settings::load(), request); + let request = resolved.request.clone(); + let Some(progress) = coordinator::request(|reply| { + Command::Queue(QueueCommand::Prepare { + item_id: item.id.clone(), + request: Box::new(request.clone()), + reply, + }) + }) else { + return; }; if crate::app_state::main_window().is_none() { finish_item( @@ -698,64 +661,72 @@ fn run_queue() { ); continue; } - let (sender, receiver) = std::sync::mpsc::channel::<()>(); - let item_id = item.id.clone(); - let completion_sender = sender.clone(); - let mut on_complete: Option = Some(Box::new(move |completion| { - finish_item(&item_id, completion); - let _ = completion_sender.send(()); - })); - drop(sender); + let (completion_sink, completions) = std::sync::mpsc::channel::(); let started = loop { - let attempt = { - let _guard = START_GUARD.lock().unwrap_or_else(|p| p.into_inner()); - let still_wanted = { - let queue = state(); - queue.running - && !queue.cancelled - && queue.items.iter().any(|entry| { - entry.id == item.id && entry.status == QueueStatus::Downloading - }) - }; - if !still_wanted { - None - } else if !downloader::can_start(Owner::Queue) { - // A manual download that was accepted just before the queue - // started still holds the slot. Wait for it instead of - // failing this and every later item. - Some(None) - } else { - let callback = on_complete.take().expect("queue callback is used once"); - Some(Some(downloader::start_download( - request.clone(), - Owner::Queue, - Some(progress.clone()), - callback, - ))) - } - }; - match attempt { - Some(None) => std::thread::sleep(Duration::from_millis(250)), - Some(Some(Err(conflict))) => { - on_complete = Some(conflict.on_complete); - std::thread::sleep(Duration::from_millis(250)); + let wanted = coordinator::request(|reply| { + Command::Queue(QueueCommand::Attempt { + item_id: item.id.clone(), + reply, + }) + }) + .unwrap_or(false); + if !wanted { + break false; + } + if let Some(blocking) = downloader::blocking_session(Owner::Queue) { + // A manual download that was accepted just before the queue + // started still holds the slot. Wait for its finalization ack + // instead of failing this and every later item. + coordinator::await_finalized(Some(blocking)); + continue; + } + match downloader::start_download( + resolved.clone(), + Owner::Queue, + Some(progress.clone()), + completion_sink.clone(), + ) { + Ok(_session_id) => { + // A cancel that landed while the session was starting + // applies to it now, from this thread. + if let Some(Some(notify)) = coordinator::request(|reply| { + Command::Queue(QueueCommand::SessionStarted { reply }) + }) { + downloader::cancel_active_session(notify); + } + break true; } - Some(Some(Ok(session_id))) => break Some(session_id), - None => break None, + Err(conflict) => coordinator::await_finalized(Some(conflict.session_id)), } }; - match started { - // Cancelled or cleared before the download started: the runner - // owns this item, so it records exactly one outcome for it. - None => finish_unstarted_item(&item, &request), - // The callback always runs exactly once per started session. - Some(_session_id) => { - let _ = receiver.recv(); + // Once started, the coordinator holds the only remaining sender, so + // this receive ends when the session's terminal result is delivered. + drop(completion_sink); + if !started { + // Cancelled or cleared before the download started: the runner owns + // this item, so it records exactly one outcome for it. + let completion = + synthetic_completion(&item, &request, Outcome::Cancelled, "⏹️ Cancelled."); + let recorded = coordinator::request(|reply| { + Command::Queue(QueueCommand::ItemUnstarted { + item_id: item.id.clone(), + completion: Box::new(completion.clone()), + reply, + }) + }) + .unwrap_or(false); + if recorded { + crate::activity::record(&completion); } + continue; + } + if let Ok(completion) = completions.recv() { + finish_item(&item.id, completion); } } } + #[cfg(test)] mod persistence_tests { use super::*; @@ -1149,84 +1120,56 @@ pub fn is_running() -> bool { /// The interrupted item goes back to pending, so it runs again on the next /// start instead of looking like the user cancelled it. pub fn stop() { - let _guard = START_GUARD.lock().unwrap_or_else(|p| p.into_inner()); - let interrupted = { - let mut queue = state(); - queue.cancelled = true; - queue.running = false; - queue.stopping = true; - queue.active_item_id.take() - }; - downloader::cancel_active_session(false); - downloader::kill_all_processes(); - // The claimed-but-unstarted item must acquire START_GUARD to finish. - drop(_guard); - let mut queue = state(); - while queue.runner_alive { - queue = RUNNER_CHANGED - .wait(queue) - .unwrap_or_else(|p| p.into_inner()); - } - let requeued = interrupted.is_some_and(|id| { - queue - .items - .iter_mut() - .find(|item| item.id == id && item.status == QueueStatus::Cancelled) - .map(|item| { - clear_attempt(item); - item.status = QueueStatus::Pending; - }) - .is_some() - }); - queue.stopping = false; - drop(queue); - if requeued { - broadcast(); - } + coordinator::stop(); } #[derive(serde::Serialize)] #[cfg_attr(test, derive(ts_rs::TS))] pub struct AddResult { - added: usize, - skipped: usize, + pub(crate) added: usize, + pub(crate) skipped: usize, } #[tauri::command(async)] -pub fn add_to_queue(urls: Value, options: Option) -> IpcResult { - let Some(urls) = urls.as_array() else { - return ipc::err(VALIDATION_ERROR, "URLs must be an array."); +pub fn add_to_queue( + urls: FalliblePayload, + options: Option>, +) -> IpcResult { + let urls = match urls { + FalliblePayload::Typed(urls) => urls.0, + FalliblePayload::Invalid(_) => return ipc::err(VALIDATION_ERROR, "URLs must be an array."), }; + let options = options + .map(FalliblePayload::into_value) + .unwrap_or(Value::Null); let overrides = match &options { - None | Some(Value::Null) => None, - Some(Value::Object(map)) => Some(map), - Some(_) => return ipc::err(VALIDATION_ERROR, "Queue request options must be an object."), + Value::Null => None, + Value::Object(map) => Some(map), + _ => return ipc::err(VALIDATION_ERROR, "Queue request options must be an object."), }; let settings = crate::settings::load(); - let mut queue = state(); - let nonterminal: HashSet = queue - .items - .iter() - .filter(|item| { - item.status == QueueStatus::Pending || item.status == QueueStatus::Downloading - }) - .map(|item| item.url.clone()) - .collect(); + let nonterminal = nonterminal_urls(); let mut batch = HashSet::new(); let mut pending = Vec::new(); let input_count = urls.len(); let mut valid = 0; let mut skipped = 0; for raw in urls { - if raw - .as_str() - .is_some_and(|url| url.len() > MAX_QUEUE_URL_BYTES) - { - return ipc::err(VALIDATION_ERROR, "Queue URLs must not exceed 64 KiB."); - } - let Some(url) = raw.as_str().and_then(normalize_queue_url) else { - skipped += 1; - continue; + let url = match raw { + QueueUrlInput::Text(raw) if raw.len() > MAX_QUEUE_URL_BYTES => { + return ipc::err(VALIDATION_ERROR, "Queue URLs must not exceed 64 KiB."); + } + QueueUrlInput::Text(raw) => match normalize_queue_url(&raw) { + Some(url) => url, + None => { + skipped += 1; + continue; + } + }, + QueueUrlInput::Other(_) => { + skipped += 1; + continue; + } }; valid += 1; if nonterminal.contains(&url) || batch.contains(&url) { @@ -1265,115 +1208,31 @@ pub fn add_to_queue(urls: Value, options: Option) -> IpcResult } return ipc::err(VALIDATION_ERROR, "No valid URLs provided."); } - if queue.items.len() + pending.len() > MAX_QUEUE_SIZE { - return ipc::err( - VALIDATION_ERROR, - format!("Queue limit reached (max {MAX_QUEUE_SIZE} items)."), - ); - } - let added = pending.len(); - if added > 0 { - let candidate: Vec<&QueueItem> = queue.items.iter().chain(pending.iter()).collect(); - match crate::fs_util::encode_list(&candidate) { - Ok(encoded) if encoded.len() <= MAX_QUEUE_ADMISSION_BYTES => {} - Ok(_) => return ipc::err(VALIDATION_ERROR, "Queue storage limit reached. Remove items or shorten URLs before adding this batch."), - Err(_) => return ipc::err(VALIDATION_ERROR, "Could not encode the queue; no items were added."), - } - queue.items.extend(pending); - drop(queue); - broadcast(); - } - ipc::ok(AddResult { added, skipped }) + coordinator::admit_items(pending, skipped) } #[tauri::command(async)] pub fn remove_from_queue(id: Value) -> IpcResult<()> { - let id = match validate_queue_item_id(&id) { - Ok(id) => id, - Err(error) => return ipc::from_error(error), - }; - let mut queue = state(); - let Some(index) = queue.items.iter().position(|item| item.id == id) else { - return ipc::err(NOT_AVAILABLE, "Queue item not found."); - }; - if queue.items[index].status == QueueStatus::Downloading { - return ipc::err( - VALIDATION_ERROR, - "Cannot remove an actively downloading item.", - ); + match validate_queue_item_id(&id) { + Ok(id) => coordinator::remove_item(id), + Err(error) => ipc::from_error(error), } - queue.items.remove(index); - drop(queue); - broadcast(); - ipc::ok(()) } #[tauri::command(async)] pub fn retry_queue_item(id: Value) -> IpcResult<()> { - let id = match validate_queue_item_id(&id) { - Ok(id) => id, - Err(error) => return ipc::from_error(error), - }; - let mut queue = state(); - let Some(item) = queue.items.iter_mut().find(|item| item.id == id) else { - return ipc::err(NOT_AVAILABLE, "Queue item not found."); - }; - if item.status != QueueStatus::Failed && item.status != QueueStatus::Cancelled { - return ipc::err( - VALIDATION_ERROR, - "Only failed or cancelled queue items can be retried.", - ); + match validate_queue_item_id(&id) { + Ok(id) => coordinator::retry_item(id), + Err(error) => ipc::from_error(error), } - clear_attempt(item); - item.status = QueueStatus::Pending; - drop(queue); - broadcast(); - ipc::ok(()) } #[tauri::command(async)] pub fn reorder_queue_item(request: Value) -> IpcResult<()> { - let (id, up) = match validate_queue_reorder(&request) { - Ok(parsed) => parsed, - Err(error) => return ipc::from_error(error), - }; - let mut queue = state(); - let Some(index) = queue.items.iter().position(|item| item.id == id) else { - return ipc::err(NOT_AVAILABLE, "Queue item not found."); - }; - if queue.items[index].status != QueueStatus::Pending { - return ipc::err( - VALIDATION_ERROR, - "Only pending queue items can be reordered.", - ); + match validate_queue_reorder(&request) { + Ok((id, up)) => coordinator::reorder_item(id, up), + Err(error) => ipc::from_error(error), } - let pending: Vec = queue - .items - .iter() - .enumerate() - .filter(|(_, item)| item.status == QueueStatus::Pending) - .map(|(position, _)| position) - .collect(); - let position = pending - .iter() - .position(|candidate| *candidate == index) - .unwrap_or(0); - let destination = if up { - position.checked_sub(1) - } else { - Some(position + 1) - } - .and_then(|slot| pending.get(slot).copied()); - let Some(destination) = destination else { - return ipc::err( - NOT_AVAILABLE, - format!("Queue item cannot move {}.", if up { "up" } else { "down" }), - ); - }; - queue.items.swap(index, destination); - drop(queue); - broadcast(); - ipc::ok(()) } #[tauri::command] @@ -1384,50 +1243,36 @@ pub async fn clear_queue() -> IpcResult<()> { } fn clear_queue_blocking() -> IpcResult<()> { - let _guard = START_GUARD.lock().unwrap_or_else(|p| p.into_inner()); - let was_running = { - let mut queue = state(); - let running = queue.running; - if running { - queue.cancelled = true; - queue.running = false; - queue.active_item_id = None; - } - running + let Some(was_running) = + coordinator::request(|reply| Command::Queue(QueueCommand::ClearBegin { reply })) + else { + return ipc::err(crate::ipc::INTERNAL_ERROR, "Queue coordinator is not running."); }; if was_running { + // Completes the running session synchronously; its result reaches the + // runner, which records the cancelled outcome. downloader::cancel_active_session(true); } - { - let mut queue = state(); - queue.items.clear(); + match coordinator::request(|reply| Command::Queue(QueueCommand::ClearItems { reply })) { + Some(()) => ipc::ok(()), + None => ipc::err(crate::ipc::INTERNAL_ERROR, "Queue coordinator is not running."), } - broadcast(); - ipc::ok(()) } /// Remove every completed, failed or cancelled item. Pending and active items /// stay, so this never interrupts a run. #[tauri::command(async)] pub fn clear_finished_queue() -> IpcResult { - let removed = { - let mut queue = state(); - let before = queue.items.len(); - queue - .items - .retain(|item| matches!(item.status, QueueStatus::Pending | QueueStatus::Downloading)); - before - queue.items.len() - }; - if removed > 0 { - broadcast(); + match coordinator::clear_finished_items() { + Some(removed) => ipc::ok(RemovedCount { removed }), + None => ipc::err(crate::ipc::INTERNAL_ERROR, "Queue coordinator is not running."), } - ipc::ok(RemovedCount { removed }) } #[derive(serde::Serialize)] #[cfg_attr(test, derive(ts_rs::TS))] pub struct RemovedCount { - removed: usize, + pub(crate) removed: usize, } #[tauri::command(async)] @@ -1435,53 +1280,16 @@ pub fn get_queue() -> Vec { state().items.clone() } -/// Longest a start waits for the previous runner to exit after its run drained. -/// The runner exits within a loop turn, so this only bounds a stuck runner. -const RUNNER_EXIT_WAIT: Duration = Duration::from_secs(2); - #[tauri::command(async)] pub fn start_queue() -> IpcResult { - let (mut queue, _) = RUNNER_CHANGED - .wait_timeout_while(state(), RUNNER_EXIT_WAIT, |queue| { - start_waits_for_exit(queue) - }) - .unwrap_or_else(|poisoned| poisoned.into_inner()); - if !queue - .items - .iter() - .any(|item| item.status == QueueStatus::Pending) - { - return ipc::err(NOT_AVAILABLE, "No pending items in queue."); - } - if queue.stopping { - return ipc::err(NOT_AVAILABLE, "Queue is stopping."); - } - if queue.running { - return ipc::err(VALIDATION_ERROR, "Queue is already running."); - } - if queue.runner_alive { - return ipc::err( - NOT_AVAILABLE, - "Queue is still finishing. Try again shortly.", - ); - } - if !downloader::can_start(Owner::Queue) { - return ipc::err(NOT_AVAILABLE, "A manual download is already in progress."); - } - queue.running = true; - queue.cancelled = false; - queue.runner_alive = true; - queue.run_started_at = crate::app_state::now_ms(); - drop(queue); - std::thread::spawn(run_queue); - ipc::ok(Started { started: true }) + coordinator::start() } #[derive(serde::Serialize)] #[cfg_attr(test, derive(ts_rs::TS))] #[cfg_attr(test, ts(rename = "QueueStarted"))] pub struct Started { - started: bool, + pub(crate) started: bool, } #[tauri::command] @@ -1492,58 +1300,57 @@ pub async fn cancel_queue() -> IpcResult<()> { } fn cancel_queue_blocking() -> IpcResult<()> { - let _guard = START_GUARD.lock().unwrap_or_else(|p| p.into_inner()); - let active = { - let mut queue = state(); - queue.cancelled = true; - queue.running = false; - queue.active_item_id.clone() + let Some(active) = + coordinator::request(|reply| Command::Queue(QueueCommand::CancelBegin { reply })) + else { + return ipc::err(crate::ipc::INTERNAL_ERROR, "Queue coordinator is not running."); }; - if active.is_some() { - // Completes the running session synchronously; its callback records - // the item's single cancelled outcome. + if active { + // Completes the running session synchronously; its result reaches the + // runner, which records the item's single cancelled outcome. downloader::cancel_active_session(true); } - // A "downloading" item without a session belongs to the runner, which - // records it once it sees the cancel. Only untouched items are cancelled - // here, so no item is ever recorded twice. - let remaining: Vec = state() - .items + // A pending item belongs to no runner, so the handler records it here. + let Some((_, items)) = + coordinator::request(|reply| Command::Queue(QueueCommand::Snapshot { bump: false, reply })) + else { + return ipc::err(crate::ipc::INTERNAL_ERROR, "Queue coordinator is not running."); + }; + let completions: Vec<(String, DownloadCompletion)> = items .iter() .filter(|item| item.status == QueueStatus::Pending) - .cloned() + .map(|item| { + let request = resolve_request(item); + ( + item.id.clone(), + synthetic_completion(item, &request, Outcome::Cancelled, "⏹️ Cancelled."), + ) + }) .collect(); - let mut completions = Vec::new(); - for item in &remaining { - let request = resolve_request(item); - completions.push(( - item.id.clone(), - synthetic_completion(item, &request, Outcome::Cancelled, "⏹️ Cancelled."), - )); - } + let records: Vec = completions + .iter() + .map(|(_, completion)| completion.clone()) + .collect(); + if coordinator::request(|reply| { + Command::Queue(QueueCommand::CancelApply { + completions, + reply, + }) + }) + .is_none() { - let mut queue = state(); - for (id, completion) in &completions { - if let Some(item) = queue - .items - .iter_mut() - .find(|item| &item.id == id && item.status == QueueStatus::Pending) - { - apply_completion(item, completion); - } - } - queue.active_item_id = None; + return ipc::err(crate::ipc::INTERNAL_ERROR, "Queue coordinator is not running."); } - for (_, completion) in &completions { + for completion in &records { crate::activity::record(completion); } - broadcast(); ipc::ok(()) } #[cfg(test)] mod run_drain_tests { use super::*; + use crate::coordinator::start_waits_for_exit; fn item(id: &str, status: QueueStatus) -> QueueItem { QueueItem { diff --git a/src-tauri/src/types.rs b/src-tauri/src/types.rs index cb4b76b5..dc0e86fc 100644 --- a/src-tauri/src/types.rs +++ b/src-tauri/src/types.rs @@ -372,6 +372,16 @@ pub struct QueueItem { pub error: Option, } +/// Payload of `queue-update`. `revision` increases with every queue change the +/// coordinator publishes, so the renderer can drop an older snapshot. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct QueueSnapshot { + pub revision: u64, + pub items: Vec, +} + #[derive(Clone, Debug, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] #[cfg_attr(test, derive(ts_rs::TS))] @@ -388,6 +398,43 @@ pub struct VideoInfo { pub webpage_url: Option, } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(test, derive(ts_rs::TS))] +pub enum StreamKind { + Audio, + Video, + AudioVideo, +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(test, derive(ts_rs::TS))] +#[cfg_attr(test, ts(optional_fields = nullable))] +pub struct FormatEntry { + pub format_id: String, + pub stream_kind: StreamKind, + #[serde(skip_serializing_if = "Option::is_none")] + pub vcodec: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub acodec: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub resolution: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub fps: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub file_size_bytes: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub estimated_size_bytes: Option, +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct FormatList { + pub formats: Vec, +} + #[derive(Clone, Debug, Default, Serialize, PartialEq)] #[serde(rename_all = "camelCase")] #[cfg_attr(test, derive(ts_rs::TS))] @@ -456,10 +503,15 @@ mod ts_bindings { JobProgressEvent::decl(&cfg), QueueStatus::decl(&cfg), QueueItem::decl(&cfg), + QueueSnapshot::decl(&cfg), VideoInfo::decl(&cfg), + StreamKind::decl(&cfg), + FormatEntry::decl(&cfg), + FormatList::decl(&cfg), DownloadStats::decl(&cfg), GpuDetectionResult::decl(&cfg), crate::ipc::IpcError::decl(&cfg), + crate::ipc::DownloadRequestInput::decl(&cfg), crate::downloader::Started::decl(&cfg), crate::queue::Started::decl(&cfg), crate::queue::AddResult::decl(&cfg), diff --git a/src-tauri/src/validation.rs b/src-tauri/src/validation.rs index ba8007a3..e2a4262b 100644 --- a/src-tauri/src/validation.rs +++ b/src-tauri/src/validation.rs @@ -718,11 +718,11 @@ pub fn validate_download_request(value: &Value) -> Result Some(String::new()), + value => validate_ffmpeg_path_value(value.map(str::trim))?, + }; let convert_format = optional_string(object, "convertFormat")? .map(str::trim) .filter(|value| !value.is_empty()) diff --git a/src/commands.ts b/src/commands.ts index 3b03b541..20807b7b 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -17,7 +17,7 @@ export interface Commands { reset_stats: { args: void; result: Envelope }; get_download_activity: { args: void; result: Envelope }; clear_download_activity: { args: void; result: Envelope }; - get_formats: { args: { url: string }; result: Envelope }; + get_formats: { args: { url: string }; result: Envelope }; cancel_formats: { args: void; result: void }; get_video_info: { args: { url: string; playlistMode: 'current' | 'all' | null }; @@ -25,12 +25,16 @@ export interface Commands { }; cancel_video_info: { args: void; result: void }; download_video: { - args: { options: Partial }; + args: { options: Ipc.DownloadRequestInput }; result: Envelope; }; + resolve_download_options: { + args: { options: Ipc.DownloadRequestInput }; + result: Envelope; + }; cancel_download: { args: void; result: void }; add_to_queue: { - args: { urls: string[]; options: Partial | null }; + args: { urls: string[]; options: Ipc.DownloadRequestInput | null }; result: Envelope; }; remove_from_queue: { args: { id: string }; result: Envelope }; diff --git a/src/css/02-sidebar.css b/src/css/02-sidebar.css index 7ace52a0..089d9826 100644 --- a/src/css/02-sidebar.css +++ b/src/css/02-sidebar.css @@ -559,6 +559,34 @@ border-top: 1px solid var(--border-subtle); } +.settings-save-feedback { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--spacing-sm); + min-height: 1.8rem; + margin-bottom: 0.55rem; + font-size: var(--text-xs); + color: var(--text-muted); +} + +.settings-save-feedback[data-state='error'] { + color: var(--danger); +} + +.settings-save-feedback[data-state='saved'] { + color: var(--success); +} + +.settings-save-feedback[data-state='saving'] { + color: var(--text-secondary); +} + +.setting-explanation { + margin: 0; + line-height: 1.4; +} + .reset-btn { --btn-h: 38px; } diff --git a/src/css/03-main.css b/src/css/03-main.css index 7b7afe41..de434c44 100644 --- a/src/css/03-main.css +++ b/src/css/03-main.css @@ -421,9 +421,23 @@ .download-output-summary { margin: 0.45rem 0 0 0.2rem; font-size: var(--text-sm); + line-height: 1.4; color: var(--text-muted); } +.download-output-summary[data-state='resolved'] { + color: var(--text-secondary); +} + +.download-output-summary[data-state='resolving'] { + color: var(--text-tertiary); +} + +.download-output-summary[data-state='error'], +.download-output-summary[data-state='invalid-url'] { + color: var(--danger); +} + /* ── Saved presets popover ── */ .preset-popover { top: 42px; diff --git a/src/css/08-wizard.css b/src/css/08-wizard.css index 1f32a83c..42a843d6 100644 --- a/src/css/08-wizard.css +++ b/src/css/08-wizard.css @@ -255,6 +255,7 @@ .wizard-nav { display: flex; + flex-wrap: wrap; align-items: center; justify-content: space-between; margin-top: var(--spacing-xl); @@ -262,6 +263,16 @@ border-top: 1px solid var(--border-subtle); } +.wizard-nav-error { + flex-basis: 100%; + margin: 0 0 var(--spacing-sm); +} + +#wizard-folder-error { + margin: 0; + line-height: 1.35; +} + .wizard-dots { display: flex; gap: var(--spacing-xs); diff --git a/src/engine/bind/backend-events.ts b/src/engine/bind/backend-events.ts index 718616cb..94760d23 100644 --- a/src/engine/bind/backend-events.ts +++ b/src/engine/bind/backend-events.ts @@ -1,10 +1,6 @@ // Startup bindings for backend events. import { logError } from '../core'; -import { - handleLegacyManualCompletion, - handleManualDownloadCompletion, - manualDownload, -} from '../manual-download'; +import { handleManualDownloadCompletion, manualDownload } from '../manual-download'; import { showLicenses } from '../overlays'; import { renderPresetOptions } from '../presets'; import { applyJobProgress, downloadState, showProgressBar } from '../progress'; @@ -13,29 +9,21 @@ import { refs } from '../refs'; import { reconcileSettingsInPlace, settingsStore } from '../settings-store'; import { syncDockFromSettings, updateUIFromSettings } from '../settings-view'; import { applyTheme } from '../theme'; -import { appendConsoleOutput, setButtonLoading, toggleSidebar } from '../ui-helpers'; +import { appendConsoleOutput, toggleSidebar } from '../ui-helpers'; import { checkForUpdates } from '../updater-ui'; /** Backend events: progress, completion, queue, activity, and menu actions. */ export function bindBackendEvents() { - const { activityPanel, fetchFormatsBtn, ipcCleanupFunctions, outputEl } = refs; + const { activityPanel, ipcCleanupFunctions, outputEl } = refs; + // Newest queue revision rendered so far. Snapshots older than it are dropped. + let latestQueueRevision = 0; + // Queue snapshots received so far. The startup read carries no revision, so + // it is applied only if no snapshot arrived while it was in flight. + let queueSnapshotsSeen = 0; ipcCleanupFunctions.push( window.api.onProgress((message) => { if (!outputEl) return; appendConsoleOutput(outputEl, message); - - if ( - !manualDownload.manualDownloadStartPending && - manualDownload.manualSessionIdentityReceived && - manualDownload.manualDownloadSessionId === null && - downloadState.isDownloading && - (message.includes('Identified file:') || message.includes('Successfully converted to')) - ) { - const fileMatch = message.match(/(?:Identified file:|Successfully converted to)\s*(.+)$/); - if (fileMatch && fileMatch[1]) { - downloadState.lastDownloadedFilePath = fileMatch[1].trim(); - } - } }) ); @@ -94,9 +82,7 @@ export function bindBackendEvents() { ipcCleanupFunctions.push( window.api.onComplete((statusMessage) => { - if (fetchFormatsBtn) setButtonLoading(fetchFormatsBtn, false); if (outputEl) appendConsoleOutput(outputEl, statusMessage); - handleLegacyManualCompletion(statusMessage); }) ); @@ -115,8 +101,15 @@ export function bindBackendEvents() { } ipcCleanupFunctions.push( - window.api.onQueueUpdate((queue) => { - renderQueue(queue); + window.api.onQueueUpdate((payload) => { + // Older payloads are bare arrays without a revision; they are always applied. + const snapshot = Array.isArray(payload) ? { revision: null, items: payload } : payload; + if (snapshot.revision !== null) { + if (snapshot.revision < latestQueueRevision) return; + latestQueueRevision = snapshot.revision; + } + queueSnapshotsSeen += 1; + renderQueue(snapshot.items); }) ); @@ -144,8 +137,11 @@ export function bindBackendEvents() { }) ); + const snapshotsBeforeRead = queueSnapshotsSeen; window.api .getQueue() - .then((queue) => renderQueue(queue)) + .then((queue) => { + if (queueSnapshotsSeen === snapshotsBeforeRead) renderQueue(queue); + }) .catch(() => {}); } diff --git a/src/engine/bind/settings-controls.ts b/src/engine/bind/settings-controls.ts index 23659605..6f84aa09 100644 --- a/src/engine/bind/settings-controls.ts +++ b/src/engine/bind/settings-controls.ts @@ -1,6 +1,17 @@ // Startup bindings for settings controls. -import { RosiSettings, isValidSubtitleLangs } from '../core'; +import { RosiSettings, isValidSubtitleLangs, isValidUrl } from '../core'; +import { + configureEffectiveOptionsRequestBuilder, + refreshEffectiveOptionsSummary, +} from '../messages'; +import type { EffectiveOptionsReadiness } from '../messages'; import { showModal } from '../overlays'; +import { isPlaylistScopeVisible, resolvePlaylistSelection } from '../playlist'; +import { + buildOnScreenPresetOverrides, + getSelectedPreset, + readAdvancedFormatSelections, +} from '../presets'; import { formatBytes, formatRelativeTime } from '../progress'; import { refs } from '../refs'; import { flushBeforeRestart, persistSettings, settingsStore } from '../settings-store'; @@ -8,6 +19,95 @@ import { applyDownloadProfile, bindExternalLink, updateUIFromSettings } from '.. import { applyTheme, updateBackgroundAnimation } from '../theme'; import { showToast, updateConsoleVisibility } from '../ui-helpers'; +function buildEffectiveOptionsReadiness(): EffectiveOptionsReadiness { + const url = refs.urlInput?.value.trim() ?? ''; + const profile = settingsStore.settings?.downloadMode ?? 'compatible'; + if (!url) { + return { state: 'profile-preview', profile, audioFormat: settingsStore.settings?.audioFormat }; + } + if (!isValidUrl(url)) return { state: 'invalid-url' }; + + const settings = settingsStore.settings; + if ( + settingsStore.persistDebounceTimer || + settingsStore.settingsSaveInFlight || + settingsStore.settingsSaveWaiters.length > 0 + ) { + return { state: 'settings-saving' }; + } + if (settingsStore.settingsSavedRevision !== settingsStore.settingsRevision) { + return { state: 'settings-unsaved' }; + } + const outputPath = settings.askDownloadLocation ? '' : (settings.downloadFolder?.trim() ?? ''); + if (!outputPath) return { state: 'destination' }; + + const formatSelections = readAdvancedFormatSelections(url); + if (settings.advancedOptions && !formatSelections.videoFormat && !formatSelections.audioFormat) { + return { state: 'formats' }; + } + + const playlist = resolvePlaylistSelection(); + const playlistVisible = isPlaylistScopeVisible(); + if (playlistVisible && !playlist) return { state: 'playlist' }; + + const selectedPreset = getSelectedPreset(); + const convertEnabled = settings.convertEnabled && !settings.audioOnly; + const request = { + url, + outputPath, + videoFormat: formatSelections.videoFormat, + audioFormat: formatSelections.audioFormat, + convertFormat: convertEnabled ? refs.convertFormatSelect?.value.trim() || undefined : undefined, + keepOriginal: convertEnabled ? refs.keepOriginalToggle?.checked : undefined, + ...(playlistVisible && playlist ? { playlist } : {}), + ...(selectedPreset + ? { + presetId: selectedPreset.id, + presetName: selectedPreset.name, + ...buildOnScreenPresetOverrides(formatSelections), + } + : {}), + }; + return { state: 'ready', request }; +} + +function bindEffectiveOptionsSummary() { + configureEffectiveOptionsRequestBuilder(buildEffectiveOptionsReadiness); + const watchedElements = [ + refs.urlInput, + refs.profileAudioFormatSelect, + refs.downloadPresetSelect, + refs.convertToggle, + refs.convertFormatSelect, + refs.keepOriginalToggle, + refs.gpuAccelerationToggle, + refs.gpuTypeSelect, + refs.writeSubtitlesToggle, + refs.subtitleLangsInput, + refs.embedMetadataToggle, + refs.embedThumbnailToggle, + refs.sponsorblockToggle, + refs.askDownloadLocationToggle, + refs.playlistRangeStart, + refs.playlistRangeEnd, + ].filter((element): element is NonNullable => element !== null); + watchedElements.forEach((element) => { + if (element === refs.urlInput) { + element.addEventListener('input', () => refreshEffectiveOptionsSummary()); + } + element.addEventListener('change', () => refreshEffectiveOptionsSummary()); + }); + document + .getElementById('downloadProfilesComposer') + ?.addEventListener('click', () => refreshEffectiveOptionsSummary()); + document + .getElementById('playlistScope') + ?.addEventListener('change', () => refreshEffectiveOptionsSummary()); + document + .getElementById('changeDownloadFolderBtn') + ?.addEventListener('click', () => window.setTimeout(refreshEffectiveOptionsSummary, 0)); +} + /** Windows-only browser cookie choices. */ export function bindWindowsBrowserChoice() { const { browserChoiceSelect } = refs; @@ -30,6 +130,7 @@ export function bindWindowsBrowserChoice() { /** Settings toggles, selects, and inputs that save on change. */ export function bindSettingsControls() { + bindEffectiveOptionsSummary(); const { animateBackgroundToggle, askDownloadLocationToggle, @@ -317,6 +418,10 @@ export function bindSettingsControls() { /** Update channel, reset, export, import, and statistics. */ export function bindSettingsActions() { + const retrySettingsSave = document.getElementById('retrySettingsSave'); + retrySettingsSave?.addEventListener('click', () => { + void persistSettings(false, true); + }); const { exportSettingsBtn, importSettingsBtn, diff --git a/src/engine/bind/settings-sections.ts b/src/engine/bind/settings-sections.ts index e510b205..6f85051e 100644 --- a/src/engine/bind/settings-sections.ts +++ b/src/engine/bind/settings-sections.ts @@ -1,5 +1,7 @@ // Startup bindings for settings search, reset, and collapsible sections. import { RosiSettings } from '../core'; +import { UI_MESSAGES } from '../messages'; +import { showModal } from '../overlays'; import { byId, refs } from '../refs'; import { loadDefaultSettings, persistSettings, settingsStore } from '../settings-store'; import { @@ -81,26 +83,49 @@ export function initSettingsSearch() { const sectionName = button.dataset.resetSection ?? ''; const keys = SECTION_RESET_KEYS[sectionName]; if (!keys) return; - const defaults = await loadDefaultSettings(); - if (!defaults) { - showToast('Could not load default settings.', { type: 'error' }); - return; - } - const settingsRecord = settingsStore.settings as unknown as Record; - const defaultsRecord = defaults as unknown as Record; - keys.forEach((key) => { - settingsRecord[key] = defaultsRecord[key]; - }); - updateUIFromSettings(); - applyTheme(settingsStore.settings.theme ?? 'system'); - const saved = await persistSettings(true, true); - showToast(saved ? 'Section restored to defaults.' : 'Could not save the restored section.', { - type: saved ? 'success' : 'error', + const sectionLabel = + button.closest('.settings-section')?.querySelector('.settings-section-title') + ?.textContent ?? sectionName; + // Only the confirm action resets. Cancel, Escape and the close control leave + // every value untouched and return focus to this button. Focus it first so + // the return target is this button however the prompt was opened: a script + // or pointer click may not focus it (Safari does not focus buttons on click). + button.focus(); + showModal({ + title: UI_MESSAGES.settings.resetTitle(sectionLabel), + message: UI_MESSAGES.settings.resetMessage(sectionLabel), + buttons: [ + { label: UI_MESSAGES.settings.resetCancel }, + { + label: UI_MESSAGES.settings.resetConfirm, + danger: true, + action: () => void applySectionReset(keys), + }, + ], }); }); }); } +async function applySectionReset(keys: string[]) { + const defaults = await loadDefaultSettings(); + if (!defaults) { + showToast(UI_MESSAGES.settings.defaultsFailed, { type: 'error' }); + return; + } + const settingsRecord = settingsStore.settings as unknown as Record; + const defaultsRecord = defaults as unknown as Record; + keys.forEach((key) => { + settingsRecord[key] = defaultsRecord[key]; + }); + updateUIFromSettings(); + applyTheme(settingsStore.settings.theme ?? 'system'); + const saved = await persistSettings(true, true); + showToast(saved ? UI_MESSAGES.settings.resetSaved : UI_MESSAGES.settings.resetFailed, { + type: saved ? 'success' : 'error', + }); +} + /** Collapsible settings sections. */ export function initSettingsSections() { const settingsHeaders = Array.from( diff --git a/src/engine/deno.ts b/src/engine/deno.ts index 4e529080..fe98ca56 100644 --- a/src/engine/deno.ts +++ b/src/engine/deno.ts @@ -1,5 +1,6 @@ // Deno detection, reminder, and install flow. import { RosiSettings, logError } from './core'; +import { UI_MESSAGES } from './messages'; import { showModal } from './overlays'; import { showRestartFailure } from './updater-ui'; @@ -37,7 +38,7 @@ export async function checkDenoInstallation( primary: true, action: () => window.api.openExternal(DENO_INSTALL_DOCS), }, - { label: 'Later' }, + { label: UI_MESSAGES.wizard.later }, { label: "No, don't remind me", action: () => { @@ -138,5 +139,17 @@ export async function checkDenoInstallation( } } catch (error) { logError('Error checking Deno installation', error); + showModal({ + title: UI_MESSAGES.wizard.denoCheckUnavailableTitle, + message: UI_MESSAGES.wizard.denoCheckFailed, + buttons: [ + { + label: UI_MESSAGES.wizard.installInstructions, + primary: true, + action: () => window.api.openExternal(DENO_INSTALL_DOCS), + }, + { label: 'Later' }, + ], + }); } } diff --git a/src/engine/formats.ts b/src/engine/formats.ts index ac20ad6d..99312091 100644 --- a/src/engine/formats.ts +++ b/src/engine/formats.ts @@ -9,11 +9,37 @@ export let fetchFormatsAbort: (() => void) | null = null; export let formatRequestGeneration = 0; export let formatRequestUrl: string | null = null; +function setSelectMessage(select: HTMLSelectElement | null, message: string) { + if (!select) return; + const option = document.createElement('option'); + option.value = ''; + option.textContent = message; + select.replaceChildren(option); +} + +function setPickerMessage(message: string) { + setSelectMessage(document.getElementById('videoFormat') as HTMLSelectElement | null, message); + setSelectMessage(document.getElementById('audioFormat') as HTMLSelectElement | null, message); +} + +function appendFormatOption(select: HTMLSelectElement | null, format: RosiFormatEntry) { + if (!select) return; + const option = document.createElement('option'); + option.value = format.formatId; + option.textContent = + window.rosiModules?.downloads?.formatFormatEntry(format) ?? `ID: ${format.formatId}`; + select.appendChild(option); +} + export function clearAdvancedFormatSelections() { - const videoSelect = document.getElementById('videoFormat') as HTMLSelectElement | null; - const audioSelect = document.getElementById('audioFormat') as HTMLSelectElement | null; - if (videoSelect) videoSelect.innerHTML = ''; - if (audioSelect) audioSelect.innerHTML = ''; + setSelectMessage( + document.getElementById('videoFormat') as HTMLSelectElement | null, + 'Select Video Format' + ); + setSelectMessage( + document.getElementById('audioFormat') as HTMLSelectElement | null, + 'Select Audio Format' + ); formatState.formatSelectionsUrl = null; } @@ -31,6 +57,8 @@ export function invalidateFormatRequest() { export async function fetchFormats() { const btn = document.getElementById('fetchFormatsBtn') as HTMLButtonElement | null; const urlInput = document.getElementById('url') as HTMLInputElement | null; + const videoSelect = document.getElementById('videoFormat') as HTMLSelectElement | null; + const audioSelect = document.getElementById('audioFormat') as HTMLSelectElement | null; const videoUrl = urlInput?.value.trim() || null; try { @@ -43,8 +71,9 @@ export async function fetchFormats() { return; } - // Validate URL format if (!isValidUrl(videoUrl)) { + clearAdvancedFormatSelections(); + setPickerMessage('Invalid URL'); showModal({ title: 'Invalid URL', message: 'Please enter a valid URL starting with http:// or https://', @@ -69,35 +98,32 @@ export async function fetchFormats() { formatState.formatSelectionsUrl = null; isFetchingFormats = false; fetchFormatsAbort = null; - clearAdvancedFormatSelections(); + setPickerMessage('Format check cancelled'); setButtonLoading(btn, false); }; setButtonLoading( btn, true, () => { - if (window.api.cancelFormats) { - window.api.cancelFormats(); - } + window.api.cancelFormats(); fetchFormatsAbort?.(); }, 'Cancel format check' ); - const videoSelect = document.getElementById('videoFormat') as HTMLSelectElement | null; - const audioSelect = document.getElementById('audioFormat') as HTMLSelectElement | null; - if (videoSelect) videoSelect.innerHTML = ''; - if (audioSelect) audioSelect.innerHTML = ''; + setSelectMessage(videoSelect, 'Loading...'); + setSelectMessage(audioSelect, 'Loading...'); + try { const formatResult = await window.api.getFormats(videoUrl); if (wasCancelled || !isCurrentRequest()) return; if (!formatResult || formatResult.ok !== true) { + if (formatResult?.error?.code === 'NOT_AVAILABLE') { + formatState.formatSelectionsUrl = null; + setPickerMessage('Format check cancelled'); + return; + } const errorMessage = formatResult?.error?.message || 'Unknown error'; - const cancelled = - wasCancelled || - (typeof errorMessage === 'string' && errorMessage.toLowerCase().includes('cancel')); - if (cancelled) return; - if (videoSelect) videoSelect.innerHTML = ''; - if (audioSelect) audioSelect.innerHTML = ''; + setPickerMessage('Error loading formats'); showModal({ title: 'Format Fetch Failed', message: `Could not retrieve formats.\nError: ${errorMessage}`, @@ -106,58 +132,21 @@ export async function fetchFormats() { return; } - const lines = formatResult.data.split('\n'); - if (videoSelect) videoSelect.innerHTML = ''; - if (audioSelect) audioSelect.innerHTML = ''; - let videoFormatsFound = 0, - audioFormatsFound = 0; - const FORMAT_ID = /^([A-Za-z0-9][A-Za-z0-9._-]{0,63})\s+\S/; - lines.forEach((line) => { - const trimmed = line.trim(); - const idMatch = trimmed.match(FORMAT_ID); - if (!idMatch) return; - const formatId = idMatch[1]; - if (!formatId || formatId.toLowerCase() === 'id') return; - if (/storyboard|images? only|mhtml/i.test(line)) return; - const option = document.createElement('option'); - option.value = formatId; - const labelText = trimmed; - const resolutionMatch = labelText.match(/(\d{3,4}x\d{3,4}|\d{3,4}p)/); - const fpsMatch = labelText.match(/@?\s*(\d+)\s*fps/i); - const sizeMatch = labelText.match(/(\d+(\.\d+)?(MiB|GiB|KiB))/); - const codecMatch = line.match( - /(avc1|vp9|vp09|av01|h264|h265|hevc|opus|mp4a|aac|vorbis|flac)/i - ); - let cleanLabel = `ID: ${formatId}`; - if (resolutionMatch) cleanLabel += ` ${resolutionMatch[0]}`; - if (fpsMatch) cleanLabel += ` ${fpsMatch[1]}fps`; - if (codecMatch) cleanLabel += ` (${codecMatch[0]})`; - if (sizeMatch) cleanLabel += ` ~${sizeMatch[0]}`; - option.text = cleanLabel; - option.title = trimmed; - const isVideoOnly = /video only/i.test(line); - const isAudioOnly = /audio only/i.test(line); - if (isAudioOnly) { - if (audioSelect) audioSelect.appendChild(option); - audioFormatsFound++; - } else { - // Video-only streams and combined video+audio formats. Combined - // formats (common on sites with a single file) carry no marker. - if (!isVideoOnly) option.text += ' (video + audio)'; - if (videoSelect) videoSelect.appendChild(option); - videoFormatsFound++; - } - }); - if (videoFormatsFound === 0 && videoSelect) - videoSelect.innerHTML = ''; - if (audioFormatsFound === 0 && audioSelect) - audioSelect.innerHTML = ''; - formatState.formatSelectionsUrl = videoUrl; + const formats = formatResult.data.formats; + if (!Array.isArray(formats)) throw new Error('Format metadata did not contain a list.'); + const videoFormats = formats.filter((format) => format.streamKind !== 'audio'); + const audioFormats = formats.filter((format) => format.streamKind === 'audio'); + setSelectMessage(videoSelect, 'Select Video Format'); + setSelectMessage(audioSelect, 'Select Audio Format'); + videoFormats.forEach((format) => appendFormatOption(videoSelect, format)); + audioFormats.forEach((format) => appendFormatOption(audioSelect, format)); + if (videoFormats.length === 0) setSelectMessage(videoSelect, 'No video formats found'); + if (audioFormats.length === 0) setSelectMessage(audioSelect, 'No audio formats found'); + formatState.formatSelectionsUrl = formats.length > 0 ? videoUrl : null; } catch (e) { if (!isCurrentRequest()) return; const errorMessage = typeof e === 'string' ? e : (e as Error)?.message || 'Unknown error'; - if (videoSelect) videoSelect.innerHTML = ''; - if (audioSelect) audioSelect.innerHTML = ''; + setPickerMessage('Error loading formats'); showModal({ title: 'Format Fetch Failed', message: `Could not retrieve formats.\nError: ${errorMessage}`, @@ -175,6 +164,7 @@ export async function fetchFormats() { logError('Unexpected error in fetchFormats', outerError); isFetchingFormats = false; if (btn) setButtonLoading(btn, false); + setPickerMessage('Error loading formats'); showModal({ title: 'Unexpected Error', message: 'An unexpected error occurred while fetching formats. Please try again.', diff --git a/src/engine/manual-download.ts b/src/engine/manual-download.ts index 74fdd4d3..3b955879 100644 --- a/src/engine/manual-download.ts +++ b/src/engine/manual-download.ts @@ -168,29 +168,6 @@ export function handleManualDownloadCompletion(completion: RosiDownloadCompletio showManualDownloadCompletion(completion, manualDownload.manualDownloadOperation); } -export function handleLegacyManualCompletion(statusMessage: string) { - if ( - manualDownload.manualDownloadStartPending || - !manualDownload.manualSessionIdentityReceived || - manualDownload.manualDownloadSessionId !== null || - !downloadState.isDownloading - ) { - return; - } - const normalizedStatus = String(statusMessage || '').toLowerCase(); - const isCancelled = normalizedStatus.includes('cancel'); - const isSuccess = - !isCancelled && (statusMessage.includes('✅') || normalizedStatus.includes('complete')); - showManualDownloadCompletion( - { - outcome: isSuccess ? 'success' : isCancelled ? 'cancelled' : 'failed', - statusMessage, - outputPath: isSuccess ? (downloadState.lastDownloadedFilePath ?? undefined) : undefined, - }, - manualDownload.manualDownloadOperation - ); -} - // Owned by the renderer controller; set during startup and updated while it runs. export const manualDownload: { manualDownloadOperation: number; diff --git a/src/engine/messages.ts b/src/engine/messages.ts new file mode 100644 index 00000000..46cff443 --- /dev/null +++ b/src/engine/messages.ts @@ -0,0 +1,238 @@ +import type { DownloadProfile, DownloadRequestOptions } from '../generated/ipc-types'; + +export const UI_MESSAGES = { + options: { + profilePreview: (description: string) => + `${description}. Enter a valid URL and choose a save location to check effective options.`, + // What each profile produces, shown before a URL exists to resolve it. + profileDescriptions: { + compatible: + 'Prefer MP4 when available; otherwise use the best available format. Often low resolution', + 'best-video': 'Highest available video and audio quality, merged into one file', + audio: (audioFormat: string) => `Audio only, saved as ${audioFormat.toUpperCase()}`, + custom: 'Pick exact video and audio formats below', + } satisfies Record< + DownloadRequestOptions['profile'] & string, + string | ((format: string) => string) + >, + invalidUrl: 'Enter a valid http or https URL to check effective options.', + destination: 'Choose a save location before effective options can be checked.', + formats: 'Select a video or audio format before checking custom options.', + playlist: 'Fix the playlist selection before checking effective options.', + resolving: 'Checking effective options…', + settingsSaving: 'Saving settings before checking effective options…', + settingsUnsaved: + 'Settings are not saved. Retry the settings save before trusting the effective options preview.', + unavailable: + 'Effective options are unavailable. ROSI will validate them when the download starts.', + failed: (reason: string) => `Could not check effective options. ${reason}`, + result: (details: string) => `Effective options: ${details}`, + profiles: { + compatible: 'Compatible', + 'best-video': 'Best video', + audio: 'Audio only', + custom: 'Custom formats', + } satisfies Record, + }, + settings: { + saving: 'Saving settings…', + saved: 'Settings saved.', + saveFailed: 'Settings did not save. Your choices are still here; retry the save.', + conflict: 'Settings changed outside ROSI. Close ROSI and resolve that file before retrying.', + retry: 'Retry save', + resetTitle: (section: string) => `Reset ${section.toLowerCase()} settings?`, + resetMessage: (section: string) => + `${section} settings will return to their defaults. You can cancel without changing them.`, + resetConfirm: 'Reset section', + resetCancel: 'Cancel', + defaultsFailed: 'Could not load default settings. Nothing was reset.', + resetSaved: 'Section restored to defaults.', + resetFailed: 'Could not save the restored settings. Retry the save from Settings.', + }, + controls: { + convertAudioOnly: 'Conversion is unavailable while the Audio only profile is selected.', + }, + queue: { + pending: 'Waiting for the queue to start.', + downloading: 'This download is in progress.', + completed: 'This download completed.', + failed: 'This download failed. Review its details before retrying.', + cancelled: 'This download was cancelled. Requeue it to try again.', + first: 'This is the first pending item in the queue.', + last: 'This is the last pending item in the queue.', + }, + activity: { + completed: 'Completed', + partial: 'Partially completed', + failed: 'Failed', + cancelled: 'Cancelled', + partialCount: (successes: number, total: number) => + `${successes} of ${total} entries completed`, + filesSaved: (count: number) => `${count} files saved`, + }, + wizard: { + folderCancelled: 'No folder was chosen. Choose a folder or ask ROSI before each download.', + folderFailed: 'ROSI could not open the folder picker. Try again or ask before each download.', + saveFailed: 'ROSI could not save setup. Your choices are still here; try Finish or Skip again.', + defaultsFailed: 'ROSI could not load default settings, so setup was not skipped. Try again.', + denoMissing: "Deno isn't installed. Some YouTube videos may not download until it is.", + denoChecking: 'Checking for Deno…', + denoInstalling: 'Installing Deno. This may take a moment…', + denoInstalled: 'Deno is installed. YouTube downloads are fully supported.', + denoInstalledRestart: 'Deno is installed. Restart ROSI after setup to use it.', + denoCheckFailed: "Couldn't check for Deno. Open the official install instructions for help.", + denoInstallFailed: (reason: string) => `Automatic install failed: ${reason}`, + flatpakRuntime: + 'This Flatpak build includes its own JavaScript runtime. YouTube downloads are fully supported.', + installInstructions: 'Open install instructions', + installDeno: 'Install Deno', + denoCheckUnavailableTitle: 'Deno check unavailable', + later: 'Later', + }, +} as const; + +export type EffectiveOptionsReadiness = + | { state: 'profile-preview'; profile: DownloadProfile; audioFormat?: string } + | { state: 'invalid-url' } + | { state: 'destination' } + | { state: 'formats' } + | { state: 'playlist' } + | { state: 'settings-saving' } + | { state: 'settings-unsaved' } + | { state: 'ready'; request: Partial }; + +type EffectiveOptionsRequestBuilder = () => EffectiveOptionsReadiness; + +let requestBuilder: EffectiveOptionsRequestBuilder = () => ({ + state: 'profile-preview', + profile: 'compatible', +}); +let requestGeneration = 0; +let requestTimer: ReturnType | null = null; +let lastRequestKey: string | null = null; + +function describeProfileOutput(profile: DownloadProfile, audioFormat?: string) { + const description = UI_MESSAGES.options.profileDescriptions[profile]; + return typeof description === 'function' ? description(audioFormat || 'mp3') : description; +} + +function setSummaryState(summary: HTMLElement, state: string, text: string, busy = false) { + summary.dataset.state = state; + summary.textContent = text; + summary.setAttribute('aria-busy', String(busy)); +} + +function formatResolvedOptions(options: DownloadRequestOptions) { + const profile = options.profile ?? (options.audioOnly ? 'audio' : 'compatible'); + const details = [UI_MESSAGES.options.profiles[profile]]; + if (options.presetName) details.push(`Preset: ${options.presetName}`); + if (options.videoFormat) details.push(`Video ${options.videoFormat}`); + if (options.audioFormat) details.push(`Audio ${options.audioFormat}`); + if (options.audioOutputFormat) details.push(options.audioOutputFormat.toUpperCase()); + if (options.convertEnabled && options.convertFormat) { + details.push(`Convert to ${options.convertFormat.toUpperCase()}`); + } + if (options.writeSubtitles) details.push('Subtitles'); + if (options.embedMetadata) details.push('Metadata'); + if (options.embedThumbnail) details.push('Thumbnail'); + if (options.sponsorblockRemove) details.push('SponsorBlock'); + if (options.playlist && options.playlist.mode !== 'current') { + details.push( + options.playlist.mode === 'all' + ? 'Entire playlist' + : `Playlist entries ${options.playlist.start ?? 1}–${options.playlist.end ?? 'last'}` + ); + } + return { profile, text: UI_MESSAGES.options.result(details.join(' · ')) }; +} + +export function configureEffectiveOptionsRequestBuilder(builder: EffectiveOptionsRequestBuilder) { + requestBuilder = builder; + lastRequestKey = null; + refreshEffectiveOptionsSummary(); +} + +export function refreshEffectiveOptionsSummary(force = false) { + const summary = document.getElementById('downloadOutputSummary'); + if (!(summary instanceof HTMLElement)) return; + + const readiness = requestBuilder(); + const key = JSON.stringify(readiness); + if (!force && key === lastRequestKey) return; + lastRequestKey = key; + requestGeneration += 1; + const generation = requestGeneration; + if (requestTimer) clearTimeout(requestTimer); + requestTimer = null; + delete summary.dataset.profile; + + if (readiness.state !== 'ready') { + const messages: Record< + Exclude, + string + > = { + 'invalid-url': UI_MESSAGES.options.invalidUrl, + destination: UI_MESSAGES.options.destination, + formats: UI_MESSAGES.options.formats, + playlist: UI_MESSAGES.options.playlist, + 'settings-saving': UI_MESSAGES.options.settingsSaving, + 'settings-unsaved': UI_MESSAGES.options.settingsUnsaved, + }; + const text = + readiness.state === 'profile-preview' + ? UI_MESSAGES.options.profilePreview( + describeProfileOutput(readiness.profile, readiness.audioFormat) + ) + : messages[readiness.state]; + setSummaryState(summary, readiness.state, text); + return; + } + + setSummaryState(summary, 'resolving', UI_MESSAGES.options.resolving, true); + requestTimer = setTimeout(() => { + requestTimer = null; + if (JSON.stringify(requestBuilder()) !== key) { + lastRequestKey = null; + refreshEffectiveOptionsSummary(); + return; + } + const resolve = window.api.resolveDownloadOptions; + if (typeof resolve !== 'function') { + if (generation === requestGeneration) { + setSummaryState(summary, 'unavailable', UI_MESSAGES.options.unavailable); + } + return; + } + void resolve(readiness.request).then( + (result) => { + if (generation !== requestGeneration || !summary.isConnected) return; + if (!result || result.ok !== true) { + setSummaryState( + summary, + 'error', + UI_MESSAGES.options.failed(result?.error?.message ?? 'Try again before downloading.') + ); + return; + } + const resolved = formatResolvedOptions(result.data); + summary.dataset.profile = resolved.profile; + setSummaryState(summary, 'resolved', resolved.text); + }, + (error: unknown) => { + if (generation !== requestGeneration || !summary.isConnected) return; + const reason = error instanceof Error ? error.message : 'Try again before downloading.'; + setSummaryState(summary, 'error', UI_MESSAGES.options.failed(reason)); + } + ); + }, 180); +} + +// Modules are import-free IIFEs, so they read the same strings through this handle. +declare global { + interface Window { + rosiMessages?: typeof UI_MESSAGES; + } +} +if (typeof window !== 'undefined') { + window.rosiMessages = UI_MESSAGES; +} diff --git a/src/engine/overlays.ts b/src/engine/overlays.ts index d4e7334d..6a7d9fa8 100644 --- a/src/engine/overlays.ts +++ b/src/engine/overlays.ts @@ -42,6 +42,12 @@ export function focusTopOverlayOr(target: Element | null) { const topOverlayId = getTopActiveOverlayId(); if (topOverlayId) { const overlay = document.getElementById(topOverlayId); + // The control that opened the prompt may live inside the overlay underneath + // it (the reset buttons sit in the open settings sidebar). Return there first. + if (target instanceof HTMLElement && overlay?.contains(target)) { + target.focus(); + if (document.activeElement === target) return; + } if (focusFirstElement(overlay)) return; if (overlay instanceof HTMLElement) overlay.focus(); return; diff --git a/src/engine/settings-store.ts b/src/engine/settings-store.ts index 252347af..f4355117 100644 --- a/src/engine/settings-store.ts +++ b/src/engine/settings-store.ts @@ -1,12 +1,14 @@ // Settings state, change tracking, and serialized saves to the backend. import { RosiDownloadPreset, RosiSettings, logError } from './core'; +import { refreshEffectiveOptionsSummary, UI_MESSAGES } from './messages'; import { showModal } from './overlays'; import { downloadState } from './progress'; import { queueController } from './queue-controller'; import { showRestartFailure } from './updater-ui'; -export const trackSettings = (value: RosiSettings): RosiSettings => - new Proxy(value, { +export const trackSettings = (value: RosiSettings): RosiSettings => { + settingsStore.settingsSavedRevision = settingsStore.settingsRevision; + return new Proxy(value, { set(target, property, next, receiver) { const previous = Reflect.get(target, property, receiver); const applied = Reflect.set(target, property, next, receiver); @@ -23,6 +25,7 @@ export const trackSettings = (value: RosiSettings): RosiSettings => return applied; }, }); +}; export const reconcileSettingsInPlace = (value: RosiSettings) => { const current = settingsStore.settings as unknown as Record; @@ -38,18 +41,20 @@ export const reconcileSettingsInPlace = (value: RosiSettings) => { } }; -export function showSettingsSaveError(message: string) { - const now = Date.now(); - if (now - settingsStore.settingsSaveErrorShownAt < 5000) { - return; - } - settingsStore.settingsSaveErrorShownAt = now; - showModal({ - title: 'Settings Save Failed', - message, - buttons: [{ label: 'OK', primary: true }], - priority: true, - }); +export function setSettingsSaveFeedback(state: 'saving' | 'saved' | 'error', message: string) { + const feedback = document.getElementById('settingsSaveFeedback'); + if (!(feedback instanceof HTMLElement)) return; + feedback.dataset.state = state; + const messageElement = feedback.querySelector('.settings-save-message'); + if (messageElement) messageElement.textContent = message; + const retry = document.getElementById('retrySettingsSave') as HTMLButtonElement | null; + if (retry) retry.hidden = state !== 'error'; +} + +export function showSettingsSaveError(message: string, retryable = true) { + setSettingsSaveFeedback('error', message); + const retry = document.getElementById('retrySettingsSave') as HTMLButtonElement | null; + if (retry) retry.hidden = !retryable; } export function settleSettingsSaveWaiters( @@ -123,6 +128,7 @@ export async function drainSettingsSaves() { // snapshot is still the newest renderer revision. if (snapshotRevision === settingsStore.settingsRevision) { reconcileSettingsInPlace(result.data as RosiSettings); + settingsStore.settingsSavedRevision = snapshotRevision; } } else if (result?.error?.code === 'VALIDATION_ERROR' && result.error.details) { // The other fields were saved; only the listed ones were refused. @@ -146,6 +152,7 @@ export async function drainSettingsSaves() { settingsStore.reconcilingSettings = false; } settingsStore.refreshSettingsControls?.(); + settingsStore.settingsSavedRevision = snapshotRevision; saved = true; settingsStore.lastSettingsSaveErrorCode = null; rejectedMessage = result.error.message; @@ -161,21 +168,23 @@ export async function drainSettingsSaves() { // A newer ROSI owns settings.json: the file is preserved and the user was // told once. Callers proceed with the in-memory values. const preserved = !saved && settingsStore.lastSettingsSaveErrorCode === 'NEWER_VERSION'; - const settled = settleSettingsSaveWaiters(snapshotRevision, saved || preserved, latestRevision); + settleSettingsSaveWaiters(snapshotRevision, saved || preserved, latestRevision); if (rejectedMessage) { showSettingsSaveError( - `This setting was not changed:\n${rejectedMessage}\nYour other settings were saved.` + `This setting was not changed. ${rejectedMessage} Other settings were saved.`, + false ); - } else if ( - !saved && - settingsStore.lastSettingsSaveErrorCode !== 'NEWER_VERSION' && - snapshotRevision === latestRevision && - settled.some((waiter) => !waiter.silent) - ) { - // A newer-version settings file is reported once by the backend. - showSettingsSaveError(`${errorMessage}\nChanges may not persist after restart.`); + } else if (preserved && snapshotRevision === latestRevision) { + showSettingsSaveError(UI_MESSAGES.settings.conflict, false); + } else if (saved && snapshotRevision === latestRevision) { + setSettingsSaveFeedback('saved', UI_MESSAGES.settings.saved); + } else if (!saved && snapshotRevision === latestRevision) { + showSettingsSaveError(`${UI_MESSAGES.settings.saveFailed} ${errorMessage}`); + } else if (settingsStore.settingsSaveWaiters.length > 0) { + setSettingsSaveFeedback('saving', UI_MESSAGES.settings.saving); } settingsStore.settingsSaveInFlight = false; + refreshEffectiveOptionsSummary(true); // A save requested during this request either fired its debounce already, // or explicitly asked for an immediate flush. Preserve debounce spacing @@ -190,6 +199,7 @@ export async function drainSettingsSaves() { } export async function persistSettings(silent = false, immediate = false): Promise { + setSettingsSaveFeedback('saving', UI_MESSAGES.settings.saving); if (settingsStore.persistDebounceTimer) { clearTimeout(settingsStore.persistDebounceTimer); settingsStore.persistDebounceTimer = null; @@ -290,6 +300,7 @@ export async function checkUpdatesOnStartup() { // Owned by the renderer controller; set during startup and updated while it runs. export const settingsStore: { settingsRevision: number; + settingsSavedRevision: number; settings: RosiSettings; reconcilingSettings: boolean; settingsSaveErrorShownAt: number; @@ -307,6 +318,7 @@ export const settingsStore: { isFlatpakBuild: boolean; } = { settingsRevision: 0, + settingsSavedRevision: 0, settings: undefined as unknown as RosiSettings, reconcilingSettings: false, settingsSaveErrorShownAt: 0, diff --git a/src/engine/settings-view.ts b/src/engine/settings-view.ts index 99fa2076..2f63d179 100644 --- a/src/engine/settings-view.ts +++ b/src/engine/settings-view.ts @@ -1,5 +1,6 @@ // Settings controls: rendering from settings, search, and section collapse. import { RosiSettings, dockModule, renderFolderSummary, settingsModule } from './core'; +import { refreshEffectiveOptionsSummary, UI_MESSAGES } from './messages'; import { isModalActive, modalQueue, showModal } from './overlays'; import { refs } from './refs'; import { persistSettings, settingsStore } from './settings-store'; @@ -124,29 +125,21 @@ export const updateUIFromSettings = () => { if (refs.downloadFolderSummary) { renderFolderSummary(refs.downloadFolderSummary, settingsStore.settings.downloadFolder); } - if (refs.downloadOutputSummary) { - if (settingsStore.settings.downloadMode === 'best-video') { - refs.downloadOutputSummary.textContent = - 'Highest available video and audio quality, merged into one file'; - } else if (settingsStore.settings.downloadMode === 'audio') { - refs.downloadOutputSummary.textContent = `Audio only, saved as ${(settingsStore.settings.audioFormat || 'mp3').toUpperCase()}`; - } else if (settingsStore.settings.downloadMode === 'custom') { - refs.downloadOutputSummary.textContent = 'Pick exact video and audio formats below'; - } else { - refs.downloadOutputSummary.textContent = - 'Prefer MP4 when available; otherwise use the best available format. Often low resolution'; - } - } // disable convert when audio-only is enabled if (refs.convertToggle) { - refs.convertToggle.disabled = settingsStore.settings.audioOnly ?? false; - if (settingsStore.settings.audioOnly) { + const conversionUnavailable = settingsStore.settings.audioOnly ?? false; + refs.convertToggle.disabled = conversionUnavailable; + const conversionHint = document.getElementById('convertDisabledHint'); + if (conversionUnavailable) { refs.convertToggle.parentElement!.classList.add('disabled'); - refs.convertToggle.parentElement!.title = 'Disabled when Audio-only mode is enabled'; + refs.convertToggle.parentElement!.title = UI_MESSAGES.controls.convertAudioOnly; + refs.convertToggle.setAttribute('aria-describedby', 'convertDisabledHint'); } else { refs.convertToggle.parentElement!.classList.remove('disabled'); refs.convertToggle.parentElement!.title = ''; + refs.convertToggle.removeAttribute('aria-describedby'); } + if (conversionHint instanceof HTMLElement) conversionHint.hidden = !conversionUnavailable; } if (refs.notificationsToggle) { refs.notificationsToggle.checked = settingsStore.settings.notifications ?? true; @@ -192,6 +185,7 @@ export const updateUIFromSettings = () => { if (refs.showUpdateChannelBtn) refs.showUpdateChannelBtn.classList.add('hidden'); } } + refreshEffectiveOptionsSummary(); }; export const applyDownloadProfile = (mode: RosiSettings['downloadMode']) => { diff --git a/src/engine/wizard.ts b/src/engine/wizard.ts index badf4ba1..f575ad92 100644 --- a/src/engine/wizard.ts +++ b/src/engine/wizard.ts @@ -7,6 +7,7 @@ import { renderFolderSummary, } from './core'; import { DENO_INSTALL_DOCS, isLinuxPlatform } from './deno'; +import { UI_MESSAGES } from './messages'; import { focusFirstElement, focusTopOverlayOr, @@ -99,6 +100,8 @@ export function launchSetupWizard( // Destination step: the folder is optional when asking every time. let wizardChosenFolder = settings.downloadFolder?.trim() || ''; const wizardFolderSummary = document.getElementById('wizard-folder-summary'); + const wizardFolderError = document.getElementById('wizard-folder-error'); + const wizardError = document.getElementById('wizard-error'); const wizardChooseFolderBtn = document.getElementById( 'wizard-choose-folder' ) as HTMLButtonElement | null; @@ -110,26 +113,52 @@ export function launchSetupWizard( if (!wizardFolderSummary) return; if (wizardAskLocation?.checked) { wizardFolderSummary.textContent = 'ROSI will ask before every download'; + wizardFolderSummary.title = ''; return; } - wizardFolderSummary.textContent = wizardChosenFolder || 'Choose a folder or ask each time'; + wizardFolderSummary.textContent = + wizardChosenFolder || 'Choose a folder or ask before each download'; + wizardFolderSummary.title = wizardChosenFolder; + }; + const clearFolderError = () => { + if (wizardFolderError) { + wizardFolderError.textContent = ''; + wizardFolderError.hidden = true; + } + }; + const showFolderError = (message: string) => { + if (wizardFolderError) { + wizardFolderError.textContent = message; + wizardFolderError.hidden = false; + } }; if (wizardAskLocation) { wizardAskLocation.checked = !!settings.askDownloadLocation; - wizardAskLocation.addEventListener('change', syncWizardFolderSummary); + wizardAskLocation.addEventListener('change', () => { + clearFolderError(); + syncWizardFolderSummary(); + }); } if (wizardChooseFolderBtn) { wizardChooseFolderBtn.addEventListener('click', async () => { wizardChooseFolderBtn.disabled = true; + wizardChooseFolderBtn.setAttribute('aria-busy', 'true'); + clearFolderError(); try { const chosen = await window.api.selectDownloadLocation(); if (chosen) { wizardChosenFolder = chosen; if (wizardAskLocation) wizardAskLocation.checked = false; syncWizardFolderSummary(); + } else if (!wizardAskLocation?.checked) { + showFolderError(UI_MESSAGES.wizard.folderCancelled); } + } catch (error) { + logError('Wizard folder selection failed', error); + showFolderError(UI_MESSAGES.wizard.folderFailed); } finally { wizardChooseFolderBtn.disabled = false; + wizardChooseFolderBtn.removeAttribute('aria-busy'); } }); } @@ -239,21 +268,18 @@ export function launchSetupWizard( } function showDenoMissing() { - setDenoStatus( - 'missing', - "Deno isn't installed. Some YouTube videos may not download until it is." - ); + setDenoStatus('missing', UI_MESSAGES.wizard.denoMissing); if (isLinuxPlatform()) { - setDenoAction('Open install instructions', () => { + setDenoAction(UI_MESSAGES.wizard.installInstructions, () => { void window.api.openExternal(DENO_INSTALL_DOCS); }); } else { - setDenoAction('Install Deno', () => void installDenoFromWizard()); + setDenoAction(UI_MESSAGES.wizard.installDeno, () => void installDenoFromWizard()); } } async function installDenoFromWizard() { - setDenoStatus('installing', 'Installing Deno. This may take a moment…'); + setDenoStatus('installing', UI_MESSAGES.wizard.denoInstalling); if (denoAction) denoAction.disabled = true; try { const result = await window.api.installDeno(); @@ -264,14 +290,14 @@ export function launchSetupWizard( if (result?.success !== true) { throw new Error(result?.error || 'Deno installation did not complete successfully.'); } - setDenoStatus('installed', 'Deno is installed. Restart ROSI after setup to use it.'); + setDenoStatus('installed', UI_MESSAGES.wizard.denoInstalledRestart); setDenoAction(null, null); } catch (error) { const message = (error as { error?: string })?.error || (error instanceof Error ? error.message : 'Unknown error'); - setDenoStatus('error', `Automatic install failed: ${message}`); - setDenoAction('Open install instructions', () => { + setDenoStatus('error', UI_MESSAGES.wizard.denoInstallFailed(message)); + setDenoAction(UI_MESSAGES.wizard.installInstructions, () => { void window.api.openExternal(DENO_INSTALL_DOCS); }); } @@ -287,23 +313,20 @@ export function launchSetupWizard( denoDescription.textContent = 'yt-dlp uses a small JavaScript runtime for full YouTube support. This Flatpak build includes its own.'; } - setDenoStatus( - 'installed', - 'This Flatpak build includes its own JavaScript runtime. YouTube downloads are fully supported.' - ); + setDenoStatus('installed', UI_MESSAGES.wizard.flatpakRuntime); return; } - setDenoStatus('checking', 'Checking for Deno…'); + setDenoStatus('checking', UI_MESSAGES.wizard.denoChecking); try { if (await window.api.checkDenoInstalled()) { - setDenoStatus('installed', 'Deno is installed. YouTube downloads are fully supported.'); + setDenoStatus('installed', UI_MESSAGES.wizard.denoInstalled); } else { showDenoMissing(); } } catch (error) { logError('Wizard Deno check failed', error); - setDenoStatus('error', "Couldn't check for Deno."); - setDenoAction('Open install instructions', () => { + setDenoStatus('error', UI_MESSAGES.wizard.denoCheckFailed); + setDenoAction(UI_MESSAGES.wizard.installInstructions, () => { void window.api.openExternal(DENO_INSTALL_DOCS); }); } @@ -411,16 +434,16 @@ export function launchSetupWizard( } catch (error) { logError('Could not load default settings for setup skip', error); } - if (defaults) { - const target = settings as unknown as Record; - const source = defaults as unknown as Record; - WIZARD_SETTING_KEYS.forEach((key) => { - if (key in source) target[key] = source[key]; - }); - } + if (!defaults) return false; + const target = settings as unknown as Record; + const source = defaults as unknown as Record; + WIZARD_SETTING_KEYS.forEach((key) => { + if (key in source) target[key] = source[key]; + }); applyThemeFn(settings.theme || 'system'); applyFlatUi(!!settings.flatUi); updateBackgroundAnimation(settings.animateBackground ?? true); + return true; } async function finalizeWizard(skipped: boolean): Promise { @@ -485,7 +508,16 @@ export function launchSetupWizard( if (wizardSkipping || wizardClosed) return; wizardSkipping = true; if (skipBtn) skipBtn.disabled = true; - await applyWizardDefaults(); + const defaultsLoaded = await applyWizardDefaults(); + if (!defaultsLoaded) { + wizardSkipping = false; + if (skipBtn) skipBtn.disabled = false; + if (wizardError) { + wizardError.textContent = UI_MESSAGES.wizard.defaultsFailed; + wizardError.hidden = false; + } + return; + } await closeWizard(true); } skipBtn?.addEventListener('click', () => void skipWizard()); @@ -504,8 +536,16 @@ export function launchSetupWizard( nextButton.disabled = false; backBtnEl.disabled = false; if (skipBtn) skipBtn.disabled = false; + if (wizardError) { + wizardError.textContent = UI_MESSAGES.wizard.saveFailed; + wizardError.hidden = false; + } return; } + if (wizardError) { + wizardError.textContent = ''; + wizardError.hidden = true; + } wizardClosed = true; if (wizardTrapHandler) { overlayEl.removeEventListener('keydown', wizardTrapHandler); diff --git a/src/generated/ipc-types.ts b/src/generated/ipc-types.ts index 78f3832b..bcab9eca 100644 --- a/src/generated/ipc-types.ts +++ b/src/generated/ipc-types.ts @@ -52,14 +52,24 @@ export type QueueStatus = "pending" | "downloading" | "completed" | "failed" | " export type QueueItem = { id: string, url: string, status: QueueStatus, addedAt: number, startedAt?: number | null, completedAt?: number | null, request?: DownloadRequestOptions | null, filename?: string | null, outputPath?: string | null, sizeBytes?: number | null, error?: string | null, }; +export type QueueSnapshot = { revision: number, items: Array, }; + export type VideoInfo = { title: string, uploader?: string | null, durationSeconds?: number | null, thumbnail?: string | null, ext?: string | null, viewCount?: number | null, isPlaylist: boolean, playlistCount?: number | null, webpageUrl?: string | null, }; +export type StreamKind = "audio" | "video" | "audioVideo"; + +export type FormatEntry = { formatId: string, streamKind: StreamKind, vcodec?: string | null, acodec?: string | null, resolution?: string | null, fps?: number | null, fileSizeBytes?: number | null, estimatedSizeBytes?: number | null, }; + +export type FormatList = { formats: Array, }; + export type DownloadStats = { totalDownloads: number, successfulDownloads: number, failedDownloads: number, cancelledDownloads: number, totalBytesDownloaded: number, formatCounts: { [key in string]: number }, firstDownloadAt?: number | null, lastDownloadAt?: number | null, }; export type GpuDetectionResult = { nvidia: boolean, amd: boolean, intel: boolean, }; export type IpcError = { code: "VALIDATION_ERROR" | "INVALID_URL" | "INVALID_PATH" | "NOT_AVAILABLE" | "INTERNAL_ERROR" | "NEWER_VERSION", message: string, details?: string | null, }; +export type DownloadRequestInput = { url?: string | null, outputPath?: string | null, ffmpegPath?: string | null, convertEnabled?: boolean | null, convertFormat?: string | null, keepOriginal?: boolean | null, videoFormat?: string | null, audioFormat?: string | null, playlist?: PlaylistSelection | null, profile?: string | null, presetId?: string | null, presetName?: string | null, bestQuality?: boolean | null, advancedOptions?: boolean | null, audioOnly?: boolean | null, audioOutputFormat?: string | null, hookBrowser?: boolean | null, browserChoice?: string | null, gpuAcceleration?: boolean | null, gpuType?: string | null, writeSubtitles?: boolean | null, subtitleLangs?: string | null, embedThumbnail?: boolean | null, embedMetadata?: boolean | null, sponsorblockRemove?: boolean | null, }; + export type DownloadStarted = { started: boolean, sessionId: number, }; export type QueueStarted = { started: boolean, }; diff --git a/src/index.html b/src/index.html index 2790bbdc..f105d63c 100644 --- a/src/index.html +++ b/src/index.html @@ -85,6 +85,9 @@

Settings

Convert after download +
-

+

Prefer MP4 when available; otherwise use the best available format. Often low resolution

@@ -1389,6 +1413,13 @@

Set Up Downloads

Choose… +