diff --git a/.github/workflows/app-store.yml b/.github/workflows/app-store.yml new file mode 100644 index 0000000..2c23e5a --- /dev/null +++ b/.github/workflows/app-store.yml @@ -0,0 +1,186 @@ +name: App Store Connect + +on: + workflow_dispatch: + inputs: + version: + description: Formal version to validate (defaults to the workspace version); does not upload + required: false + default: "" + type: string + workflow_call: + inputs: + version: + required: true + type: string + +permissions: + contents: read + +jobs: + upload: + runs-on: xcode-27 + timeout-minutes: 120 + concurrency: + group: app-store-${{ inputs.version || github.ref_name }} + cancel-in-progress: false + env: + CARGO_TERM_COLOR: always + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + APP_STORE_APP_IDENTITY: ${{ vars.APP_STORE_APP_IDENTITY }} + APP_STORE_INSTALLER_IDENTITY: ${{ vars.APP_STORE_INSTALLER_IDENTITY }} + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/macos-sdk + id: macos-sdk + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Validate App Store configuration + env: + APP_STORE_CERTIFICATE: ${{ secrets.APP_STORE_CERTIFICATE }} + APP_STORE_CERTIFICATE_PASSWORD: ${{ secrets.APP_STORE_CERTIFICATE_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + run: | + python scripts/app-store.py preflight + python - <<'PY' + import os + required = ("APP_STORE_CERTIFICATE", "APP_STORE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD") + missing = [name for name in required if not os.environ.get(name)] + if missing: + raise SystemExit("Missing GitHub Secrets: " + ", ".join(missing)) + with open(os.environ["GITHUB_ENV"], "a") as output: + output.write("APP_STORE_KEYCHAIN=" + os.environ["RUNNER_TEMP"] + "/beacon-app-store.keychain-db\n") + PY + - name: Validate App Store Connect authentication + env: + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + run: xcrun altool --list-providers --username "$APPLE_ID" --app-password '@env:APPLE_PASSWORD' > /dev/null + - name: Apply release version + id: version + env: + RELEASE_VERSION: ${{ inputs.version }} + # Encode the attempt too, so an upload rerun never reuses a build number. + run: | + test "$GITHUB_RUN_ATTEMPT" -lt 100 + export GITHUB_RUN_NUMBER=$((GITHUB_RUN_NUMBER * 100 + GITHUB_RUN_ATTEMPT)) + if [ -z "$RELEASE_VERSION" ]; then + RELEASE_VERSION="$(python -c 'import pathlib, tomllib; print(tomllib.loads(pathlib.Path("Cargo.toml").read_text())["workspace"]["package"]["version"])')" + fi + python scripts/release.py set "$RELEASE_VERSION" + echo "version=$RELEASE_VERSION" >> "$GITHUB_OUTPUT" + - uses: dtolnay/rust-toolchain@1.98 + with: + targets: aarch64-apple-darwin,x86_64-apple-darwin + - uses: Swatinem/rust-cache@v2 + with: + key: app-store${{ steps.macos-sdk.outputs.cache-suffix }} + - name: Install cargo-packager + run: | + if ! cargo packager --version 2>/dev/null | grep -q '0.11.8'; then + cargo install cargo-packager --version 0.11.8 --locked --force + fi + - name: Build sandboxed universal application + run: | + cargo build --locked --release -p beacon --features app-store --target aarch64-apple-darwin + cargo build --locked --release -p beacon --features app-store --target x86_64-apple-darwin + python scripts/check-macos-sdk.py target/aarch64-apple-darwin/release/beacon --sdk-version "$BEACON_MACOS_SDK_VERSION" + python scripts/check-macos-sdk.py target/x86_64-apple-darwin/release/beacon --sdk-version "$BEACON_MACOS_SDK_VERSION" + mkdir -p target/app-store + lipo -create target/aarch64-apple-darwin/release/beacon target/x86_64-apple-darwin/release/beacon -output target/app-store/beacon + - name: Import App Store signing identities + env: + APP_STORE_CERTIFICATE: ${{ secrets.APP_STORE_CERTIFICATE }} + APP_STORE_CERTIFICATE_PASSWORD: ${{ secrets.APP_STORE_CERTIFICATE_PASSWORD }} + APP_STORE_PROVISIONING_PROFILE: ${{ secrets.APP_STORE_PROVISIONING_PROFILE }} + run: | + python - <<'PY' + import base64, json, os, secrets, shlex, subprocess + from pathlib import Path + def run(*args, **kwargs): + return subprocess.run(args, check=True, **kwargs) + directory = Path(os.environ["RUNNER_TEMP"]) + previous = shlex.split(run("security", "list-keychains", "-d", "user", capture_output=True, text=True).stdout) + (directory / "beacon-keychains.json").write_text(json.dumps(previous)) + password = secrets.token_urlsafe(32) + print("::add-mask::" + password) + keychain = os.environ["APP_STORE_KEYCHAIN"] + certificate = directory / "beacon-app-store.p12" + certificate.write_bytes(base64.b64decode(os.environ["APP_STORE_CERTIFICATE"], validate=True)) + certificate.chmod(0o600) + try: + run("security", "create-keychain", "-p", password, keychain) + run("security", "set-keychain-settings", "-lut", "21600", keychain) + run("security", "unlock-keychain", "-p", password, keychain) + run("security", "list-keychains", "-d", "user", "-s", keychain, *previous) + run("security", "import", str(certificate), "-k", keychain, "-P", os.environ["APP_STORE_CERTIFICATE_PASSWORD"], "-T", "/usr/bin/codesign", "-T", "/usr/bin/productbuild", stdout=subprocess.DEVNULL) + run("security", "set-key-partition-list", "-S", "apple-tool:,apple:,codesign:", "-s", "-k", password, keychain, stdout=subprocess.DEVNULL) + identities = run("security", "find-identity", "-v", keychain, capture_output=True, text=True).stdout + for name in ("APP_STORE_APP_IDENTITY", "APP_STORE_INSTALLER_IDENTITY"): + if '"' + os.environ[name] + '"' not in identities: + raise SystemExit(name + " is missing from the imported p12") + finally: + certificate.unlink(missing_ok=True) + profile = os.environ.get("APP_STORE_PROVISIONING_PROFILE") + if profile: + (directory / "beacon-app-store.provisionprofile").write_bytes(base64.b64decode(profile, validate=True)) + PY + - name: Sign application and installer + run: | + PROFILE_ARGS=() + if [ -f "$RUNNER_TEMP/beacon-app-store.provisionprofile" ]; then + PROFILE_ARGS=(--profile "$RUNNER_TEMP/beacon-app-store.provisionprofile") + fi + python scripts/app-store.py package --keychain "$APP_STORE_KEYCHAIN" "${PROFILE_ARGS[@]}" + - uses: actions/upload-artifact@v4 + with: + name: app-store-${{ steps.version.outputs.version }} + path: target/app-store/*.pkg + if-no-files-found: error + - name: Validate package with App Store Connect + env: + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APP_STORE_PROVIDER_ID: ${{ vars.APP_STORE_PROVIDER_ID }} + run: | + PROVIDER_ARGS=() + if [ -n "$APP_STORE_PROVIDER_ID" ]; then + PROVIDER_ARGS=(--provider-public-id "$APP_STORE_PROVIDER_ID") + fi + xcrun altool --validate-app target/app-store/*.pkg --username "$APPLE_ID" --app-password '@env:APPLE_PASSWORD' "${PROVIDER_ARGS[@]}" + - name: Upload to App Store Connect and wait for processing + if: github.event_name == 'push' + env: + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APP_STORE_PROVIDER_ID: ${{ vars.APP_STORE_PROVIDER_ID }} + run: | + PROVIDER_ARGS=() + if [ -n "$APP_STORE_PROVIDER_ID" ]; then + PROVIDER_ARGS=(--provider-public-id "$APP_STORE_PROVIDER_ID") + fi + xcrun altool --upload-package target/app-store/*.pkg --username "$APPLE_ID" --app-password '@env:APPLE_PASSWORD' --wait "${PROVIDER_ARGS[@]}" + - name: Record validation result + if: github.event_name == 'workflow_dispatch' + env: + RELEASE_VERSION: ${{ steps.version.outputs.version }} + run: echo "Validated the signed universal package for Beacon $RELEASE_VERSION with App Store Connect. No build was uploaded." >> "$GITHUB_STEP_SUMMARY" + - name: Remove temporary signing material + if: always() + run: | + python - <<'PY' + import json, os, subprocess + from pathlib import Path + directory = Path(os.environ["RUNNER_TEMP"]) + previous = directory / "beacon-keychains.json" + if previous.exists(): + subprocess.run(["security", "list-keychains", "-d", "user", "-s", *json.loads(previous.read_text())], check=True) + previous.unlink() + keychain = directory / "beacon-app-store.keychain-db" + if keychain.exists(): + subprocess.run(["security", "delete-keychain", str(keychain)], check=True) + for name in ("beacon-app-store.p12", "beacon-app-store.provisionprofile"): + (directory / name).unlink(missing_ok=True) + PY diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 911facf..916026b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -140,3 +140,9 @@ jobs: # whole test suite runs on a CI runner without a display. - name: Test run: cargo --config .github/ci-profile.toml test --locked --workspace --target ${{ matrix.target }} + + - name: Check Mac App Store variant + if: runner.os == 'macOS' + run: | + cargo --config .github/ci-profile.toml clippy --locked -p beacon --features app-store --target ${{ matrix.target }} + cargo --config .github/ci-profile.toml test --locked -p beacon-updater --features app-store --target ${{ matrix.target }} diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 7d26001..95eca34 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -360,6 +360,14 @@ jobs: target/${{ matrix.target }}/release/*.sig if-no-files-found: error + app-store: + if: needs.prepare.outputs.publish == 'true' && vars.APP_STORE_ENABLED == 'true' + needs: [prepare, release] + uses: ./.github/workflows/app-store.yml + with: + version: ${{ needs.prepare.outputs.version }} + secrets: inherit + release: if: needs.prepare.outputs.publish == 'true' needs: [prepare, checks, package] diff --git a/Cargo.lock b/Cargo.lock index 177421b..f0b92f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -734,6 +734,8 @@ dependencies = [ "gpui-kit", "lsp-types", "nucleo-matcher", + "objc2 0.6.4", + "objc2-foundation 0.3.2", "regex", "roxmltree 0.21.1", "rust-i18n", diff --git a/assets/packaging/Info.plist b/assets/packaging/Info.plist index b125de4..c7f337f 100644 --- a/assets/packaging/Info.plist +++ b/assets/packaging/Info.plist @@ -8,5 +8,7 @@ 1.4.59 CFBundleVersion 1.0.0 + NSHumanReadableCopyright + © 2026 Beacon Team diff --git a/assets/packaging/app-store.entitlements b/assets/packaging/app-store.entitlements new file mode 100644 index 0000000..e013abc --- /dev/null +++ b/assets/packaging/app-store.entitlements @@ -0,0 +1,16 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.bookmarks.app-scope + + + diff --git a/crates/beacon-ui/Cargo.toml b/crates/beacon-ui/Cargo.toml index 552eb9f..fd8e08a 100644 --- a/crates/beacon-ui/Cargo.toml +++ b/crates/beacon-ui/Cargo.toml @@ -6,6 +6,7 @@ rust-version.workspace = true license.workspace = true [features] +app-store = ["beacon-updater/app-store", "dep:objc2", "dep:objc2-foundation"] ui-tests = ["gpui-kit/test-support", "beacon-kube/test-support"] [dependencies] @@ -39,3 +40,7 @@ roxmltree = "=0.21.1" [build-dependencies] serde_json.workspace = true + +[target.'cfg(target_os = "macos")'.dependencies] +objc2 = { version = "0.6.3", optional = true } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSData", "NSError", "NSString", "NSURL"], optional = true } diff --git a/crates/beacon-ui/locales/settings.json b/crates/beacon-ui/locales/settings.json index f4f91aa..4b6c646 100644 --- a/crates/beacon-ui/locales/settings.json +++ b/crates/beacon-ui/locales/settings.json @@ -1099,5 +1099,13 @@ "settings.add_file": { "en": "Add file", "zh-CN": "添加文件" + }, + "settings.app_store_updates": { + "en": "Updates are managed by the Mac App Store.", + "zh-CN": "更新由 Mac App Store 管理。" + }, + "settings.open_app_store": { + "en": "Open App Store", + "zh-CN": "打开 App Store" } } diff --git a/crates/beacon-ui/src/app_store.rs b/crates/beacon-ui/src/app_store.rs new file mode 100644 index 0000000..a744ce9 --- /dev/null +++ b/crates/beacon-ui/src/app_store.rs @@ -0,0 +1,122 @@ +//! Keep user-selected kubeconfig locations accessible across sandboxed launches. +use gpui_kit::{App, Global}; +use objc2::{rc::Retained, runtime::Bool}; +use objc2_foundation::{ + NSData, NSString, NSURL, NSURLBookmarkCreationOptions, NSURLBookmarkResolutionOptions, +}; +use std::{collections::BTreeMap, path::PathBuf}; + +struct Access(Retained); +impl Drop for Access { + fn drop(&mut self) { + // SAFETY: Access is constructed only after a successful start call. + unsafe { self.0.stopAccessingSecurityScopedResource() }; + } +} +struct FileAccess { + path: PathBuf, + bookmarks: BTreeMap>, + active: BTreeMap, +} +impl Global for FileAccess {} + +fn bookmark(url: &NSURL) -> Result, String> { + url.bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error( + NSURLBookmarkCreationOptions::WithSecurityScope, + None, + None, + ) + .map(|data| data.to_vec()) + .map_err(|error| format!("Could not save file access. Choose the location again. {error}")) +} + +fn resolve(bytes: &[u8]) -> Result<(Access, bool), String> { + let mut stale = Bool::NO; + // SAFETY: stale points to a live Bool for the duration of this call. + let url = unsafe { + NSURL::URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error( + &NSData::with_bytes(bytes), + NSURLBookmarkResolutionOptions::WithSecurityScope + | NSURLBookmarkResolutionOptions::WithoutUI, + None, + &mut stale, + ) + } + .map_err(|error| { + format!("Could not restore file access. Choose the location again. {error}") + })?; + // SAFETY: the URL was resolved with security scope and remains retained. + if !unsafe { url.startAccessingSecurityScopedResource() } { + return Err("Could not access the selected location. Choose it again.".into()); + } + Ok((Access(url), stale.as_bool())) +} + +pub(crate) fn init(cx: &mut App) { + let path = crate::settings::store(cx) + .read(cx) + .directory + .join("file-access.json"); + let bookmarks = match std::fs::read(&path) { + Ok(data) => serde_json::from_slice::>>(&data) + .unwrap_or_else(|error| { + tracing::warn!(%error, "could not read saved file access; reselect kubeconfig locations"); + BTreeMap::new() + }), + Err(error) => { + if error.kind() != std::io::ErrorKind::NotFound { + tracing::warn!(%error, "could not read saved file access"); + } + BTreeMap::new() + } + }; + let mut state = FileAccess { + path, + bookmarks, + active: BTreeMap::new(), + }; + let mut refreshed = false; + for (path, bytes) in &mut state.bookmarks { + match resolve(bytes) { + Ok((access, stale)) => { + if stale && let Ok(data) = bookmark(&access.0) { + *bytes = data; + refreshed = true; + } + state.active.insert(path.clone(), access); + } + Err(error) => { + tracing::warn!(%error, path = %path.display(), "file access expired; reselect the kubeconfig location") + } + } + } + if refreshed && let Err(error) = state.save() { + tracing::warn!(%error, "could not refresh saved file access"); + } + cx.set_global(state); +} + +impl FileAccess { + fn save(&self) -> Result<(), String> { + std::fs::create_dir_all(self.path.parent().ok_or("No settings directory.")?) + .map_err(|error| error.to_string())?; + crate::settings::atomic_write( + &self.path, + &serde_json::to_vec(&self.bookmarks).map_err(|error| error.to_string())?, + ) + } +} + +/// Call immediately after the native Open panel grants access to these paths. +pub(crate) fn remember(paths: &[PathBuf], cx: &mut App) -> Result<(), String> { + let state = cx.global_mut::(); + for path in paths { + let url = NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy())); + let data = bookmark(&url)?; + // GPUI returns paths. Resolve the bookmark to regain a scoped NSURL. + let (access, _) = resolve(&data)?; + state.bookmarks.insert(path.clone(), data); + state.active.insert(path.clone(), access); + } + state.save() +} diff --git a/crates/beacon-ui/src/lib.rs b/crates/beacon-ui/src/lib.rs index 3d0a788..3786d86 100644 --- a/crates/beacon-ui/src/lib.rs +++ b/crates/beacon-ui/src/lib.rs @@ -8,6 +8,8 @@ mod activity; mod aggregate_logs; pub mod app; mod app_logs; +#[cfg(all(feature = "app-store", target_os = "macos"))] +mod app_store; mod argo; mod argo_canvas; mod argo_node; diff --git a/crates/beacon-ui/src/preferences/update_page.rs b/crates/beacon-ui/src/preferences/update_page.rs index 4a5f367..20cc2f8 100644 --- a/crates/beacon-ui/src/preferences/update_page.rs +++ b/crates/beacon-ui/src/preferences/update_page.rs @@ -154,6 +154,20 @@ fn preference_row( impl PreferencesView { pub(super) fn updates_form(&self, cx: &mut Context) -> AnyElement { + if cfg!(feature = "app-store") { + return v_flex() + .gap_3() + .child(div().font_weight(FontWeight::MEDIUM).child("Mac App Store")) + .child(hint("Updates are managed by the Mac App Store.", cx)) + .child( + Button::new("app-store-updates") + .small() + .outline() + .label(crate::i18n::text("Open App Store")) + .on_click(|_, _, cx| cx.open_url("macappstore://showUpdates")), + ) + .into_any_element(); + } let Some(store) = crate::updates::maybe_store(cx) else { return div().into_any_element(); }; diff --git a/crates/beacon-ui/src/sources.rs b/crates/beacon-ui/src/sources.rs index 1c79a54..19dc8ed 100644 --- a/crates/beacon-ui/src/sources.rs +++ b/crates/beacon-ui/src/sources.rs @@ -42,6 +42,8 @@ pub(crate) fn kubeconfig_path(id: &beacon_kube::ClusterId, cx: &App) -> Option

) { + if cfg!(feature = "app-store") { + if kind == CheckKind::Manual { + cx.open_url("macappstore://showUpdates"); + } + return; + } if matches!(self.status, Status::Checking) { // A manual request may reuse the running background check, but its // result must now report errors to the user who requested it. diff --git a/crates/beacon-updater/Cargo.toml b/crates/beacon-updater/Cargo.toml index 4e3935e..e801686 100644 --- a/crates/beacon-updater/Cargo.toml +++ b/crates/beacon-updater/Cargo.toml @@ -5,6 +5,9 @@ edition.workspace = true rust-version.workspace = true license.workspace = true +[features] +app-store = [] + [dependencies] anyhow.workspace = true base64.workspace = true diff --git a/crates/beacon-updater/src/install.rs b/crates/beacon-updater/src/install.rs index 5f8182d..4ab7dc7 100644 --- a/crates/beacon-updater/src/install.rs +++ b/crates/beacon-updater/src/install.rs @@ -26,6 +26,9 @@ pub enum Installation { } impl Installation { pub fn detect() -> Self { + if cfg!(feature = "app-store") { + return Self::Managed; + } let Ok(executable) = std::env::current_exe() else { return Self::Managed; }; @@ -51,7 +54,7 @@ impl Installation { Self::Managed } pub fn can_install(&self) -> bool { - !matches!(self, Self::Managed) + !cfg!(feature = "app-store") && !matches!(self, Self::Managed) } pub fn platform(&self) -> String { let format = match self { @@ -177,6 +180,9 @@ pub fn prepare_install( } /// Must be called before logging workers, Tokio or GPUI are initialized. pub fn helper_main() -> Option> { + if cfg!(feature = "app-store") { + return None; + } let mut args = std::env::args_os().skip(1); if args.next().as_deref() != Some(std::ffi::OsStr::new("--beacon-update")) { return None; diff --git a/crates/beacon-updater/src/lib.rs b/crates/beacon-updater/src/lib.rs index b1fdd01..bd18066 100644 --- a/crates/beacon-updater/src/lib.rs +++ b/crates/beacon-updater/src/lib.rs @@ -156,6 +156,9 @@ impl Client { channel: Channel, installation: &Installation, ) -> Result> { + if cfg!(feature = "app-store") { + return Ok(None); + } let current = Version::parse(current)?; let api = match channel { Channel::Stable => format!("https://api.github.com/repos/{REPOSITORY}/releases/latest"), @@ -245,6 +248,9 @@ impl Client { cache: PathBuf, mut progress: impl FnMut(u64, u64) + Send, ) -> Result { + if cfg!(feature = "app-store") { + bail!("Updates are managed by the Mac App Store"); + } // Synchronous file handles are confined to the network worker. Their // deterministic drop closes the file before TempDir cleanup on Windows. use std::io::Write as _; @@ -464,3 +470,49 @@ mod tests { assert!(verify(&key, b"tampered", "aW52YWxpZA==").is_err()); } } + +#[cfg(all(test, feature = "app-store"))] +mod app_store_tests { + use super::*; + + #[tokio::test] + async fn store_build_never_checks_or_downloads_external_updates() { + let client = Client::new(Proxy::Direct, PUBLIC_KEY).unwrap(); + // This must return before parsing metadata or contacting GitHub. + assert!( + client + .check("invalid", Channel::Stable, &Installation::Managed) + .await + .unwrap() + .is_none() + ); + let directory = tempfile::tempdir().unwrap(); + let cache = directory.path().join("must-not-create"); + let release = Release { + version: Version::new(2, 0, 0), + notes: String::new(), + page: "https://example.invalid".parse().unwrap(), + asset: Asset { + url: "https://example.invalid/package".parse().unwrap(), + signature: String::new(), + size: 1, + format: Format::App, + }, + }; + let error = client + .download(release, cache.clone(), |_, _| {}) + .await + .err() + .unwrap(); + assert!(error.to_string().contains("Mac App Store")); + assert!(!cache.exists()); + assert!(!Installation::detect().can_install()); + assert!( + !Installation::MacApp { + bundle: "/Applications/Beacon.app".into(), + executable: "/Applications/Beacon.app/Contents/MacOS/beacon".into() + } + .can_install() + ); + } +} diff --git a/crates/beacon-updater/tests/download.rs b/crates/beacon-updater/tests/download.rs index a907f66..1b59821 100644 --- a/crates/beacon-updater/tests/download.rs +++ b/crates/beacon-updater/tests/download.rs @@ -1,3 +1,5 @@ +#![cfg(not(feature = "app-store"))] + use beacon_updater::{Asset, Client, Format, Proxy, Release, verify_package}; use std::time::Duration; use tokio::{ diff --git a/crates/beacon/Cargo.toml b/crates/beacon/Cargo.toml index b45e341..cdc2450 100644 --- a/crates/beacon/Cargo.toml +++ b/crates/beacon/Cargo.toml @@ -10,6 +10,9 @@ description = "A cross-platform Kubernetes client built with Rust and GPUI" name = "beacon" path = "src/main.rs" +[features] +app-store = ["beacon-ui/app-store", "beacon-updater/app-store"] + [dependencies] beacon-kube.workspace = true beacon-ui.workspace = true @@ -32,6 +35,7 @@ embed-resource = "3.0.11" # not. [package.metadata.packager] product-name = "Beacon" +copyright = "© 2026 Beacon Team" # Has to stay in step with `ProjectDirs::from("dev", "beacon", "Beacon")` in # crates/beacon/src/logging.rs, which is what decides where the log directory # lives. Changing it strands whatever is already on disk. @@ -75,9 +79,8 @@ info-plist-path = "../../assets/packaging/Info.plist" # cargo-packager always passes `--options runtime`, and passes `--entitlements` # only when one is configured, so leaving `entitlements` unset is what keeps the -# app out of the App Sandbox. Beacon reads ~/.kube/config and runs kubeconfig -# `exec` credential plugins, neither of which a sandboxed app can do without -# entitlements nobody has asked for yet. +# standalone app out of the App Sandbox. The App Store workflow builds a +# separate app-store feature with sandbox entitlements and scoped file access. # The package workflow sets this locally on the runner from a GitHub variable. # For local signing, set the identity stored in your keychain. # signing-identity = "Developer ID Application: NAME (TEAMID)" diff --git a/crates/beacon/src/main.rs b/crates/beacon/src/main.rs index 267bbbd..74c6205 100644 --- a/crates/beacon/src/main.rs +++ b/crates/beacon/src/main.rs @@ -27,7 +27,10 @@ fn main() -> anyhow::Result<()> { // PATH also has to be updated before the logging worker starts, and // before kubeconfig exec credential plugins are looked up on PATH. - beacon_kube::shell_env::merge_login_shell_path(); + // A sandboxed app cannot source the user's login-shell configuration. + if !cfg!(feature = "app-store") { + beacon_kube::shell_env::merge_login_shell_path(); + } let logging = logging::init()?; let log_directory = logging.directory.clone(); diff --git a/docs/PACKAGING.md b/docs/PACKAGING.md index eca1099..db202bc 100644 --- a/docs/PACKAGING.md +++ b/docs/PACKAGING.md @@ -83,10 +83,62 @@ GitHub Actions 用 **Developer ID Application** 签署 Beacon 的 `.app` 和 `.d [apple-app-password]: https://support.apple.com/zh-cn/102654 -**不开 App Sandbox。** cargo-packager 对原生二进制总是传 `--options runtime`,只在配置了 +**独立分发版不开 App Sandbox。** cargo-packager 对原生二进制总是传 `--options runtime`,只在配置了 `entitlements` 时才传 `--entitlements`,所以"不写 entitlements"就是保持不沙箱的全部操作。 这不是偷懒:Beacon 要读 `~/.kube/config`,还要在 PATH 上找 kubeconfig 的 `exec` 凭据插件 -并把它作为子进程跑起来,沙箱里这两件事都做不了。 +并把它作为子进程跑起来。商店版使用下面的独立构建流程,文件和子进程操作受沙箱限制。 + +## App Store Connect + +正式标签发布 GitHub Release 后,`package` 工作流调用 `app-store.yml`,构建开启 +`app-store` feature 的 ARM64 + Intel 通用应用,用商店证书签署 `.app` 和 `.pkg`, +通过 `xcrun altool --upload-package --wait` 上传并等待 Apple 处理。安装包同时保存在 +Actions 的 `app-store-<版本>` artifact 中。这个流程只上传构建,不自动提交审核或上架。 +手动运行 `package` 仍只生成普通开发版产物。 + +手动运行 **App Store Connect** 工作流会构建并签署商店安装包,再使用 Apple 的服务 +验证安装包和上传凭据,产物保存在 Actions 中。这个手动入口不会上传构建,适合首次配置 +证书或轮换证书后验证流程。只有正式标签触发的发布才会执行上传步骤。 + +在 Xcode 的 Accounts → Manage Certificates 或 Apple Developer 网站创建 +**Apple Distribution / Mac App Distribution** 和 **Mac Installer Distribution**, +将带有私钥的两个身份一起导出为有密码的 `.p12`。可用 `security find-identity -v` +查看两者,`-p codesigning` 会隐藏安装器身份。Developer ID 证书不能用于商店上传。 + +新增以下 GitHub Actions 配置,保留原有独立分发的 Apple 凭据。 + +| 类型 | 名称 | 值 | +| --- | --- | --- | +| Secret | `APP_STORE_CERTIFICATE` | 包含应用和安装器两个身份的 `.p12`,Base64 编码,无换行 | +| Secret | `APP_STORE_CERTIFICATE_PASSWORD` | 该 `.p12` 的导出密码 | +| Secret,可选 | `APP_STORE_PROVISIONING_PROFILE` | Mac App Store provisioning profile 的 Base64 内容;TestFlight 必须配置 | +| Variable | `APP_STORE_APP_IDENTITY` | `Apple Distribution: NAME (TEAMID)` 或 `3rd Party Mac Developer Application: NAME (TEAMID)` | +| Variable | `APP_STORE_INSTALLER_IDENTITY` | `3rd Party Mac Developer Installer: NAME (TEAMID)` | +| Variable,可选 | `APP_STORE_PROVIDER_ID` | Apple 账户属于多个 provider 时填写,使用 `xcrun altool --list-providers` 查询 | +| Variable | `APP_STORE_ENABLED` | 完成证书配置后设为 `true`,启用正式版本自动上传 | + +上传复用 `APPLE_ID`、`APPLE_PASSWORD`(应用专用密码)和 `APPLE_TEAM_ID`。 +账户需要有上传该 App 的权限。签名材料仅在临时钥匙串中导入,任务结束后删除。 +当前网络、用户选择文件和书签权限无需受限 entitlement 的 profile;配置 profile 后, +脚本会校验有效期、Team ID、完整 App ID,并拒绝开发或 Developer ID profile。 + +商店版启用 `assets/packaging/app-store.entitlements` 中的 App Sandbox、网络客户端与 +服务器权限(用于集群访问和端口转发)、用户选择文件读写及持久书签。请通过 +**Kubeconfig sources → Add files / Choose folder** 授权配置位置,或粘贴自包含 YAML。 +选择配置目录可同时授权目录中的证书等相对路径文件;直接输入路径不会授予沙箱访问权限。 +书签保存于容器内的 `file-access.json`,在启动时恢复。系统 kubeconfig、登录 shell 环境、 +外部凭据插件、kubectl / Helm 和终端功能不能沿用独立分发版的完整访问权限,需要在真实 +商店签名构建中逐项验证。商店版不运行 GitHub 更新检查或安装器,更新入口打开 Mac App Store。 + +App Store Connect 的 App 记录必须使用 `dev.beacon.Beacon`,版本号必须与正式发布的 +`X.Y.Z` 一致。Apple 处理完成后,在对应版本的“构建版本”中选择上传结果,再填写商店资料并提交审核。 +原来的 `1.0` 页面需要先改为本次发布版本。重跑上传会使用新的 `CFBundleVersion`。 + +版权在 `crates/beacon/Cargo.toml` 的 `package.metadata.packager.copyright` 中配置, +当前为 `© 2026 Beacon Team`。`release.py` 每次更新版本都会将它写入 +`NSHumanReadableCopyright`,Finder 的“显示简介”可以显示该文字。 +App Store Connect 页面里的“版权”是独立商店资料,首次提交时填写 `2026 Beacon Team` +(Apple 自动加上 ©);上传安装包不会替你修改这个字段。 ## 构建与打包分开执行 @@ -94,9 +146,8 @@ cargo-packager 只打包、**不构建**。先显式 `cargo build --release -p b cargo-packager。产物跟着**当前机器的架构**走 —— 本机是 arm64,DMG 名字里的 `aarch64` 就是它。 -不做 universal:那意味着把整棵依赖树(含 GPUI)编两遍再 `lipo`,而 cargo-packager 本身 -没有 universal 的概念。真要做的话是加一个先编两个 target 再 lipo 到 `target/release/beacon` -的脚本,然后让 cargo-packager 打那个合并后的二进制。 +独立分发版按架构分别打包。商店版先编译两个 target,再用 `lipo` 合并到 +`target/app-store/beacon`,由 `scripts/app-store.py` 使用相同的 cargo-packager 元数据打包。 ## 两个会咬人的环境问题 diff --git a/scripts/app-store.py b/scripts/app-store.py new file mode 100644 index 0000000..169011b --- /dev/null +++ b/scripts/app-store.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Package the app-store feature's universal binary for App Store Connect.""" +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import tomllib + + +ROOT = Path(__file__).resolve().parents[1] + + +def run(*args, **kwargs): + return subprocess.run([str(arg) for arg in args], check=True, **kwargs) + + +def identities(environment): + names = ("APPLE_TEAM_ID", "APP_STORE_APP_IDENTITY", "APP_STORE_INSTALLER_IDENTITY") + missing = [name for name in names if not environment.get(name)] + if missing: + raise ValueError("Missing App Store configuration: " + ", ".join(missing)) + team, app, installer = (environment[name] for name in names) + if not re.fullmatch(r"[A-Z0-9]{10}", team): + raise ValueError("APPLE_TEAM_ID must contain ten uppercase letters or digits") + if not app.startswith(("Apple Distribution:", "3rd Party Mac Developer Application:")): + raise ValueError("APP_STORE_APP_IDENTITY must be an App Store application identity") + if not installer.startswith("3rd Party Mac Developer Installer:"): + raise ValueError("APP_STORE_INSTALLER_IDENTITY must be a Mac Installer Distribution identity") + if not all(name.endswith(f"({team})") for name in (app, installer)): + raise ValueError("Both App Store identities must belong to APPLE_TEAM_ID") + return team, app, installer + + +def provisioning_entitlements(profile, team, identifier, now=None): + """Profiles are optional for these unrestricted entitlements, required for TestFlight.""" + now = now or datetime.now(timezone.utc) + expiry = profile.get("ExpirationDate") + if not isinstance(expiry, datetime) or expiry.replace(tzinfo=timezone.utc) <= now: + raise ValueError("The App Store provisioning profile is expired or has no expiry") + entitlements = profile.get("Entitlements", {}) + app_id = f"{team}.{identifier}" + if profile.get("TeamIdentifier") != [team] or entitlements.get("com.apple.application-identifier") != app_id: + raise ValueError("The provisioning profile must match the exact team and bundle identifier") + if entitlements.get("com.apple.developer.team-identifier") != team: + raise ValueError("The provisioning profile team entitlement does not match") + if profile.get("ProvisionedDevices") or profile.get("ProvisionsAllDevices") or entitlements.get("get-task-allow") or entitlements.get("com.apple.security.get-task-allow"): + raise ValueError("Use a Mac App Store distribution profile, not a development or Developer ID profile") + return { + "com.apple.application-identifier": app_id, + "com.apple.developer.team-identifier": team, + } + + +def packager_config(root, output): + manifest = root / "crates/beacon/Cargo.toml" + package = tomllib.loads(manifest.read_text(encoding="utf-8"))["package"] + config = package["metadata"]["packager"] + version = tomllib.loads((root / "Cargo.toml").read_text(encoding="utf-8"))["workspace"]["package"]["version"] + if not re.fullmatch(r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)", version): + raise ValueError("App Store Connect packaging requires a formal X.Y.Z version") + config.update({ + "name": package["name"], "version": version, + # Select the macOS packaging backend. The input executable contains both architectures. + "target-triple": "aarch64-apple-darwin", + "out-dir": str(output), "binaries-dir": str(output), + }) + config["icons"] = [str((manifest.parent / icon).resolve()) for icon in config["icons"]] + macos = config["macos"] + macos.pop("signing-identity", None) + macos.pop("entitlements", None) + macos["info-plist-path"] = str((manifest.parent / macos["info-plist-path"]).resolve()) + # Signing follows profile embedding and uses the job's isolated keychain. + return config + + +def package(root, output, keychain, profile): + team, app_identity, installer_identity = identities(os.environ) + config = packager_config(root, output) + binary = output / "beacon" + architectures = run("lipo", "-archs", binary, capture_output=True, text=True).stdout.split() + if set(architectures) != {"arm64", "x86_64"}: + raise ValueError("App Store binary must contain both arm64 and x86_64 architectures") + config_path = output / "packager.json" + config_path.write_text(json.dumps(config), encoding="utf-8") + run("cargo", "packager", "--config", config_path, "--formats", "app", cwd=root) + app = output / "Beacon.app" + info = plistlib.loads((app / "Contents/Info.plist").read_bytes()) + if info.get("CFBundleIdentifier") != config["identifier"] or info.get("CFBundleShortVersionString") != config["version"]: + raise ValueError("Packaged app identifier or version does not match the release") + if info.get("NSHumanReadableCopyright") != config["copyright"]: + raise ValueError("Packaged app copyright does not match the packaging configuration") + entitlements = plistlib.loads((root / "assets/packaging/app-store.entitlements").read_bytes()) + if profile: + decoded = run("security", "cms", "-D", "-i", profile, capture_output=True).stdout + entitlements.update(provisioning_entitlements(plistlib.loads(decoded), team, config["identifier"])) + shutil.copyfile(profile, app / "Contents/embedded.provisionprofile") + entitlements_path = output / "app-store.entitlements" + entitlements_path.write_bytes(plistlib.dumps(entitlements)) + run("codesign", "--force", "--sign", app_identity, "--keychain", keychain, + "--entitlements", entitlements_path, app) + run("codesign", "--verify", "--deep", "--strict", "--verbose=2", + "--test-requirement", f'=anchor apple generic and certificate leaf[subject.OU] = "{team}"', app) + signed = run("codesign", "--display", "--entitlements", ":-", app, capture_output=True).stdout + if plistlib.loads(signed) != entitlements: + raise ValueError("Signed application entitlements do not match the App Store configuration") + pkg = output / f'Beacon_{config["version"]}_universal_app-store.pkg' + run("productbuild", "--component", app, "/Applications", "--sign", installer_identity, + "--keychain", keychain, pkg) + signature = run("pkgutil", "--check-signature", pkg, capture_output=True, text=True).stdout + if installer_identity not in signature: + raise ValueError("Installer signature does not match APP_STORE_INSTALLER_IDENTITY") + print(signature) + print(f"App Store package: {pkg}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=("preflight", "package")) + parser.add_argument("--output", type=Path, default=ROOT / "target/app-store") + parser.add_argument("--keychain", type=Path) + parser.add_argument("--profile", type=Path) + args = parser.parse_args() + try: + identities(os.environ) + if args.command == "package": + if not args.keychain: + raise ValueError("--keychain is required for signing") + package(ROOT, args.output.resolve(), args.keychain.resolve(), args.profile) + except (ValueError, OSError, subprocess.CalledProcessError) as error: + parser.exit(1, f"App Store packaging failed: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/release.py b/scripts/release.py index 768f46b..c5cf12d 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -84,11 +84,16 @@ def set_version(root, version, build_number=0): tomllib.loads(new_lock_text) # Apple requires numeric bundle versions. Keep the full SemVer in the app # and a custom plist key, with the CI run encoded as a 4.2.2-digit number. - plist = plistlib.dumps({ + info = { "CFBundleShortVersionString": version.split("-")[0], "CFBundleVersion": f"{1 + build_number // 10000}.{build_number // 100 % 100}.{build_number % 100}", "BeaconVersion": version, - }) + } + package = tomllib.loads((root / "crates/beacon/Cargo.toml").read_text(encoding="utf-8")) + copyright = package["package"].get("metadata", {}).get("packager", {}).get("copyright") + if copyright: + info["NSHumanReadableCopyright"] = copyright + plist = plistlib.dumps(info) plist_path = root / "assets" / "packaging" / "Info.plist" plist_path.parent.mkdir(parents=True, exist_ok=True) manifest_path.write_text(new_manifest_text, encoding="utf-8") diff --git a/scripts/tests/test_app_store.py b/scripts/tests/test_app_store.py new file mode 100644 index 0000000..c9ac111 --- /dev/null +++ b/scripts/tests/test_app_store.py @@ -0,0 +1,83 @@ +import importlib.util +from datetime import datetime, timedelta, timezone +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location("app_store", Path(__file__).resolve().parents[1] / "app-store.py") +app_store = importlib.util.module_from_spec(spec) +spec.loader.exec_module(app_store) + + +class AppStoreTests(unittest.TestCase): + def setUp(self): + self.team = "ABCDEFGHIJ" + self.environment = { + "APPLE_TEAM_ID": self.team, + "APP_STORE_APP_IDENTITY": f"Apple Distribution: Example ({self.team})", + "APP_STORE_INSTALLER_IDENTITY": f"3rd Party Mac Developer Installer: Example ({self.team})", + } + self.now = datetime(2026, 11, 18, tzinfo=timezone.utc) + self.profile = { + "ExpirationDate": self.now + timedelta(days=30), + "TeamIdentifier": [self.team], + "Entitlements": { + "com.apple.application-identifier": f"{self.team}.dev.beacon.Beacon", + "com.apple.developer.team-identifier": self.team, + }, + } + + def test_distribution_identities_are_required_and_team_must_match(self): + app_store.identities(self.environment) + self.environment["APP_STORE_APP_IDENTITY"] = f"3rd Party Mac Developer Application: Example ({self.team})" + app_store.identities(self.environment) + for name, value in ( + ("APP_STORE_APP_IDENTITY", f"Developer ID Application: Example ({self.team})"), + ("APP_STORE_APP_IDENTITY", "Apple Distribution: Example (OTHERTTEAM)"), + ("APP_STORE_INSTALLER_IDENTITY", f"Developer ID Installer: Example ({self.team})"), + ("APPLE_TEAM_ID", ""), + ): + invalid = dict(self.environment, **{name: value}) + with self.subTest(name=name, value=value), self.assertRaises(ValueError): + app_store.identities(invalid) + + def test_profile_matches_bundle_and_team(self): + result = app_store.provisioning_entitlements(self.profile, self.team, "dev.beacon.Beacon", self.now) + self.assertEqual(result, self.profile["Entitlements"]) + for team, identifier in (("OTHERTTEAM", "dev.beacon.Beacon"), (self.team, "other.bundle")): + with self.subTest(team=team, identifier=identifier), self.assertRaises(ValueError): + app_store.provisioning_entitlements(self.profile, team, identifier, self.now) + + def test_expired_development_and_developer_id_profiles_are_rejected(self): + for change in ( + {"ExpirationDate": self.now - timedelta(seconds=1)}, + {"ProvisionedDevices": ["device-id"]}, + {"ProvisionsAllDevices": True}, + {"Entitlements": dict(self.profile["Entitlements"], **{"get-task-allow": True})}, + {"Entitlements": dict(self.profile["Entitlements"], **{"com.apple.security.get-task-allow": True})}, + ): + with self.subTest(change=change), self.assertRaises(ValueError): + app_store.provisioning_entitlements(dict(self.profile, **change), self.team, "dev.beacon.Beacon", self.now) + + def test_store_config_uses_formal_version_and_separate_output(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + manifest = root / "crates/beacon/Cargo.toml" + manifest.parent.mkdir(parents=True) + manifest.write_text('[package]\nname = "beacon"\n[package.metadata.packager]\nidentifier = "dev.beacon.Beacon"\ncopyright = "© 2026 Beacon Team"\nicons = ["../../assets/icon.icns"]\n[package.metadata.packager.macos]\ninfo-plist-path = "../../assets/packaging/Info.plist"\nsigning-identity = "Developer ID Application: Example"\n', encoding="utf-8") + workspace = root / "Cargo.toml" + workspace.write_text('[workspace.package]\nversion = "1.4.60"\n') + output = root / "target/app-store" + config = app_store.packager_config(root, output) + self.assertEqual(config["version"], "1.4.60") + self.assertEqual(config["binaries-dir"], str(output)) + self.assertEqual(config["copyright"], "© 2026 Beacon Team") + self.assertNotIn("signing-identity", config["macos"]) + self.assertEqual(config["icons"], [str((root / "assets/icon.icns").resolve())]) + workspace.write_text('[workspace.package]\nversion = "1.4.60-dev.123"\n') + with self.assertRaisesRegex(ValueError, "formal"): + app_store.packager_config(root, output) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_release.py b/scripts/tests/test_release.py index 87b7c96..8d8f089 100644 --- a/scripts/tests/test_release.py +++ b/scripts/tests/test_release.py @@ -89,7 +89,7 @@ def setUp(self): ) with (self.root / "crates/beacon/Cargo.toml").open("a", encoding="utf-8") as file: file.write( - '[package.metadata.packager]\nproduct-name = "Beacon"\nicons = ["../../assets/icon.png"]\n' + '[package.metadata.packager]\nproduct-name = "Beacon"\ncopyright = "© 2026 Beacon Team"\nicons = ["../../assets/icon.png"]\n' '[package.metadata.packager.macos]\ninfo-plist-path = "../../assets/packaging/Info.plist"\n' ) self.dependency = ( @@ -137,6 +137,7 @@ def test_macos_versions_are_numeric_and_builds_remain_ordered(self): self.assertEqual(plist["CFBundleShortVersionString"], "0.2.0") self.assertEqual(plist["CFBundleVersion"], expected) self.assertEqual(plist["BeaconVersion"], f"0.2.0-dev.{number}") + self.assertEqual(plist["NSHumanReadableCopyright"], "© 2026 Beacon Team") before = self.contents() with self.assertRaises(ValueError): release.set_version(self.root, "0.2.0", 99_990_000)