diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5bda91a..988e35e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,26 +4,53 @@ on: push: tags: - 'v*' # Triggers on version tags like v0.1.1, v1.0.0 - workflow_dispatch: # Allows manual trigger from GitHub UI + workflow_dispatch: + inputs: + platforms: + description: 'Platforms to run' + type: choice + options: [none, mac, linux, windows, all] + default: none + notarize: + description: 'Try Apple notarization for this test build (failure is nonblocking)' + type: boolean + default: false # Grant write permissions for creating releases permissions: contents: write +concurrency: + group: build-${{ github.head_ref || github.ref }} + cancel-in-progress: true + jobs: + plan: + runs-on: ubuntu-latest + timeout-minutes: 2 + outputs: + platforms: ${{ steps.plan.outputs.platforms }} + build: ${{ steps.plan.outputs.build }} + steps: + - uses: actions/checkout@v4 + - id: plan + run: node scripts/ci-plan.js + env: + INPUT_PLATFORMS: ${{ inputs.platforms }} + build: + needs: [plan] + if: needs.plan.outputs.platforms != '[]' strategy: fail-fast: false # Don't cancel other builds if one fails matrix: - include: - - os: macos-latest - platform: mac - - os: windows-latest - platform: win - - os: ubuntu-latest - platform: linux + include: ${{ fromJSON(needs.plan.outputs.build) }} runs-on: ${{ matrix.os }} + timeout-minutes: 90 + env: + MAC_RELEASE_STRICT: ${{ startsWith(github.ref, 'refs/tags/') }} + NOTARIZE_MAC: ${{ startsWith(github.ref, 'refs/tags/') || inputs.notarize == true }} steps: - name: Checkout code @@ -45,12 +72,15 @@ jobs: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Build for macOS (with signing) + id: signed_mac if: matrix.platform == 'mac' + continue-on-error: ${{ !startsWith(github.ref, 'refs/tags/') }} run: | - # Unset empty signing vars so electron-builder skips signing gracefully - [ -z "$CSC_LINK" ] && unset CSC_LINK - [ -z "$CSC_KEY_PASSWORD" ] && unset CSC_KEY_PASSWORD - npm run build:mac -- --publish never + set -euo pipefail + for name in CSC_LINK CSC_KEY_PASSWORD; do + test -n "${!name}" || { echo "Missing required credential $name"; exit 1; } + done + npm run build:mac -- --arm64 --publish never -c.forceCodeSigning=true env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} CSC_LINK: ${{ secrets.CSC_LINK }} @@ -59,14 +89,31 @@ jobs: APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + - name: Build macOS test app with ad-hoc signing + if: matrix.platform == 'mac' && steps.signed_mac.outcome == 'failure' && !startsWith(github.ref, 'refs/tags/') + run: npm run build:mac -- --arm64 --publish never -c.mac.identity=- -c.mac.hardenedRuntime=false -c.forceCodeSigning=false + env: + CSC_IDENTITY_AUTO_DISCOVERY: 'false' + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Verify macOS code signature if: matrix.platform == 'mac' run: | - APP_PATH=$(find dist-electron -name "*.app" -maxdepth 2 | head -1) - if [ -n "$APP_PATH" ]; then - echo "Verifying signature on: $APP_PATH" - codesign --verify --deep --strict "$APP_PATH" && echo "Signature valid" || echo "WARNING: Signature verification failed" + set -euo pipefail + APP_PATH="dist-electron/mac-arm64/ElastOS.app" + test -d "$APP_PATH" + codesign --verify --deep --strict --verbose=2 "$APP_PATH" + codesign -dv "$APP_PATH" 2>&1 + node scripts/verify-mac-app.js "$APP_PATH" + if [[ "$MAC_RELEASE_STRICT" == true && "$NOTARIZE_MAC" == true ]]; then + spctl -a -vv "$APP_PATH" fi + for dmg in dist-electron/*.dmg; do + if [[ "$MAC_RELEASE_STRICT" == true && "$NOTARIZE_MAC" == true ]]; then + xcrun stapler validate "$dmg" + fi + shasum -a 256 "$dmg" + done - name: Upload artifacts uses: actions/upload-artifact@v4 @@ -78,12 +125,19 @@ jobs: dist-electron/*.exe dist-electron/*.AppImage dist-electron/*.deb - if-no-files-found: ignore + if-no-files-found: error + + linux-arm64: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'linux') + uses: ./.github/workflows/linux-arm64.yml + with: + platforms: linux release: - needs: build + needs: [plan, build, linux-arm64] runs-on: ubuntu-latest - if: startsWith(github.ref, 'refs/tags/') + if: startsWith(github.ref, 'refs/tags/') && needs.plan.outputs.platforms != '[]' steps: - name: Download all artifacts @@ -92,7 +146,7 @@ jobs: path: artifacts - name: Create Release - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 with: files: artifacts/**/* draft: false diff --git a/.github/workflows/linux-arm64.yml b/.github/workflows/linux-arm64.yml new file mode 100644 index 0000000..9e26dfa --- /dev/null +++ b/.github/workflows/linux-arm64.yml @@ -0,0 +1,78 @@ +name: Linux ARM64 package + +# Ubuntu 22.04 matches the Jetson glibc (2.35). +on: + pull_request: + paths-ignore: ['**/*.md', 'docs/**'] + push: + branches: [main] + workflow_dispatch: + inputs: + platforms: + description: 'Platforms to run' + type: choice + options: [none, mac, linux, windows, all] + default: none + workflow_call: + inputs: + platforms: + description: 'Platforms selected by the caller' + type: string + default: '' + +permissions: + contents: read + +concurrency: + group: linux-arm64-${{ github.head_ref || github.ref }} + cancel-in-progress: true + +jobs: + plan: + runs-on: ubuntu-latest + timeout-minutes: 2 + outputs: + platforms: ${{ steps.plan.outputs.platforms }} + steps: + - uses: actions/checkout@v4 + - id: plan + run: node scripts/ci-plan.js + env: + INPUT_PLATFORMS: ${{ inputs.platforms }} + + package: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'linux') + runs-on: ubuntu-22.04-arm + timeout-minutes: 90 + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Build the arm64 AppImage and deb + run: npm run build:linux -- --arm64 --publish never + + - name: Record checksums + run: | + set -euo pipefail + sha256sum dist-electron/*.AppImage dist-electron/*.deb + test -n "$(find dist-electron -maxdepth 1 -name '*arm64*.AppImage' -print)" + test -n "$(find dist-electron -maxdepth 1 -name '*arm64*.deb' -print)" + + - name: Upload the arm64 packages + uses: actions/upload-artifact@v4 + with: + name: ElastOS-linux-arm64 + path: | + dist-electron/*.AppImage + dist-electron/*.deb + if-no-files-found: error diff --git a/.github/workflows/runtime-smoke.yml b/.github/workflows/runtime-smoke.yml index 74c9e88..3bfbfe5 100644 --- a/.github/workflows/runtime-smoke.yml +++ b/.github/workflows/runtime-smoke.yml @@ -1,35 +1,87 @@ +# test/launcher-mac* -> mac. test/launcher-jetson* or test/launcher-linux* -> linux x64+arm64. test/launcher-windows* -> windows. +# PR into main or push to main -> all. Other branches -> none. Dispatch uses explicit platforms (default none). name: Runtime smoke -# Linux x64, macOS arm64, and the ElastOS WSL2 distro are required. -# A red run fails the pull request. Each job installs the active pin -# (canary until stable is published). If that pin does not match the -# publisher, install stops. The job then checks gateway /healthz and +# A red run fails the pull request. Each job verifies the selected channel +# against the maintainer DID and rollback floor. Failed verification means +# install stops. The job then checks gateway /healthz and # /home/. The Windows job imports distro ElastOS as WSL2. It does not skip. on: pull_request: + paths-ignore: ['**/*.md', 'docs/**'] + push: + branches: [main] workflow_dispatch: + inputs: + platforms: + description: 'Platforms to run' + type: choice + options: [none, mac, linux, windows, all] + default: none + +concurrency: + group: runtime-smoke-${{ github.head_ref || github.ref }} + cancel-in-progress: true jobs: + plan: + runs-on: ubuntu-latest + timeout-minutes: 2 + outputs: + platforms: ${{ steps.plan.outputs.platforms }} + runtime: ${{ steps.plan.outputs.runtime }} + steps: + - uses: actions/checkout@v4 + - id: plan + run: node scripts/ci-plan.js + env: + INPUT_PLATFORMS: ${{ inputs.platforms }} + + mac-dialogs: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'mac') + name: packaged dialog hit regions (mac) + runs-on: macos-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + cache: npm + - run: npm ci + - name: Package the candidate + run: npm run build:mac -- --arm64 --publish never -c.mac.identity=- -c.mac.hardenedRuntime=false -c.forceCodeSigning=false + env: + CSC_IDENTITY_AUTO_DISCOVERY: 'false' + NOTARIZE_MAC: 'false' + - name: Require clickable packaged dialogs and main controls + run: node scripts/mac-dialog-e2e.js dist-electron/mac-arm64/ElastOS.app + smoke: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'mac') || contains(needs.plan.outputs.platforms, 'linux') name: smoke (${{ matrix.platform }}) timeout-minutes: 45 strategy: fail-fast: false matrix: - include: - - os: ubuntu-24.04 - platform: linux-x64 - - os: macos-14 - platform: darwin-arm64 + include: ${{ fromJSON(needs.plan.outputs.runtime) }} runs-on: ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@v4 + - name: Require Apple silicon for the Mac lane + if: runner.os == 'macOS' + run: test "$(uname -m)" = arm64 + - name: Install pinned runtime and require a healthy Home run: bash scripts/runtime-smoke.sh windows-wsl: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'windows') name: smoke (windows-wsl) timeout-minutes: 60 runs-on: windows-2025 @@ -41,28 +93,15 @@ jobs: shell: pwsh run: pwsh -File scripts/windows-elastos-distro.ps1 - rollback: - name: rollback (linux-x64) - timeout-minutes: 60 - runs-on: ubuntu-24.04 - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Roll 0.8.0-alpha.22 back to 0.8.0-alpha.21 and forward again - run: bash scripts/runtime-rollback.sh - electron-e2e: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'mac') || contains(needs.plan.outputs.platforms, 'linux') name: e2e (${{ matrix.platform }}) - timeout-minutes: 40 + timeout-minutes: 50 strategy: fail-fast: false matrix: - include: - - os: ubuntu-24.04 - platform: linux-x64 - - os: macos-14 - platform: darwin-arm64 + include: ${{ fromJSON(needs.plan.outputs.runtime) }} runs-on: ${{ matrix.os }} steps: - name: Checkout code @@ -74,11 +113,15 @@ jobs: node-version: '20' cache: npm + - name: Require Apple silicon for the Mac lane + if: runner.os == 'macOS' + run: test "$(uname -m)" = arm64 + - name: Install display libraries if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2t64 libgtk-3-0t64 libxss1 + sudo apt-get install -y ${{ matrix.packages }} - name: Install dependencies env: @@ -107,6 +150,8 @@ jobs: fi electron-e2e-windows: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'windows') name: e2e (windows) timeout-minutes: 60 runs-on: windows-2025 @@ -133,6 +178,8 @@ jobs: run: npm run e2e windows-app: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'windows') name: app install (windows-wsl) timeout-minutes: 60 runs-on: windows-2025 @@ -158,6 +205,8 @@ jobs: run: node scripts/windows-app-install.js clean-machine-linux: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'linux') name: clean machine (ubuntu) timeout-minutes: 45 runs-on: ubuntu-24.04 @@ -183,6 +232,8 @@ jobs: run: bash scripts/clean-machine-linux.sh clean-machine-windows: + needs: [plan] + if: contains(needs.plan.outputs.platforms, 'windows') name: clean machine (windows-wsl) timeout-minutes: 20 runs-on: windows-2025 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c16c0cf..9fffdf8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,9 +2,14 @@ name: Test on: pull_request: + paths-ignore: ['**/*.md', 'docs/**'] push: branches: [main] +concurrency: + group: test-${{ github.head_ref || github.ref }} + cancel-in-progress: true + jobs: test: runs-on: ubuntu-latest @@ -21,5 +26,8 @@ jobs: - name: Install dependencies run: npm ci + - name: Install renderer test browser + run: npx playwright install --with-deps chromium + - name: Unit tests run: npm test diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index de37776..b098e3a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,19 +1,21 @@ # Contributing to the ElastOS launcher -The launcher installs one product: the pinned ElastOS runtime. +The launcher installs the current signed ElastOS for the selected channel. ## Install rule -The Install button and the smoke jobs must call the published installer the way that script accepts it: `ELASTOS_HEAD_CID` set to the pin, and arguments `--install-only` and `--maintainer-did`. Do not add a head flag the installer rejects. +The Install button and the smoke jobs must call the published installer the way that script accepts it: `ELASTOS_HEAD_CID` set to the verified head, and arguments `--install-only` and `--maintainer-did`. Do not add a head flag the installer rejects. -A pin mismatch stops the install. The launcher does not clone a git tree and does not install a second computer app. +A wrong signature or channel, version below the floor, changed metadata snapshot, or installer hash mismatch stops the install. The launcher does not clone a git tree and does not install a second computer app. ## What a change has to keep - Health is `GET http://localhost:8090/healthz` with body `OK`, probed on every address `localhost` resolves to (`src/main/targets/gatewayAddress.ts`, `probeGatewayHealth` in `src/main/targets/runtimeGateway.ts`). - Home is `http://localhost:8090/home/`. -- Stop signals the gateway process group: `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid has exited and `/healthz` has failed twice. -- Reset and uninstall remove only the ElastOS program, its data directory, and the launcher stage file. Other home directories stay on disk. +- Update offers require signed metadata. Runtime 2.0.0 needs a compatibility `update-check.json` record after a successful CLI check. Human-readable stdout never determines the offer. A 2.0.0 source with an unknown head uses the stored signed install record and matching binary version for rollback identity. +- A foreign listener on 8090 keeps running and its specific error reaches the window. A status probe that overlaps Start, Stop, or Update must honor the newer control phase. +- On Mac, the signed Home controller owns System update restarts. Re-read the verified host generation before Stop. On Linux, Stop and Quit signal the update controller only, and only after a fresh read of its `/proc` start time, its exe, and the host lock generation. A mismatch sends no signal. A gateway on `127.0.0.1:8090` stays running and has no Stop control. A process the launcher spawned is signaled through its own process handle. Windows signals the gateway process group with `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid has exited and `/healthz` has failed twice. +- Reset removes only the ElastOS program, its data directory, and the launcher stage file. Uninstall keeps Home data by default at the controller and removal boundaries; deleting data requires an explicit true choice from the native confirmation. Other home directories stay on disk. - IPC channel names are `elastos:*`. The preload object is `window.elastos`. - `src/main/index.ts` does not import `./targets`. - macOS signing stays on hardened runtime, `resources/entitlements.mac.plist`, and `scripts/notarize.js`. @@ -23,3 +25,11 @@ A pin mismatch stops the install. The launcher does not clone a git tree and doe ```bash npm test ``` + +The npm test runner creates an isolated HOME, clears inherited XDG paths, and removes PATH entries that contain an ElastOS program. The missing-runtime test also mocks binary discovery. These guards prevent unit tests from starting a host ElastOS installation. Temporary filesystem fixtures use physical paths so the symlink guard runs on Mac too. + +## Native menu and action windows + +Use `buildHomeMenu` for the tray and macOS application menu. Polls must preserve the existing menu when its state is unchanged; a stale status observation cannot override a newer action. Test the real builder, renderer and main entry point, rather than matching source strings. Run `scripts/prove-launch-redesign.js` to compare installed-app behavior against test.3 without starting Electron or a service. + +After Windows setup, recheck its preflight and resume the pending install once Linux support is available. A setup result without a healthy Home is not proof that Linux setup failed. diff --git a/README.md b/README.md index 107984a..73562d9 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,14 @@ -# ElastOS Desktop Launcher +# ElastOS Desktop App -A one-click desktop app that installs the ElastOS runtime and opens Home in the browser. +ElastOS lives in the menu bar or system tray. Opening the app opens Home in your default browser. ## What it does -Click Install. The launcher checks the signed release pin, runs the pinned installer, starts `elastos gateway` on `localhost:8090`, and opens `http://localhost:8090/home/`. Passkeys need the `localhost` name: browsers refuse them on `127.0.0.1`. +On first run, choose whether Home starts at login, then click Install. The app checks the signed release and installs Home. The ready window stays open until you click Open Home. -The window talks to the main process through `window.elastos` and `elastos:*` IPC. There is one launch target, the runtime. +Use the menu bar (macOS), system tray (Windows), or top-bar indicator (Ubuntu) to open, start, stop and update Home. Troubleshoot contains diagnostics, logs and confirmed maintenance actions. Uninstall keeps Home data unless you choose to delete it. Quit ElastOS stops Home. + +Home uses `http://localhost:8090/home/`. Passkeys require `localhost` rather than `127.0.0.1`. The signed 2.0.0 Home controller opens a browser on cold starts; quiet login and install await a Runtime option to suppress that open. ## Platforms diff --git a/docs/FIRST_RUN.md b/docs/FIRST_RUN.md index e4e33ff..9b15e6a 100644 --- a/docs/FIRST_RUN.md +++ b/docs/FIRST_RUN.md @@ -27,9 +27,9 @@ Intel Macs stop with “Intel Mac is not supported yet.” Nothing is downloaded ## macOS 1. Download the app and open it. macOS may ask whether to open an app that was downloaded from the internet. That dialog is from macOS. -2. Click Install. +2. Review Start Home at Login (checked by default), then click Install. 3. The app checks the signed release, downloads the pinned installer, and downloads a pinned Python only when the Mac cannot already run `python3 -c ''`. -4. The button becomes Open my computer. The page is `http://localhost:8090/home/` in the system browser. +4. The window says Home is ready, points to the menu bar and offers Open Home. The page is `http://localhost:8090/home/` in the system browser. 5. There is no Terminal window, no `xcode-select --install` prompt, and no administrator password for Install. The macOS test hides Command Line Tools, curl, and python3 from the installer and clicks Install on a `macos-14` runner. It is not a freshly imaged Mac. @@ -38,7 +38,7 @@ The macOS test hides Command Line Tools, curl, and python3 from the installer an 1. Open the app and click Install. 2. On glibc Linux with bash, that is the only step. The app supplies curl and, when needed, Python. No administrator password. -3. The button becomes Open my computer. +3. The button becomes Open Home. 4. `/dev/kvm` is optional. Without it, Install still finishes and the system browser opens. The separate in-computer browser stays off. That later piece can ask for a password; it is not part of this click. A musl system, or a system without bash, stops with one sentence. Install does not continue. @@ -50,17 +50,25 @@ The Linux test is an `ubuntu:24.04` container with curl, python3, and gcc absent 1. If Linux support is off, the screen says Windows needs Linux support. The person clicks Enable. They do not type a command. 2. Windows asks for permission once. If Windows says a restart is required, ElastOS says: Restart Windows. When you open ElastOS again, Install continues. 3. After the restart, if Linux support is on, opening ElastOS continues Install. The app adds its own Linux environment, installs python3 and curl there if they are missing, and installs the runtime. If Linux support is still off, Install waits. -4. The button becomes Open my computer. The page opens in the Windows browser at `http://localhost:8090/home/`. -5. The info panel says: Browser is not available on this computer yet. The in-computer Browser does not run on Windows yet. Home opens in the Windows browser. +4. The window says Home is ready, points to the menu bar and offers Open Home. The page opens in the Windows browser at `http://localhost:8090/home/`. +5. ElastOS is in the system tray; its menu opens, starts, stops and updates Home. The in-computer Browser does not run on Windows yet. The ElastOS Linux environment is not removed by Remove PC2. ## Gaps - The macOS click test hides developer tools on a GitHub `macos-14` runner. It does not boot a blank Mac. -- The Windows runner cannot turn Linux support off and reboot in the same job, so it cannot click from “WSL disabled” through to Open my computer. The Enable command, the restart sentence, and the decision to continue Install only after Linux support is on are tested. A runner that already has Linux support can install and open Home. +- The Windows runner cannot turn Linux support off and reboot in the same job, so it cannot click from “WSL disabled” through to Open Home. The Enable command, the restart sentence, and the decision to continue Install only after Linux support is on are tested. A runner that already has Linux support can install and open Home. - A musl system is refused. ElastOS does not ship a musl runtime. - A Linux system without bash is refused. The app does not bundle bash. -- The in-computer browser on Linux can still ask for a password later. Install and Open my computer do not. +- The in-computer browser on Linux can still ask for a password later. Install and Open Home do not. - Gatekeeper on macOS can still ask the person to confirm the downloaded app. The app cannot remove that system dialog. - This environment has not notarized a build. Notarization stays on the existing tag-build path. + +## Background operation + +After installation there is no standing app window. Opening ElastOS opens Home; if stopped, Home starts first. Closing an action window leaves Home available through the menu. Quit ElastOS stops Home. Start Home at Login controls hidden app startup and Home startup together. + +The pinned 2.0.0 command is `home --browser`: it starts the signed controller and opens the system browser. It has no supported quiet-start flag. Login and install therefore still open the browser on a cold start; the launcher avoids adding a second tab. The native update menu appears only for the Runtime's signed offer. The current offer format has no release-notes URL, so What's new is hidden unless a real link is supplied. + +Electron 28 accepts the `sublabel` field in its menu model but its native macOS menu implementation does not render it. The menu mock includes the requested `localhost:8090` sublabel; native display needs an Electron upgrade and packaged verification. No dependency upgrade is included in this UI change. diff --git a/docs/RUNTIME_MIGRATION.md b/docs/RUNTIME_MIGRATION.md index 0c24366..f27c188 100644 --- a/docs/RUNTIME_MIGRATION.md +++ b/docs/RUNTIME_MIGRATION.md @@ -6,9 +6,9 @@ Founder decision on 2026-10-16: the previous computer app is gone from this repo | Decision | What this tree does | |---|---| -| Product | The pinned ElastOS runtime. One Install button. | -| Update channel | `stable` is filled from runtime `main` when that head is published. `develop` maps to `canary` for testing. `"active"` in `resources/runtime-pin.json` is the switch. | -| Pin | Each launcher release pins a signed runtime version, UnixFS head CID, installer SHA-256, and maintainer DID. | +| Product | The current signed ElastOS on the selected channel. One Install button. | +| Update channel | Stable by default. `"active"` in `resources/runtime-pin.json` selects Stable or Canary. A missing channel publication fails closed. | +| Pin | Maintainer DID and minimum version 2.0.0. Verify the chosen head, its manifest hash and signature, then the manifest’s `installer_sha256`. Packaged head CIDs and installer hashes do not select a release. | | Home | Fresh runtime data directory. No import of another product. | | Windows | Dedicated WSL2 distro named `ElastOS`. | | Intel Mac | “Intel Mac is not supported yet.” until a signed `darwin-x64` release exists. | @@ -17,13 +17,19 @@ Founder decision on 2026-10-16: the previous computer app is gone from this repo ## 1. How the launcher runs the runtime -The launcher is an Electron 28 shell. It does not embed the runtime. It downloads the pinned `install.sh`, checks the Ed25519 release head and the installer SHA-256, and runs: +The launcher is an Electron 28 shell. It does not embed the runtime. It checks the Ed25519 release head against the pinned maintainer DID and the selected channel, refuses versions below 2.0.0, verifies `release.json` against the head’s `release_sha256` and the maintainer signature, and checks `install.sh` against the manifest’s `installer_sha256`. It runs: -`ELASTOS_HEAD_CID= bash install.sh --install-only --maintainer-did ` +`ELASTOS_HEAD_CID= bash install.sh --install-only --maintainer-did --publisher-gateway ` -The launcher drops every inherited `ELASTOS_*` variable before it starts install.sh, `elastos setup`, `elastos gateway`, or `elastos update` (`runtimeChildEnv` in `src/main/targets/releaseHead.ts`). install.sh lets `ELASTOS_MAINTAINER_DID`, `ELASTOS_PUBLISHER_GATEWAY`, `ELASTOS_PUBLISHER_NODE_ID`, `ELASTOS_SOURCE_CONNECT_TICKET`, `ELASTOS_IPNS_NAME`, and others replace its baked values, and the runtime reads many more. `ELASTOS_HEAD_CID` is then set from the signed pin. On Windows, wsl.exe gets no `ELASTOS_*` variable, and the distro command unsets each name install.sh reads (`INSTALLER_ENV_NAMES`) before it sets the head. +The launcher drops every inherited `ELASTOS_*` variable before it starts install.sh, `elastos setup`, `elastos gateway`, or `elastos update` (`runtimeChildEnv` in `src/main/targets/releaseHead.ts`). install.sh lets `ELASTOS_MAINTAINER_DID`, `ELASTOS_PUBLISHER_GATEWAY`, `ELASTOS_PUBLISHER_NODE_ID`, `ELASTOS_SOURCE_CONNECT_TICKET`, `ELASTOS_IPNS_NAME`, and others replace its baked values, and the runtime reads many more. `ELASTOS_HEAD_CID` is then set from the verified head. On native installs the existing curl shim serves the verified head and manifest snapshot, protected by a SHA-256 passed in the sanitized child environment. This prevents a publisher move from changing the accepted version during install. The installer still checks signatures and artifact hashes itself. On Windows, wsl.exe gets no `ELASTOS_*` variable, and the distro command unsets each name install.sh reads (`INSTALLER_ENV_NAMES`) before it sets the head. -Install skips install.sh only when the installed version, the head CID in `sources.json`, and the signed install record (`installation/release-head.json`, verified against the pinned maintainer DID by `signedInstallRecord`, the check Reset uses) all match the pin (`planRuntimeInstall` in `src/main/targets/runtimeInstall.ts`). A missing, tampered, or foreign-signed record means ElastOS is not proven installed, so Install runs the pinned install.sh again. Its `install-release` step accepts the same version (it refuses only an older one) and writes only the binary, `sources.json`, and the two release files in `installation/` (runtime `update.rs` `install_release`, `install_transaction.rs` destinations). install.sh then runs `principal-root-upgrade`, as on every install, which keeps a rollback copy under `backups/`. Nothing else in the data folder is deleted. After install.sh, Install checks the record again and stops with a plain message if it is still not valid. This is what the Reset “Fix it” button relies on. +Install adopts an installed version at least equal to the floor when its version and source head CID match its signed install record. The installed head can differ from the publisher’s current head. Curl-installed 2.0.0 can have an empty source head CID. Its verified install record and matching binary version are sufficient for adoption. Update verifies that stored record, binds it to `elastos version`, and verifies its content CID through the publisher before saving the rollback identity. A conflicting nonempty source CID remains a refusal. Missing components resume setup. A missing, tampered, foreign-signed, or mismatched record runs the verified installer again. Post-install checks require the exact head selected for that operation and a valid matching record. + +On Mac the launcher runs `elastos home --browser`, which enters Runtime 2.0.0’s signed Home update controller. That controller owns updates started from System and starts the replacement Home. The launcher refreshes status while hidden. Stop adopts the installed Home only after verifying its host lock, command, live pid and listening sockets. A controller is signaled only when its status matches that host generation and it is the host’s parent. Quit ElastOS stops Home. There is no steady-state window; closing an action window leaves the native menu available. Start Home at Login is chosen visibly before Install and remains optional. + +The launcher’s Update action stops Home, runs `elastos update --yes`, and starts the current installed binary again, including after a failed command. After a successful `elastos update --check`, a valid Runtime `update-check.json` always wins, including `offered=false`. Runtime 2.0.0 does not write that file. When the Runtime record is absent or invalid, the launcher verifies the publisher head's maintainer DID, channel and version floor, compares SemVer, and atomically writes its own result to `~/.elastos-launcher/update-check.json`. A newer signed version means Update offered. The launcher never writes Runtime's record; #554 owns its refusal-aware decision. Concurrent checks use unique temporary files and re-read Runtime's record before returning the fallback. CLI stdout never determines the offer. This shared path also serves Windows, whose Runtime record is read inside WSL while launcher bookkeeping stays on the host. Launcher self-update is outside this test build. + +The live 2.0.0 release binds install.sh through `release-head.payload.release_sha256` → signed `release.payload.installer_sha256`. This is enforced by Runtime’s publication validator at `elastos/crates/elastos-server/src/release_publication.rs:136–143` in source commit `7bc3704b5e181e5aa435c2b2cafbd73a996932ef`. No unsigned installer fallback is used. Before that command, the app puts its own `curl` and `sha256sum` on `PATH`, and a pinned CPython when this computer cannot run `python3 -c ''`. It does not ask for Xcode Command Line Tools. The click-by-click first run, including the Windows permission prompt and a possible restart, is `docs/FIRST_RUN.md`. @@ -32,7 +38,7 @@ Before that command, the app puts its own `curl` and `sha256sum` on `PATH`, and | Main process | `src/main/index.ts` | Window, tray, and `elastos:*` IPC. It does not import `./targets`. | | Supervisor | `src/main/launchController.ts` | Start, stop, install, update, reset, diagnostics. | | Preload | `src/preload/index.ts` | `window.elastos`. | -| Renderer | `src/renderer/index.html`, `src/renderer/app.js`, `src/renderer/flow.js` | Install, then “Open my computer”. | +| Renderer | `src/renderer/index.html`, `src/renderer/app.js` | Action windows: install, progress, error, update. The native menu lives in `src/main/homeMenu.ts`. | | Registry | `src/main/targets/` | One id, `runtime`. | The tray says Start, Stop, and Open my computer. There is no Computer menu and no location dropdown. @@ -62,7 +68,7 @@ Uninstall on Windows removes the whole ElastOS WSL2 Linux environment with `wsl. Remove PC2 is a separate action in `src/main/legacyPc2Removal.ts`. The button stays hidden until a legacy install is on disk: `~/.pc2`, `~/.elastos/node` when it is the old bundled Node 22.13.1 tree, a PC2 launch agent or autostart file, a sudoers file whose text matches the rules the old installer wrote (`/etc/sudoers.d/wireguard` with `wg-quick`, or `/etc/sudoers.d/amneziawg` with `NOPASSWD:SETENV`, `amneziawg-go`, and `/var/run/amneziawg/`) together with one of those installs, a `~/.pc2` folder inside another Windows Linux distro, or a Windows distro named `pc2` or `pc2-wsl` that itself contains that folder or Node tree. The old installer never wrote `/etc/sudoers.d/elastos` or `/etc/sudoers.d/pc2-wireguard`. This repo has no hash for the VPN programs it compiled, so those programs are not deleted by name. The ElastOS distro is never unregistered. The confirm dialog lists each path and its size. Removal deletes only the paths from that list. “Back up my PC2 data first” must write a backup before anything is deleted, including a Windows Linux folder or distro; if that backup cannot be saved, nothing is removed. One privileged prompt covers a matching sudoers rule. That prompt is pkexec. Cancelling it (exit 126), a missing authorization or a missing prompt (exit 127), and a missing pkexec program each have their own sentence. pkexec is not replaced with sudo. An exit after the prompt has started is the removal command's own result. The list of files still there is what that privileged script can see, including a sudoers file the app itself cannot stat. A failure says what is still there and saves a support bundle. -Stop signals the gateway process group: `SIGTERM`, 15 seconds, then `SIGKILL`, after the pid has exited and `/healthz` has failed twice. Quit shows Stopping and waits long enough for both of those waits and their health probes. If that wait expires, Quit sends `SIGKILL` only to a gateway this window started, and then closes the window. Quit, Stop, and Restart leave a gateway this window did not start running. Reset and Uninstall, after the confirm dialog, adopt that gateway from the host lock and signal the pid they read. They do not ask again. On Windows they adopt only when the distro facts say the listener is ElastOS. A different listener, and a facts read that fails, is left running. On macOS and Linux the adopt itself checks the host lock, the command line, and the health socket. On Windows, an error asking whether that pid has exited is treated as still running. Exit 75 restarts only when the binary was replaced on disk. +On Mac and Linux, Stop and Quit re-read the installed Home and signal its verified controller when the host lock and the update-controller status agree. Linux reads the controller start time from /proc, the controller exe, and the host lock generation immediately before every signal. A reused pid, a stale status file, a wrong exe, or a generation mismatch is left running, and the window says to stop that Home with Ctrl+C. Linux does not signal a host pid, a process group, or a descendant, and it does not adopt a gateway on 127.0.0.1:8090. That gateway is shown as another ElastOS Home with no Stop control. A process the launcher spawned is signaled through its own process handle. The controller drains its children. Windows retains gateway process-group supervision with `SIGTERM`, 15 seconds, then `SIGKILL`, and two failed health probes after the pid exits. Quit waits through shutdown and its health probes. Reset and Uninstall, after the confirm dialog, adopt that gateway from the host lock and signal the pid they read. They do not ask again. On Windows they adopt only when the distro facts say the listener is ElastOS. A different listener, and a facts read that fails, is left running. On macOS and Linux the adopt itself checks the host lock, the command line, and the health socket. On Windows, an error asking whether that pid has exited is treated as still running. Exit 75 restarts only when the binary was replaced on disk. The support bundle redacts labeled secrets (`password`, `token`, `api_key`, `attach_secret`, `cookie`, `authorization`, `seed`, `mnemonic`, `private_key`, `secret`, bearer tokens, and JWTs), the rest of a `seed`, `mnemonic`, `private_key`, or `secret` line, a run of 12 or more BIP39 words in any case, split by spaces, line breaks, commas, hyphens, quotes, or numbering such as `1.` or `2:`, known secret prefixes (AWS access key ids, `ghp_` tokens, and `sk-` keys), hex of 32 or more characters with or without `0x`, including a 64-character hex string unless that line is labelled sha256 or hash, hex wrapped over two or more lines that holds 32 or more characters together (a list of whole 40- or 64-character hashes stays), an unlabeled uppercase token of 16 or more characters that contains a digit and no underscore, a lowercase token of 32 or more characters with high entropy, and an unlabeled mixed-case token of 20 or more characters with high entropy. It keeps paths, a 40-character hex hash on its own line or beside a hash, cid, commit, or installer label, a 64-character hex string on a sha256 or hash line, CIDv0 and CIDv1, `did:key` values, versions, UUIDs, and `UPPER_SNAKE` names. An unlabeled secret shorter than that, or with low entropy, is not redacted. `secret-line` is a short phrase that stays. @@ -74,8 +80,10 @@ On Windows the same installer runs inside distro `ElastOS` as root, and the Wind Check these before the runtime on `main` is marketed as a live product and this launcher is the no-code way in. The Install button, the gateway supervisor, and the canary pin are in this stack. They are not a signed release by themselves. -- [ ] Land launcher PR #5 (`v1.4.0`) before the tag build. It is the notarization that waits for Apple, fails on rejection, and staples the DMG. This stack's `package.json` is already version `1.4.0` and keeps the `test` script (`npm run build:ts && node --test test/*.test.js`) and `extraResources`. Merging PR #5 (`6e28656`) onto that tree leaves `package.json` at `1.4.0` with the test script. Notarization still lives only on PR #5. -- [ ] Fill `channels.stable` in `resources/runtime-pin.json`, then change `"active"` from `canary` to `stable`. That `active` field is the channel switch. Until a stable head exists, the pin stays on canary `0.8.0-alpha.22`. +- Mac test build `2.0.0-test.1` keeps Developer ID signing when credentials work and falls back to ad-hoc signing when they do not. Only the ad-hoc test fallback disables hardened runtime, because library validation refuses Electron's framework with a different Team ID. Every Mac build must pass the packaged Electron loader check in a scratch HOME as well as signature verification. Apple notarization runs only when explicitly requested with `NOTARIZE_MAC=true`. The workflow sets it from the `notarize` dispatch input, and an Apple failure does not block manual builds. Tag builds require Developer ID signing and hardened runtime. Apple's Accepted verdict, stapling and Gatekeeper validation apply when notarization is requested. Credentials enter notarytool through its secure prompt. The notarization hook is ported from SashaMIT's `6e28656` / PR #5. +- electron-builder is pinned to 26.16.1 for its corrected temporary-keychain password handling on current Mac runners. Upstream fix is electron-userland/electron-builder#10172. +- Stable is the default and 2.0.0 is the rollback floor. Head movement alone does not require a launcher release. +- The evidence below records earlier builds. The Mac test-branch report records current checks and the DMG receipt. - [x] Linux x64 click path on GitHub Actions, [run 38883782991](https://github.com/Elacity/elastos-launcher/actions/runs/38883782991) job [`smoke (linux-x64)`](https://github.com/Elacity/elastos-launcher/actions/runs/38883782991/job/116916496268) (2026-10-16, `5620dfd`, canary `0.8.0-alpha.20`): `Release head signature matches the pinned maintainer`, `install.sh SHA-256 matches the pin`, `Installed version: ElastOS Runtime v0.8.0-alpha.20`, `Installed head CID matches the pin`, `components.json is present`, `/healthz is OK`, `/home/ HTTP 200`, `Gateway stopped cleanly`. The job is required. - [x] macOS arm64 on the same run, job [`smoke (darwin-arm64)`](https://github.com/Elacity/elastos-launcher/actions/runs/38883782991/job/116916496468), runner `macos-14`: `Platform: macOS 14.8.9 on Apple silicon (aarch64-darwin)`, `Release head signature matches the pinned maintainer`, `install.sh SHA-256 matches the pin`, `Installed version: ElastOS Runtime v0.8.0-alpha.20`, `Installed head CID matches the pin`, `components.json is present`, `/healthz is OK`, `/home/ HTTP 200`, `Gateway stopped cleanly`. The job is required. - [x] `continue-on-error` is removed from the Linux x64 and macOS arm64 smoke jobs. @@ -87,6 +95,6 @@ Check these before the runtime on `main` is marketed as a live product and this - [ ] No phone-home telemetry. - [x] Uninstall and Reset remove only the exact runtime paths: `~/.local/bin/elastos`, `~/.local/share/elastos`, `~/Library/Application Support/elastos`, `~/.elastos-launcher/install-stage.json`, and `~/.elastos-launcher/resume-install.json`. Reset also removes `~/.elastos-launcher/resume-install.json.lock`. An XDG data directory under this home is included when it is empty or holds only the partial-install files, or when every entry is a runtime name and the signed install record verifies. A user file is refused by name even beside that record. Other folders stay on disk. - [x] Remove PC2 is separate from Reset and Uninstall. It is shown only when a legacy install is detected, lists those known paths and their sizes, and refuses runtime paths, symlink escapes, and any other path. -- [ ] A gateway whose host lock is not the installed ElastOS gateway is left running. Quit, Stop, and Restart do not adopt a gateway this window did not start. Reset and Uninstall, after the confirm dialog, adopt the installed gateway and then signal its process group: `SIGTERM`, 15 seconds, then `SIGKILL`, and only after the pid is dead and `/healthz` has failed twice. Quit's wait covers both of those waits and sends `SIGKILL` only to a gateway this window started. +- A foreign listener is left running. On Mac and Linux, Start, Stop, Restart and Quit can adopt the verified installed Home. Controller shutdown drains its child processes. Windows retains its gateway supervision path. - [ ] Diagnostics and the log panel do not contain `attach_secret` or the coordinate JSON files. Labeled secrets, AWS key ids, `ghp_` tokens, `sk-` keys, a run of 12 or more BIP39 words in any layout, wrapped hex, and hex that is not a 40-character hash or a 64-character hex string on a sha256 or hash line are redacted. An unlabeled short or low-entropy phrase is not. -- [x] Live rollback on the same run, job [`rollback (linux-x64)`](https://github.com/Elacity/elastos-launcher/actions/runs/38883782991/job/116916495924): install of `0.8.0-alpha.20` prints `/healthz is OK`, then `previous head QmULef49FjitVQPtLqSpzXcpAJpvaCueLzs31R6dWBUdsM is 0.8.0-alpha.19`, `elastos update --rollback-to QmULef49FjitVQPtLqSpzXcpAJpvaCueLzs31R6dWBUdsM --yes` prints `Installed version: ElastOS Runtime v0.8.0-alpha.19` and `/healthz is OK`, then `elastos update --yes` prints `Installed version: ElastOS Runtime v0.8.0-alpha.20`, `/healthz is OK`, and `Rollback returned to the pinned release`. +- Live rollback of historical alpha releases is no longer a CI job. Stable 2.0.0's linked predecessor is Canary 2.0.0-rc.2; Runtime correctly refuses that channel change, and there is no prior Stable release within the 2.0.0 floor to exercise. Current signed install and health checks remain in smoke. Unit tests exercise the launcher's verified rollback CID and refusal paths. A future live rollback fixture must use releases on the subscribed channel and within the install floor. diff --git a/package-lock.json b/package-lock.json index e3ea2b9..8f08f47 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "elastos-launcher", - "version": "1.4.0", + "version": "2.0.0-test.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "elastos-launcher", - "version": "1.4.0", + "version": "2.0.0-test.4", "license": "AGPL-3.0", "dependencies": { "electron-log": "^5.0.0" @@ -14,29 +14,11 @@ "devDependencies": { "@types/node": "^20.10.0", "electron": "^28.0.0", - "electron-builder": "^24.9.1", + "electron-builder": "26.16.1", "playwright": "^1.48.2", "typescript": "^5.3.0" } }, - "node_modules/@develar/schema-utils": { - "version": "2.6.5", - "resolved": "https://registry.npmjs.org/@develar/schema-utils/-/schema-utils-2.6.5.tgz", - "integrity": "sha512-0cp4PsWQ/9avqTVMCtZ+GirikIA36ikvjtHweU4/j8yLtgObI0+JUPhYFScgwlteveGB1rt3Cm8UhN04XayDig==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^6.12.0", - "ajv-keywords": "^3.4.1" - }, - "engines": { - "node": ">= 8.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, "node_modules/@electron/asar": { "version": "3.4.1", "resolved": "https://registry.npmjs.org/@electron/asar/-/asar-3.4.1.tgz", @@ -55,10 +37,17 @@ "node": ">=10.12.0" } }, + "node_modules/@electron/asar/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/@electron/asar/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -67,9 +56,9 @@ } }, "node_modules/@electron/asar/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -79,6 +68,60 @@ "node": "*" } }, + "node_modules/@electron/fuses": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@electron/fuses/-/fuses-1.8.0.tgz", + "integrity": "sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.1", + "fs-extra": "^9.0.1", + "minimist": "^1.2.5" + }, + "bin": { + "electron-fuses": "dist/bin.js" + } + }, + "node_modules/@electron/fuses/node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@electron/fuses/node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/@electron/fuses/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/@electron/get": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@electron/get/-/get-2.0.3.tgz", @@ -102,9 +145,9 @@ } }, "node_modules/@electron/notarize": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.2.1.tgz", - "integrity": "sha512-aL+bFMIkpR0cmmj5Zgy0LMKEpgy43/hw5zadEArgmAMWWlKc5buwFvFT9G/o/YJkvXAJm5q3iuTuLaiaXW39sg==", + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.5.0.tgz", + "integrity": "sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==", "dev": true, "license": "MIT", "dependencies": { @@ -133,9 +176,9 @@ } }, "node_modules/@electron/notarize/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -156,9 +199,9 @@ } }, "node_modules/@electron/osx-sign": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-1.0.5.tgz", - "integrity": "sha512-k9ZzUQtamSoweGQDV2jILiRIHUu7lYlJ3c6IEmjv1hC17rclE+eb9U+f6UFlOOETo0JzY1HNlXy4YOlCvl+Lww==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@electron/osx-sign/-/osx-sign-1.3.3.tgz", + "integrity": "sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -206,9 +249,9 @@ } }, "node_modules/@electron/osx-sign/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -228,56 +271,82 @@ "node": ">= 10.0.0" } }, + "node_modules/@electron/rebuild": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@electron/rebuild/-/rebuild-4.2.1.tgz", + "integrity": "sha512-IS4pG3BysRrCLJ8xTAfvg+IQDbiUoAzdJy2SfjcYKnLDy5DpCdjnPdhS5Zf5UMfrkB24xu0KC+TqcOxg+eG+6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@malept/cross-spawn-promise": "^2.0.0", + "debug": "^4.1.1", + "node-abi": "^4.2.0", + "node-api-version": "^0.2.1", + "node-gyp": "^12.2.0", + "read-binary-file-arch": "^1.0.6" + }, + "bin": { + "electron-rebuild": "lib/cli.js" + }, + "engines": { + "node": ">=22.12.0" + } + }, "node_modules/@electron/universal": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-1.5.1.tgz", - "integrity": "sha512-kbgXxyEauPJiQQUNG2VgUeyfQNFk6hBF11ISN2PNI6agUgPl55pv4eQmaqHzTAzchBvqZ2tQuRVaPStGf0mxGw==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@electron/universal/-/universal-2.0.3.tgz", + "integrity": "sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g==", "dev": true, "license": "MIT", "dependencies": { - "@electron/asar": "^3.2.1", - "@malept/cross-spawn-promise": "^1.1.0", + "@electron/asar": "^3.3.1", + "@malept/cross-spawn-promise": "^2.0.0", "debug": "^4.3.1", - "dir-compare": "^3.0.0", - "fs-extra": "^9.0.1", - "minimatch": "^3.0.4", - "plist": "^3.0.4" + "dir-compare": "^4.2.0", + "fs-extra": "^11.1.1", + "minimatch": "^9.0.3", + "plist": "^3.1.0" }, "engines": { - "node": ">=8.6" + "node": ">=16.4" } }, + "node_modules/@electron/universal/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/@electron/universal/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "balanced-match": "^1.0.0" } }, "node_modules/@electron/universal/node_modules/fs-extra": { - "version": "9.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", - "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", "dev": true, "license": "MIT", "dependencies": { - "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" }, "engines": { - "node": ">=10" + "node": ">=14.14" } }, "node_modules/@electron/universal/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -288,16 +357,19 @@ } }, "node_modules/@electron/universal/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", "dev": true, "license": "ISC", "dependencies": { - "brace-expansion": "^1.1.7" + "brace-expansion": "^2.0.2" }, "engines": { - "node": "*" + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/@electron/universal/node_modules/universalify": { @@ -310,113 +382,89 @@ "node": ">= 10.0.0" } }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", + "node_modules/@electron/windows-sign": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-1.2.2.tgz", + "integrity": "sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==", "dev": true, - "license": "ISC", + "license": "BSD-2-Clause", + "optional": true, + "peer": true, "dependencies": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + "cross-dirname": "^0.1.0", + "debug": "^4.3.4", + "fs-extra": "^11.1.1", + "minimist": "^1.2.8", + "postject": "^1.0.0-alpha.6" + }, + "bin": { + "electron-windows-sign": "bin/electron-windows-sign.js" }, "engines": { - "node": ">=12" + "node": ">=14.14" } }, - "node_modules/@isaacs/cliui/node_modules/ansi-regex": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", - "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "node_modules/@electron/windows-sign/node_modules/fs-extra": { + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", "dev": true, "license": "MIT", - "engines": { - "node": ">=12" + "optional": true, + "peer": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/@isaacs/cliui/node_modules/ansi-styles": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", - "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", - "dev": true, - "license": "MIT", "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" + "node": ">=14.14" } }, - "node_modules/@isaacs/cliui/node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@isaacs/cliui/node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "node_modules/@electron/windows-sign/node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" + "universalify": "^2.0.0" }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "optionalDependencies": { + "graceful-fs": "^4.1.6" } }, - "node_modules/@isaacs/cliui/node_modules/strip-ansi": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", - "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "node_modules/@electron/windows-sign/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", "dev": true, "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, + "optional": true, + "peer": true, "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" + "node": ">= 10.0.0" } }, - "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" + "minipass": "^7.0.4" }, "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + "node": ">=18.0.0" } }, "node_modules/@malept/cross-spawn-promise": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-1.1.1.tgz", - "integrity": "sha512-RTBGWL5FWQcg9orDOCcp4LvItNzUPcyEU9bwaeJX0rJ1IQxzucC48Y0/sQLp/g6t99IQgAlGIaesJS+gTn7tVQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@malept/cross-spawn-promise/-/cross-spawn-promise-2.0.0.tgz", + "integrity": "sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==", "dev": true, "funding": [ { @@ -433,7 +481,7 @@ "cross-spawn": "^7.0.1" }, "engines": { - "node": ">= 10" + "node": ">= 12.13.0" } }, "node_modules/@malept/flatpak-bundler": { @@ -469,9 +517,9 @@ } }, "node_modules/@malept/flatpak-bundler/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -491,17 +539,74 @@ "node": ">= 10.0.0" } }, - "node_modules/@pkgjs/parseargs": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", - "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", "dev": true, "license": "MIT", - "optional": true, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@peculiar/asn1-schema": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@peculiar/asn1-schema/-/asn1-schema-2.11.1.tgz", + "integrity": "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" + }, "engines": { "node": ">=14" } }, + "node_modules/@peculiar/json-schema": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/@peculiar/json-schema/-/json-schema-1.1.12.tgz", + "integrity": "sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@peculiar/utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@peculiar/utils/-/utils-2.0.3.tgz", + "integrity": "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + } + }, + "node_modules/@peculiar/webcrypto": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/@peculiar/webcrypto/-/webcrypto-1.7.2.tgz", + "integrity": "sha512-ktTSACRJ5WdpfjHjFT2EWJQQPacGv1cPCDfEbdmpAHOxdFiYqPe4lfnXGA3D8Dg9/0kHPYSvyRlgujIOVlTdvQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@peculiar/asn1-schema": "^2.7.0", + "@peculiar/json-schema": "^1.1.12", + "@peculiar/utils": "^2.0.2", + "tslib": "^2.8.1", + "webcrypto-core": "^1.9.2" + }, + "engines": { + "node": ">=14.18.0" + } + }, "node_modules/@sindresorhus/is": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz", @@ -528,16 +633,6 @@ "node": ">=10" } }, - "node_modules/@tootallnate/once": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", - "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10" - } - }, "node_modules/@types/cacheable-request": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz", @@ -552,9 +647,9 @@ } }, "node_modules/@types/debug": { - "version": "4.1.12", - "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", - "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==", + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", "dev": true, "license": "MIT", "dependencies": { @@ -605,18 +700,6 @@ "undici-types": "~6.21.0" } }, - "node_modules/@types/plist": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@types/plist/-/plist-3.0.5.tgz", - "integrity": "sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@types/node": "*", - "xmlbuilder": ">=11.0.1" - } - }, "node_modules/@types/responselike": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.3.tgz", @@ -627,14 +710,6 @@ "@types/node": "*" } }, - "node_modules/@types/verror": { - "version": "1.10.11", - "resolved": "https://registry.npmjs.org/@types/verror/-/verror-1.10.11.tgz", - "integrity": "sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg==", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/@types/yauzl": { "version": "2.10.3", "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz", @@ -647,62 +722,52 @@ } }, "node_modules/@xmldom/xmldom": { - "version": "0.8.11", - "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.11.tgz", - "integrity": "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==", + "version": "0.8.15", + "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.15.tgz", + "integrity": "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==", "dev": true, "license": "MIT", "engines": { "node": ">=10.0.0" } }, - "node_modules/7zip-bin": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/7zip-bin/-/7zip-bin-5.2.0.tgz", - "integrity": "sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==", + "node_modules/abbrev": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", + "integrity": "sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==", "dev": true, - "license": "MIT" + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", "dev": true, "license": "MIT", - "dependencies": { - "debug": "4" - }, "engines": { - "node": ">= 6.0.0" + "node": ">= 14" } }, "node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", "dev": true, "license": "MIT", "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" }, "funding": { "type": "github", "url": "https://github.com/sponsors/epoberezkin" } }, - "node_modules/ajv-keywords": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.5.2.tgz", - "integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "ajv": "^6.9.1" - } - }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -729,184 +794,175 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/app-builder-bin": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/app-builder-bin/-/app-builder-bin-4.0.0.tgz", - "integrity": "sha512-xwdG0FJPQMe0M0UA4Tz0zEB8rBJTRA5a476ZawAqiBkMv16GRK5xpXThOjMaEOFnZ6zabejjG4J3da0SXG63KA==", - "dev": true, - "license": "MIT" - }, "node_modules/app-builder-lib": { - "version": "24.13.3", - "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-24.13.3.tgz", - "integrity": "sha512-FAzX6IBit2POXYGnTCT8YHFO/lr5AapAII6zzhQO3Rw4cEDOgK+t1xhLc5tNcKlicTHlo9zxIwnYCX9X2DLkig==", + "version": "26.16.1", + "resolved": "https://registry.npmjs.org/app-builder-lib/-/app-builder-lib-26.16.1.tgz", + "integrity": "sha512-FhaO6YOup01ZfQW0Z6gt3AyukJjv1gW4uFK47jTgwcHZKqyN/fSlK2LqPf9tAeZYLP2bRJLDzeOkRImsw2X4Pg==", "dev": true, "license": "MIT", "dependencies": { - "@develar/schema-utils": "~2.6.5", - "@electron/notarize": "2.2.1", - "@electron/osx-sign": "1.0.5", - "@electron/universal": "1.5.1", + "@electron/asar": "3.4.1", + "@electron/fuses": "^1.8.0", + "@electron/get": "^3.0.0", + "@electron/notarize": "2.5.0", + "@electron/osx-sign": "1.3.3", + "@electron/rebuild": "^4.0.4", + "@electron/universal": "2.0.3", "@malept/flatpak-bundler": "^0.4.0", + "@noble/hashes": "^1.8.0", + "@peculiar/webcrypto": "^1.7.1", "@types/fs-extra": "9.0.13", + "ajv": "^8.18.0", + "asn1js": "^3.0.10", "async-exit-hook": "^2.0.1", - "bluebird-lst": "^1.0.9", - "builder-util": "24.13.1", - "builder-util-runtime": "9.2.4", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", "chromium-pickle-js": "^0.2.0", + "ci-info": "4.3.1", "debug": "^4.3.4", + "dotenv": "^16.4.5", + "dotenv-expand": "^11.0.6", "ejs": "^3.1.8", - "electron-publish": "24.13.1", - "form-data": "^4.0.0", + "electron-publish": "26.16.0", "fs-extra": "^10.1.0", "hosted-git-info": "^4.1.0", - "is-ci": "^3.0.0", "isbinaryfile": "^5.0.0", + "jiti": "^2.4.2", "js-yaml": "^4.1.0", + "json5": "^2.2.3", "lazy-val": "^1.0.5", - "minimatch": "^5.1.1", - "read-config-file": "6.3.2", - "sanitize-filename": "^1.6.3", - "semver": "^7.3.8", - "tar": "^6.1.12", - "temp-file": "^3.4.0" + "minimatch": "^10.2.5", + "pkijs": "^3.4.0", + "plist": "3.1.0", + "proper-lockfile": "^4.1.2", + "resedit": "^1.7.0", + "semver": "~7.7.3", + "tar": "^7.5.7", + "temp-file": "^3.4.0", + "tiny-async-pool": "1.3.0", + "unzipper": "^0.12.3", + "which": "^5.0.0" }, "engines": { "node": ">=14.0.0" }, "peerDependencies": { - "dmg-builder": "24.13.3", - "electron-builder-squirrel-windows": "24.13.3" + "dmg-builder": "26.16.1", + "electron-builder-squirrel-windows": "26.16.1" } }, - "node_modules/app-builder-lib/node_modules/fs-extra": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", - "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "node_modules/app-builder-lib/node_modules/@electron/get": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@electron/get/-/get-3.1.0.tgz", + "integrity": "sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==", "dev": true, "license": "MIT", "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=12" + "debug": "^4.1.1", + "env-paths": "^2.2.0", + "fs-extra": "^8.1.0", + "got": "^11.8.5", + "progress": "^2.0.3", + "semver": "^6.2.0", + "sumchecker": "^3.0.1" + }, + "engines": { + "node": ">=14" + }, + "optionalDependencies": { + "global-agent": "^3.0.0" } }, - "node_modules/app-builder-lib/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", "dev": true, "license": "MIT", "dependencies": { - "universalify": "^2.0.0" + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" }, - "optionalDependencies": { - "graceful-fs": "^4.1.6" + "engines": { + "node": ">=6 <7 || >=8" } }, - "node_modules/app-builder-lib/node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "node_modules/app-builder-lib/node_modules/@electron/get/node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "dev": true, "license": "ISC", "bin": { "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" } }, - "node_modules/app-builder-lib/node_modules/universalify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", - "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "node_modules/app-builder-lib/node_modules/ci-info": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz", + "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], "license": "MIT", "engines": { - "node": ">= 10.0.0" + "node": ">=8" } }, - "node_modules/archiver": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/archiver/-/archiver-5.3.2.tgz", - "integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==", + "node_modules/app-builder-lib/node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "archiver-utils": "^2.1.0", - "async": "^3.2.4", - "buffer-crc32": "^0.2.1", - "readable-stream": "^3.6.0", - "readdir-glob": "^1.1.2", - "tar-stream": "^2.2.0", - "zip-stream": "^4.1.0" + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" }, "engines": { - "node": ">= 10" + "node": ">=12" } }, - "node_modules/archiver-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-2.1.0.tgz", - "integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==", + "node_modules/app-builder-lib/node_modules/fs-extra/node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "glob": "^7.1.4", - "graceful-fs": "^4.2.0", - "lazystream": "^1.0.0", - "lodash.defaults": "^4.2.0", - "lodash.difference": "^4.5.0", - "lodash.flatten": "^4.4.0", - "lodash.isplainobject": "^4.0.6", - "lodash.union": "^4.6.0", - "normalize-path": "^3.0.0", - "readable-stream": "^2.0.0" + "universalify": "^2.0.0" }, - "engines": { - "node": ">= 6" + "optionalDependencies": { + "graceful-fs": "^4.1.6" } }, - "node_modules/archiver-utils/node_modules/readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "node_modules/app-builder-lib/node_modules/fs-extra/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", "dev": true, "license": "MIT", - "peer": true, - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" + "engines": { + "node": ">= 10.0.0" } }, - "node_modules/archiver-utils/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/archiver-utils/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "node_modules/app-builder-lib/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "safe-buffer": "~5.1.0" + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, "node_modules/argparse": { @@ -916,26 +972,19 @@ "dev": true, "license": "Python-2.0" }, - "node_modules/assert-plus": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", - "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.8" - } - }, - "node_modules/astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "node_modules/asn1js": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz", + "integrity": "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA==", "dev": true, - "license": "MIT", - "optional": true, + "license": "BSD-3-Clause", + "dependencies": { + "pvtsutils": "^1.3.6", + "pvutils": "^1.2.0", + "tslib": "^2.8.1" + }, "engines": { - "node": ">=8" + "node": ">=12.0.0" } }, "node_modules/async": { @@ -972,13 +1021,23 @@ "node": ">= 4.0.0" } }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "node_modules/aws4": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz", + "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==", "dev": true, "license": "MIT" }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", @@ -1000,19 +1059,6 @@ ], "license": "MIT" }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, "node_modules/bluebird": { "version": "3.7.2", "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", @@ -1020,16 +1066,6 @@ "dev": true, "license": "MIT" }, - "node_modules/bluebird-lst": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/bluebird-lst/-/bluebird-lst-1.0.9.tgz", - "integrity": "sha512-7B1Rtx82hjnSD4PGLAjVWeYH3tHAcVUmChh85a3lltKQm6FresXh9ErQo6oAv6CqxttczC3/kEg8SY5NluPuUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "bluebird": "^3.5.5" - } - }, "node_modules/boolean": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz", @@ -1040,38 +1076,16 @@ "optional": true }, "node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], "license": "MIT", "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" } }, "node_modules/buffer-crc32": { @@ -1084,19 +1098,6 @@ "node": "*" } }, - "node_modules/buffer-equal": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-1.0.1.tgz", - "integrity": "sha512-QoV3ptgEaQpvVwbXdSO39iqPQTCxSF7A5U99AxbHYqUdCizL/lH2Z0A2y6nbZucxMEOtNyZfG2s6gsVugGpKkg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -1105,34 +1106,35 @@ "license": "MIT" }, "node_modules/builder-util": { - "version": "24.13.1", - "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-24.13.1.tgz", - "integrity": "sha512-NhbCSIntruNDTOVI9fdXz0dihaqX2YuE1D6zZMrwiErzH4ELZHE6mdiB40wEgZNprDia+FghRFgKoAqMZRRjSA==", + "version": "26.16.0", + "resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.16.0.tgz", + "integrity": "sha512-RLyJhB7Si3YkzKR9ubQslWuXW3Vhs3CGe1i+SeixBZ0qTd1mk3XBmssvY22TlB6CS5blyko8Gu1JzpYk8UkYAg==", "dev": true, "license": "MIT", "dependencies": { "@types/debug": "^4.1.6", - "7zip-bin": "~5.2.0", - "app-builder-bin": "4.0.0", - "bluebird-lst": "^1.0.9", - "builder-util-runtime": "9.2.4", + "builder-util-runtime": "9.7.0", "chalk": "^4.1.2", - "cross-spawn": "^7.0.3", + "cross-spawn": "^7.0.6", "debug": "^4.3.4", "fs-extra": "^10.1.0", - "http-proxy-agent": "^5.0.0", - "https-proxy-agent": "^5.0.1", - "is-ci": "^3.0.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.0", "js-yaml": "^4.1.0", + "sanitize-filename": "^1.6.3", "source-map-support": "^0.5.19", "stat-mode": "^1.0.0", - "temp-file": "^3.4.0" + "temp-file": "^3.4.0", + "tiny-async-pool": "1.3.0" + }, + "engines": { + "node": ">=14.0.0" } }, "node_modules/builder-util-runtime": { - "version": "9.2.4", - "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.2.4.tgz", - "integrity": "sha512-upp+biKpN/XZMLim7aguUyW8s0FUpDvOtK6sbanMFDAMBzpHDqdhgVYm6zc9HJ6nWo7u2Lxk60i2M6Jd3aiNrA==", + "version": "9.7.0", + "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz", + "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==", "dev": true, "license": "MIT", "dependencies": { @@ -1159,9 +1161,9 @@ } }, "node_modules/builder-util/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -1181,6 +1183,16 @@ "node": ">= 10.0.0" } }, + "node_modules/bytestreamjs": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/bytestreamjs/-/bytestreamjs-2.0.1.tgz", + "integrity": "sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/cacheable-lookup": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", @@ -1242,13 +1254,13 @@ } }, "node_modules/chownr": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", - "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { - "node": ">=10" + "node": ">=18" } }, "node_modules/chromium-pickle-js": { @@ -1259,9 +1271,9 @@ "license": "MIT" }, "node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", "dev": true, "funding": [ { @@ -1274,24 +1286,6 @@ "node": ">=8" } }, - "node_modules/cli-truncate": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", - "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "slice-ansi": "^3.0.0", - "string-width": "^4.2.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -1373,23 +1367,6 @@ "node": ">=0.10.0" } }, - "node_modules/compress-commons": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-4.1.2.tgz", - "integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "buffer-crc32": "^0.2.13", - "crc32-stream": "^4.0.2", - "normalize-path": "^3.0.0", - "readable-stream": "^3.6.0" - }, - "engines": { - "node": ">= 10" - } - }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -1397,130 +1374,64 @@ "dev": true, "license": "MIT" }, - "node_modules/config-file-ts": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/config-file-ts/-/config-file-ts-0.2.6.tgz", - "integrity": "sha512-6boGVaglwblBgJqGyxm4+xCmEGcWgnWHSWHY5jad58awQhB6gftq0G8HbzU39YqCIYHMLAiL1yjwiZ36m/CL8w==", + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-dirname": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz", + "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "license": "MIT", "dependencies": { - "glob": "^10.3.10", - "typescript": "^5.3.3" + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" } }, - "node_modules/config-file-ts/node_modules/glob": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", - "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "node_modules/cross-spawn/node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/cross-spawn/node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dev": true, "license": "ISC", "dependencies": { - "foreground-child": "^3.1.0", - "jackspeak": "^3.1.2", - "minimatch": "^9.0.4", - "minipass": "^7.1.2", - "package-json-from-dist": "^1.0.0", - "path-scurry": "^1.11.1" + "isexe": "^2.0.0" }, "bin": { - "glob": "dist/esm/bin.mjs" + "node-which": "bin/node-which" }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "engines": { + "node": ">= 8" } }, - "node_modules/config-file-ts/node_modules/minimatch": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", - "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/config-file-ts/node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/core-util-is": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/crc": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/crc/-/crc-3.8.0.tgz", - "integrity": "sha512-iX3mfgcTMIq3ZKLIsVFAbv7+Mc10kxabAGQb8HvjA1o3T1PIYprbakQ65d3I+2HGHt6nSKkM9PYjgoJO2KcFBQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "buffer": "^5.1.0" - } - }, - "node_modules/crc-32": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", - "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", - "dev": true, - "license": "Apache-2.0", - "peer": true, - "bin": { - "crc32": "bin/crc32.njs" - }, - "engines": { - "node": ">=0.8" - } - }, - "node_modules/crc32-stream": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-4.0.3.tgz", - "integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "crc-32": "^1.2.0", - "readable-stream": "^3.4.0" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { @@ -1631,20 +1542,27 @@ "optional": true }, "node_modules/dir-compare": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-3.3.0.tgz", - "integrity": "sha512-J7/et3WlGUCxjdnD3HAAzQ6nsnc0WL6DD7WcwJb7c39iH1+AWfg+9OqzJNaI6PkBwBvm1mhZNL9iY/nRiZXlPg==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz", + "integrity": "sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==", "dev": true, "license": "MIT", "dependencies": { - "buffer-equal": "^1.0.0", - "minimatch": "^3.0.4" + "minimatch": "^3.0.5", + "p-limit": "^3.1.0 " } }, + "node_modules/dir-compare/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/dir-compare/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -1653,9 +1571,9 @@ } }, "node_modules/dir-compare/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -1666,21 +1584,16 @@ } }, "node_modules/dmg-builder": { - "version": "24.13.3", - "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-24.13.3.tgz", - "integrity": "sha512-rcJUkMfnJpfCboZoOOPf4L29TRtEieHNOeAbYPWPxlaBw/Z1RKrRA86dOI9rwaI4tQSc/RD82zTNHprfUHXsoQ==", + "version": "26.16.1", + "resolved": "https://registry.npmjs.org/dmg-builder/-/dmg-builder-26.16.1.tgz", + "integrity": "sha512-pnI/3Qb24Uk+rMTgIUrsVUKosVgwmBUdF8Zeb8TexOSbpq8MWc7v6l+n+FrEqVkjNZwzBN+XpDS9ENgZ/rkWAw==", "dev": true, "license": "MIT", "dependencies": { - "app-builder-lib": "24.13.3", - "builder-util": "24.13.1", - "builder-util-runtime": "9.2.4", + "app-builder-lib": "26.16.1", + "builder-util": "26.16.0", "fs-extra": "^10.1.0", - "iconv-lite": "^0.6.2", "js-yaml": "^4.1.0" - }, - "optionalDependencies": { - "dmg-license": "^1.0.11" } }, "node_modules/dmg-builder/node_modules/fs-extra": { @@ -1699,9 +1612,9 @@ } }, "node_modules/dmg-builder/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -1721,49 +1634,34 @@ "node": ">= 10.0.0" } }, - "node_modules/dmg-license": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/dmg-license/-/dmg-license-1.0.11.tgz", - "integrity": "sha512-ZdzmqwKmECOWJpqefloC5OJy1+WZBBse5+MR88z9g9Zn4VY+WYUkAyojmhzJckH5YbbZGcYIuGAkY5/Ys5OM2Q==", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "@types/plist": "^3.0.1", - "@types/verror": "^1.10.3", - "ajv": "^6.10.0", - "crc": "^3.8.0", - "iconv-corefoundation": "^1.1.7", - "plist": "^3.0.4", - "smart-buffer": "^4.0.2", - "verror": "^1.10.0" - }, - "bin": { - "dmg-license": "bin/dmg-license.js" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/dotenv": { - "version": "9.0.2", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-9.0.2.tgz", - "integrity": "sha512-I9OvvrHp4pIARv4+x9iuewrWycX6CcZtoAu1XrzPxc5UygMJXJZYmBsynku8IkrJwgypE5DGNjDPmPRhDCptUg==", + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", "dev": true, "license": "BSD-2-Clause", "engines": { - "node": ">=10" + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" } }, "node_modules/dotenv-expand": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-5.1.0.tgz", - "integrity": "sha512-YXQl1DSa4/PQyRfgrv6aoNjhasp/p4qs9FjJ4q4cQk+8m4r6k4ZSiEyytKG8f8W9gi8WsQtIObNmKd+tMzNTmA==", + "version": "11.0.7", + "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-11.0.7.tgz", + "integrity": "sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==", "dev": true, - "license": "BSD-2-Clause" + "license": "BSD-2-Clause", + "dependencies": { + "dotenv": "^16.4.5" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } }, "node_modules/dunder-proto": { "version": "1.0.1", @@ -1780,12 +1678,15 @@ "node": ">= 0.4" } }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", - "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "node_modules/duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", "dev": true, - "license": "MIT" + "license": "BSD-3-Clause", + "dependencies": { + "readable-stream": "^2.0.2" + } }, "node_modules/ejs": { "version": "3.1.10", @@ -1823,21 +1724,20 @@ } }, "node_modules/electron-builder": { - "version": "24.13.3", - "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-24.13.3.tgz", - "integrity": "sha512-yZSgVHft5dNVlo31qmJAe4BVKQfFdwpRw7sFp1iQglDRCDD6r22zfRJuZlhtB5gp9FHUxCMEoWGq10SkCnMAIg==", + "version": "26.16.1", + "resolved": "https://registry.npmjs.org/electron-builder/-/electron-builder-26.16.1.tgz", + "integrity": "sha512-LrLK65QX5PUYYODXqp23FKrV7CILTtVY7mrJckNknO9jLNSMiqFkKbSMiDRw4CjOADMPVDdWLxY4mezOZWswxg==", "dev": true, "license": "MIT", "dependencies": { - "app-builder-lib": "24.13.3", - "builder-util": "24.13.1", - "builder-util-runtime": "9.2.4", + "app-builder-lib": "26.16.1", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", "chalk": "^4.1.2", - "dmg-builder": "24.13.3", + "ci-info": "^4.2.0", + "dmg-builder": "26.16.1", "fs-extra": "^10.1.0", - "is-ci": "^3.0.0", "lazy-val": "^1.0.5", - "read-config-file": "6.3.2", "simple-update-notifier": "2.0.0", "yargs": "^17.6.2" }, @@ -1850,58 +1750,16 @@ } }, "node_modules/electron-builder-squirrel-windows": { - "version": "24.13.3", - "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-24.13.3.tgz", - "integrity": "sha512-oHkV0iogWfyK+ah9ZIvMDpei1m9ZRpdXcvde1wTpra2U8AFDNNpqJdnin5z+PM1GbQ5BoaKCWas2HSjtR0HwMg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "app-builder-lib": "24.13.3", - "archiver": "^5.3.1", - "builder-util": "24.13.1", - "fs-extra": "^10.1.0" - } - }, - "node_modules/electron-builder-squirrel-windows/node_modules/fs-extra": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", - "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/electron-builder-squirrel-windows/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "26.16.1", + "resolved": "https://registry.npmjs.org/electron-builder-squirrel-windows/-/electron-builder-squirrel-windows-26.16.1.tgz", + "integrity": "sha512-w0y44wSaT1l6R7CAGmeHn4nHPfvzDyCAU1xJyi1w9SbPYJpYn76SmHDzqHf8Y7l91cPWTdPYBpGQtB2T5mJ08A==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "universalify": "^2.0.0" - }, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/electron-builder-squirrel-windows/node_modules/universalify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", - "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", - "dev": true, - "license": "MIT", - "peer": true, - "engines": { - "node": ">= 10.0.0" + "app-builder-lib": "26.16.1", + "builder-util": "26.16.0", + "electron-winstaller": "5.4.0" } }, "node_modules/electron-builder/node_modules/fs-extra": { @@ -1952,16 +1810,18 @@ } }, "node_modules/electron-publish": { - "version": "24.13.1", - "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-24.13.1.tgz", - "integrity": "sha512-2ZgdEqJ8e9D17Hwp5LEq5mLQPjqU3lv/IALvgp+4W8VeNhryfGhYEQC/PgDPMrnWUp+l60Ou5SJLsu+k4mhQ8A==", + "version": "26.16.0", + "resolved": "https://registry.npmjs.org/electron-publish/-/electron-publish-26.16.0.tgz", + "integrity": "sha512-Vt3KzQIiw9BImvNOYtndg9Mjki+tl4+1sQiC/+G5j8khWaENOJFWodiB+sUl6yyHwtd37avehskdtPw7f8y/+Q==", "dev": true, "license": "MIT", "dependencies": { "@types/fs-extra": "^9.0.11", - "builder-util": "24.13.1", - "builder-util-runtime": "9.2.4", + "aws4": "^1.13.2", + "builder-util": "26.16.0", + "builder-util-runtime": "9.7.0", "chalk": "^4.1.2", + "form-data": "^4.0.5", "fs-extra": "^10.1.0", "lazy-val": "^1.0.5", "mime": "^2.5.2" @@ -1983,9 +1843,9 @@ } }, "node_modules/electron-publish/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -2005,6 +1865,44 @@ "node": ">= 10.0.0" } }, + "node_modules/electron-winstaller": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/electron-winstaller/-/electron-winstaller-5.4.0.tgz", + "integrity": "sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@electron/asar": "^3.2.1", + "debug": "^4.1.1", + "fs-extra": "^7.0.1", + "lodash": "^4.17.21", + "temp": "^0.9.0" + }, + "engines": { + "node": ">=8.0.0" + }, + "optionalDependencies": { + "@electron/windows-sign": "^1.1.2" + } + }, + "node_modules/electron-winstaller/node_modules/fs-extra": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", + "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, "node_modules/electron/node_modules/@types/node": { "version": "18.19.130", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", @@ -2077,9 +1975,9 @@ } }, "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", "dev": true, "license": "MIT", "dependencies": { @@ -2137,6 +2035,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/exponential-backoff": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", + "integrity": "sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/extract-zip": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", @@ -2158,17 +2063,6 @@ "@types/yauzl": "^2.9.1" } }, - "node_modules/extsprintf": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.4.1.tgz", - "integrity": "sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==", - "dev": true, - "engines": [ - "node >=0.6.0" - ], - "license": "MIT", - "optional": true - }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -2176,12 +2070,22 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, - "license": "MIT" + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" }, "node_modules/fd-slicer": { "version": "1.1.0", @@ -2193,58 +2097,81 @@ "pend": "~1.2.0" } }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, "node_modules/filelist": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", - "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz", + "integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==", "dev": true, "license": "Apache-2.0", "dependencies": { "minimatch": "^5.0.1" } }, - "node_modules/foreground-child": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", - "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "node_modules/filelist/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/filelist/node_modules/brace-expansion": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/filelist/node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", "dev": true, "license": "ISC", "dependencies": { - "cross-spawn": "^7.0.6", - "signal-exit": "^4.0.1" + "brace-expansion": "^2.0.1" }, "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": ">=10" } }, "node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" } }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/fs-extra": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", @@ -2260,43 +2187,17 @@ "node": ">=6 <7 || >=8" } }, - "node_modules/fs-minipass": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", - "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } + "license": "ISC" }, - "node_modules/fs-minipass/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "license": "ISC" - }, - "node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -2387,7 +2288,7 @@ "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", "dev": true, "license": "ISC", "dependencies": { @@ -2405,10 +2306,17 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/glob/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, "node_modules/glob/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "version": "1.1.21", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", + "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", "dev": true, "license": "MIT", "dependencies": { @@ -2417,9 +2325,9 @@ } }, "node_modules/glob/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", "dev": true, "license": "ISC", "dependencies": { @@ -2580,9 +2488,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "dev": true, "license": "MIT", "dependencies": { @@ -2613,18 +2521,17 @@ "license": "BSD-2-Clause" }, "node_modules/http-proxy-agent": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", - "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", "dev": true, "license": "MIT", "dependencies": { - "@tootallnate/once": "2", - "agent-base": "6", - "debug": "4" + "agent-base": "^7.1.0", + "debug": "^4.3.4" }, "engines": { - "node": ">= 6" + "node": ">= 14" } }, "node_modules/http2-wrapper": { @@ -2642,71 +2549,19 @@ } }, "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", "dev": true, "license": "MIT", "dependencies": { - "agent-base": "6", + "agent-base": "^7.1.2", "debug": "4" }, "engines": { - "node": ">= 6" - } - }, - "node_modules/iconv-corefoundation": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/iconv-corefoundation/-/iconv-corefoundation-1.1.7.tgz", - "integrity": "sha512-T10qvkw0zz4wnm560lOEg0PovVqUXuOFhhHAkixw8/sycy7TJt7v/RrkEKEQnAw2viPSJu6iAkErxnzR0g8PpQ==", - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "dependencies": { - "cli-truncate": "^2.1.0", - "node-addon-api": "^1.6.3" - }, - "engines": { - "node": "^8.11.2 || >=10" - } - }, - "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" + "node": ">= 14" } }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -2726,19 +2581,6 @@ "dev": true, "license": "ISC" }, - "node_modules/is-ci": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-3.0.1.tgz", - "integrity": "sha512-ZYvCgrefwqoQ6yTyYUbQu64HsITZ3NfKX1lzaEYdkTDcfKzzCI/wthRRYKkdjHKFVgNiXKAKm65Zo1pk2as/QQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ci-info": "^3.2.0" - }, - "bin": { - "is-ci": "bin.js" - } - }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -2754,8 +2596,7 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/isbinaryfile": { "version": "5.0.7", @@ -2771,26 +2612,13 @@ } }, "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/jackspeak": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", - "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz", + "integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==", "dev": true, "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/cliui": "^8.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "optionalDependencies": { - "@pkgjs/parseargs": "^0.11.0" + "engines": { + "node": ">=18" } }, "node_modules/jake": { @@ -2811,11 +2639,31 @@ "node": ">=10" } }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -2832,9 +2680,9 @@ "license": "MIT" }, "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "dev": true, "license": "MIT" }, @@ -2886,103 +2734,13 @@ "dev": true, "license": "MIT" }, - "node_modules/lazystream": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz", - "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "readable-stream": "^2.0.5" - }, - "engines": { - "node": ">= 0.6.3" - } - }, - "node_modules/lazystream/node_modules/readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/lazystream/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/lazystream/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, "node_modules/lodash": { - "version": "4.17.23", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", - "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", "dev": true, "license": "MIT" }, - "node_modules/lodash.defaults": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", - "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/lodash.difference": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz", - "integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/lodash.flatten": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz", - "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", - "dev": true, - "license": "MIT", - "peer": true - }, - "node_modules/lodash.union": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz", - "integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==", - "dev": true, - "license": "MIT", - "peer": true - }, "node_modules/lowercase-keys": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", @@ -3077,16 +2835,19 @@ } }, "node_modules/minimatch": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", - "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^2.0.1" + "brace-expansion": "^5.0.8" }, "engines": { - "node": ">=10" + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/minimist": { @@ -3100,79 +2861,183 @@ } }, "node_modules/minipass": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", - "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "engines": { - "node": ">=8" + "node": ">=16 || 14 >=14.17" } }, "node_modules/minizlib": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", - "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", "dev": true, "license": "MIT", "dependencies": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" + "minipass": "^7.1.2" }, "engines": { - "node": ">= 8" + "node": ">= 18" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-abi": { + "version": "4.40.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.40.0.tgz", + "integrity": "sha512-GuvqvtrOk+AC27RidBxBsMzVNkwNl7PjHgc4NXbmdvSVLgIUjpaqcG1FjNRYnt2Yn9Ytq+Ln37XsBaglUcte/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.6.3" + }, + "engines": { + "node": ">=22.12.0" } }, - "node_modules/minizlib/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "node_modules/node-abi/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-api-version": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/node-api-version/-/node-api-version-0.2.1.tgz", + "integrity": "sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==", + "dev": true, + "license": "MIT", "dependencies": { - "yallist": "^4.0.0" + "semver": "^7.3.5" + } + }, + "node_modules/node-api-version/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" }, "engines": { - "node": ">=8" + "node": ">=10" } }, - "node_modules/mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "node_modules/node-gyp": { + "version": "12.4.0", + "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz", + "integrity": "sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==", "dev": true, "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "graceful-fs": "^4.2.6", + "nopt": "^9.0.0", + "proc-log": "^6.0.0", + "semver": "^7.3.5", + "tar": "^7.5.4", + "tinyglobby": "^0.2.12", + "undici": "^6.25.0", + "which": "^6.0.0" + }, "bin": { - "mkdirp": "bin/cmd.js" + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/node-gyp/node_modules/isexe": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz", + "integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=20" + } + }, + "node_modules/node-gyp/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" }, "engines": { "node": ">=10" } }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "node_modules/node-gyp/node_modules/which": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz", + "integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==", "dev": true, - "license": "MIT" + "license": "ISC", + "dependencies": { + "isexe": "^4.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^20.17.0 || >=22.9.0" + } }, - "node_modules/node-addon-api": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-1.7.2.tgz", - "integrity": "sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg==", + "node_modules/node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", "dev": true, - "license": "MIT", - "optional": true + "license": "MIT" }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "node_modules/nopt": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-9.0.0.tgz", + "integrity": "sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==", "dev": true, - "license": "MIT", - "peer": true, + "license": "ISC", + "dependencies": { + "abbrev": "^4.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, "engines": { - "node": ">=0.10.0" + "node": "^20.17.0 || >=22.9.0" } }, "node_modules/normalize-url": { @@ -3219,12 +3084,21 @@ "node": ">=8" } }, - "node_modules/package-json-from-dist": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", - "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, - "license": "BlueOak-1.0.0" + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, "node_modules/path-is-absolute": { "version": "1.0.1", @@ -3246,30 +3120,21 @@ "node": ">=8" } }, - "node_modules/path-scurry": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", - "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "node_modules/pe-library": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz", + "integrity": "sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==", "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^10.2.0", - "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" - }, + "license": "MIT", "engines": { - "node": ">=16 || 14 >=14.18" + "node": ">=12", + "npm": ">=6" }, "funding": { - "url": "https://github.com/sponsors/isaacs" + "type": "github", + "url": "https://github.com/sponsors/jet2jet" } }, - "node_modules/path-scurry/node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, - "license": "ISC" - }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -3284,6 +3149,40 @@ "dev": true, "license": "ISC" }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkijs": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.3.tgz", + "integrity": "sha512-V9kOzaItwDgqlryhXysQsAXUEKi5O7kqWUaP3dXI7MLvkPqWWMb4wVb1QAtmEDCKI+XIAINsZoNKMFF7sZb1eg==", + "dev": true, + "license": "BSD-3-Clause", + "workspaces": [ + "website" + ], + "dependencies": { + "@noble/hashes": "1.8.0", + "asn1js": "^3.0.6", + "bytestreamjs": "^2.0.1", + "pvtsutils": "^1.3.6", + "pvutils": "^1.1.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/playwright": { "version": "1.48.2", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.48.2.tgz", @@ -3331,13 +3230,52 @@ "node": ">=10.4.0" } }, + "node_modules/postject": { + "version": "1.0.0-alpha.6", + "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz", + "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "commander": "^9.4.0" + }, + "bin": { + "postject": "dist/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/postject/node_modules/commander": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", + "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": "^12.20.0 || >=14" + } + }, + "node_modules/proc-log": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-6.1.0.tgz", + "integrity": "sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, "node_modules/process-nextick-args": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/progress": { "version": "2.0.3", @@ -3363,6 +3301,18 @@ "node": ">=10" } }, + "node_modules/proper-lockfile": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", + "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "retry": "^0.12.0", + "signal-exit": "^3.0.2" + } + }, "node_modules/pump": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", @@ -3374,72 +3324,66 @@ "once": "^1.3.1" } }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "node_modules/pvtsutils": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz", + "integrity": "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==", "dev": true, "license": "MIT", - "engines": { - "node": ">=6" + "dependencies": { + "tslib": "^2.8.1" } }, - "node_modules/quick-lru": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", - "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==", + "node_modules/pvutils": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pvutils/-/pvutils-1.2.0.tgz", + "integrity": "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==", "dev": true, "license": "MIT", "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=16.0.0" } }, - "node_modules/read-config-file": { - "version": "6.3.2", - "resolved": "https://registry.npmjs.org/read-config-file/-/read-config-file-6.3.2.tgz", - "integrity": "sha512-M80lpCjnE6Wt6zb98DoW8WHR09nzMSpu8XHtPkiTHrJ5Az9CybfeQhTJ8D7saeBHpGhLPIVyA8lcL6ZmdKwY6Q==", + "node_modules/quick-lru": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz", + "integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==", "dev": true, "license": "MIT", - "dependencies": { - "config-file-ts": "^0.2.4", - "dotenv": "^9.0.2", - "dotenv-expand": "^5.1.0", - "js-yaml": "^4.1.0", - "json5": "^2.2.0", - "lazy-val": "^1.0.4" - }, "engines": { - "node": ">=12.0.0" + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "node_modules/read-binary-file-arch": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz", + "integrity": "sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" + "debug": "^4.3.4" }, - "engines": { - "node": ">= 6" + "bin": { + "read-binary-file-arch": "cli.js" } }, - "node_modules/readdir-glob": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz", - "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==", + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", "dev": true, - "license": "Apache-2.0", - "peer": true, + "license": "MIT", "dependencies": { - "minimatch": "^5.1.0" + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" } }, "node_modules/require-directory": { @@ -3452,6 +3396,34 @@ "node": ">=0.10.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resedit": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/resedit/-/resedit-1.7.2.tgz", + "integrity": "sha512-vHjcY2MlAITJhC0eRD/Vv8Vlgmu9Sd3LX9zZvtGzU5ZImdTN3+d6e/4mnTyV8vEbyf1sgNIrWxhWlrys52OkEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "pe-library": "^0.4.1" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jet2jet" + } + }, "node_modules/resolve-alpn": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz", @@ -3482,6 +3454,21 @@ "node": ">= 4" } }, + "node_modules/rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dev": true, + "license": "ISC", + "peer": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, "node_modules/roarr": { "version": "2.15.4", "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", @@ -3502,38 +3489,16 @@ } }, "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "peer": true - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", "dev": true, "license": "MIT" }, "node_modules/sanitize-filename": { - "version": "1.6.3", - "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.3.tgz", - "integrity": "sha512-y/52Mcy7aw3gRm7IrcGDFx/bCk4AhRh2eI9luHOQM86nZsqwiRkkq2GekHXBBD+SmPidc8i2PqtYZl+pWJ8Oeg==", + "version": "1.6.5", + "resolved": "https://registry.npmjs.org/sanitize-filename/-/sanitize-filename-1.6.5.tgz", + "integrity": "sha512-+dVApt46/oAFWRP0KBSnYNLRw1peY7o/b12tmpllPNFpjfwkPuZut1+DiKaD9zYx5r2SHwc+XMLSBaDiyUJw3g==", "dev": true, "license": "WTFPL OR ISC", "dependencies": { @@ -3541,9 +3506,9 @@ } }, "node_modules/sax": { - "version": "1.4.4", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.4.tgz", - "integrity": "sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz", + "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==", "dev": true, "license": "BlueOak-1.0.0", "engines": { @@ -3623,17 +3588,11 @@ } }, "node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } + "license": "ISC" }, "node_modules/simple-update-notifier": { "version": "2.0.0", @@ -3661,34 +3620,6 @@ "node": ">=10" } }, - "node_modules/slice-ansi": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", - "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/smart-buffer": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", - "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 6.0.0", - "npm": ">= 3.0.0" - } - }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -3729,14 +3660,13 @@ } }, "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { - "safe-buffer": "~5.2.0" + "safe-buffer": "~5.1.0" } }, "node_modules/string-width": { @@ -3754,22 +3684,6 @@ "node": ">=8" } }, - "node_modules/string-width-cjs": { - "name": "string-width", - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -3783,20 +3697,6 @@ "node": ">=8" } }, - "node_modules/strip-ansi-cjs": { - "name": "strip-ansi", - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/sumchecker": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz", @@ -3824,40 +3724,45 @@ } }, "node_modules/tar": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", - "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", - "deprecated": "Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exhorbitant rates) by contacting i@izs.me", + "version": "7.5.22", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", + "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^5.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" }, "engines": { - "node": ">=10" + "node": ">=18" + } + }, + "node_modules/tar/node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" } }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "node_modules/temp": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/temp/-/temp-0.9.4.tgz", + "integrity": "sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==", "dev": true, "license": "MIT", "peer": true, "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" + "mkdirp": "^0.5.1", + "rimraf": "~2.6.2" }, "engines": { - "node": ">=6" + "node": ">=6.0.0" } }, "node_modules/temp-file": { @@ -3887,9 +3792,9 @@ } }, "node_modules/temp-file/node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", "dev": true, "license": "MIT", "dependencies": { @@ -3909,10 +3814,47 @@ "node": ">= 10.0.0" } }, + "node_modules/tiny-async-pool": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz", + "integrity": "sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^5.5.0" + } + }, + "node_modules/tiny-async-pool/node_modules/semver": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.3.tgz", + "integrity": "sha512-kM18BPOqTi0+TB68703/GJRpAML5Me+IDQsR1J26YB3EFKKNEyHIVZuWDX7+WKQB3tHwDwgk24BfhdpWUbytvQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, "node_modules/tmp": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", - "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", "dev": true, "license": "MIT", "engines": { @@ -3939,6 +3881,13 @@ "utf8-byte-length": "^1.0.1" } }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD" + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -3953,6 +3902,16 @@ "node": ">=14.17" } }, + "node_modules/undici": { + "version": "6.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", + "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, "node_modules/undici-types": { "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", @@ -3970,14 +3929,56 @@ "node": ">= 4.0.0" } }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "node_modules/unzipper": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz", + "integrity": "sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==", "dev": true, - "license": "BSD-2-Clause", + "license": "MIT", + "dependencies": { + "bluebird": "~3.7.2", + "duplexer2": "~0.1.4", + "fs-extra": "11.3.1", + "graceful-fs": "^4.2.2", + "node-int64": "^0.4.0" + } + }, + "node_modules/unzipper/node_modules/fs-extra": { + "version": "11.3.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.1.tgz", + "integrity": "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/unzipper/node_modules/jsonfile": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", + "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==", + "dev": true, + "license": "MIT", "dependencies": { - "punycode": "^2.1.0" + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/unzipper/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" } }, "node_modules/utf8-byte-length": { @@ -3992,39 +3993,36 @@ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, - "node_modules/verror": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.1.tgz", - "integrity": "sha512-veufcmxri4e3XSrT0xwfUR7kguIkaxBeosDg00yDWhk49wdwkSUrvvsm7nc75e1PUyvIeZj6nS8VQRYz2/S4Xg==", + "node_modules/webcrypto-core": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz", + "integrity": "sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==", "dev": true, "license": "MIT", - "optional": true, "dependencies": { - "assert-plus": "^1.0.0", - "core-util-is": "1.0.2", - "extsprintf": "^1.2.0" - }, - "engines": { - "node": ">=0.6.0" + "@peculiar/asn1-schema": "^2.7.0", + "@peculiar/json-schema": "^1.1.12", + "@peculiar/utils": "^2.0.2", + "asn1js": "^3.0.10", + "tslib": "^2.8.1" } }, "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz", + "integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==", "dev": true, "license": "ISC", "dependencies": { - "isexe": "^2.0.0" + "isexe": "^3.1.1" }, "bin": { - "node-which": "bin/node-which" + "node-which": "bin/which.js" }, "engines": { - "node": ">= 8" + "node": "^18.17.0 || >=20.5.0" } }, "node_modules/wrap-ansi": { @@ -4045,25 +4043,6 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/wrap-ansi-cjs": { - "name": "wrap-ansi", - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -4138,43 +4117,17 @@ "fd-slicer": "~1.1.0" } }, - "node_modules/zip-stream": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz", - "integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==", + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true, "license": "MIT", - "peer": true, - "dependencies": { - "archiver-utils": "^3.0.4", - "compress-commons": "^4.1.2", - "readable-stream": "^3.6.0" - }, "engines": { - "node": ">= 10" - } - }, - "node_modules/zip-stream/node_modules/archiver-utils": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-3.0.4.tgz", - "integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==", - "dev": true, - "license": "MIT", - "peer": true, - "dependencies": { - "glob": "^7.2.3", - "graceful-fs": "^4.2.0", - "lazystream": "^1.0.0", - "lodash.defaults": "^4.2.0", - "lodash.difference": "^4.5.0", - "lodash.flatten": "^4.4.0", - "lodash.isplainobject": "^4.0.6", - "lodash.union": "^4.6.0", - "normalize-path": "^3.0.0", - "readable-stream": "^3.6.0" + "node": ">=10" }, - "engines": { - "node": ">= 10" + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } } } diff --git a/package.json b/package.json index 8b4fd5e..f4f41a6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "elastos-launcher", - "version": "1.4.0", + "version": "2.0.0-test.4", "description": "ElastOS runtime desktop launcher", "main": "dist/main/index.js", "author": { @@ -10,13 +10,13 @@ "license": "AGPL-3.0", "scripts": { "dev": "electron .", - "build:ts": "tsc", + "build:ts": "node scripts/build-mac-process-info.js && node scripts/build-linux-pidfd.js && tsc", "build": "npm run build:ts && electron-builder", "build:mac": "npm run build:ts && electron-builder --mac", "build:win": "npm run build:ts && electron-builder --win", "build:linux": "npm run build:ts && electron-builder --linux", "build:all": "npm run build:ts && electron-builder --mac --win --linux", - "test": "npm run build:ts && node --test test/*.test.js", + "test": "npm run build:ts && node scripts/test.js", "e2e": "npm run build:ts && node scripts/electron-e2e.js", "e2e:upgrade": "npm run build:ts && node scripts/legacy-upgrade-e2e.js" }, @@ -26,7 +26,7 @@ "devDependencies": { "@types/node": "^20.10.0", "electron": "^28.0.0", - "electron-builder": "^24.9.1", + "electron-builder": "26.16.1", "playwright": "^1.48.2", "typescript": "^5.3.0" }, @@ -39,10 +39,13 @@ }, "files": [ "dist/**/*", - "src/renderer/**/*" + "src/renderer/**/*", + "resources/icon.png", + "resources/tray/**/*" ], "mac": { "category": "public.app-category.utilities", + "extendInfo": { "LSUIElement": true }, "icon": "resources/icon.icns", "target": [ "dmg", @@ -69,6 +72,21 @@ ], "category": "Utility" }, + "deb": { + "depends": [ + "libgtk-3-0", + "libnotify4", + "libnss3", + "libxss1", + "libxtst6", + "xdg-utils", + "libatspi2.0-0", + "libuuid1", + "libsecret-1-0", + "libayatana-appindicator3-1" + ] + }, + "asarUnpack": ["dist/native/mac-process-info", "dist/native/linux-pidfd"], "afterAllArtifactBuild": "scripts/notarize.js", "extraResources": [ { diff --git a/resources/runtime-pin.json b/resources/runtime-pin.json index 00f1ee5..01da9a4 100644 --- a/resources/runtime-pin.json +++ b/resources/runtime-pin.json @@ -1,18 +1,18 @@ { - "active": "canary", + "active": "stable", "publisherGateway": "https://elastos.elacitylabs.com", "fallbackInstallerUrl": "https://elastos.elacitylabs.com/install.sh", "maintainerDid": "did:key:z6MkgwHd2BCWe1jHMXPiR6H1q1RFPcv1YzhMbK5G1kBarbfe", - "installerSha256": "18768ef071a9f921fe0c1d902926c138e86f925dbaf5dfb9185fecb8789d6714", + "installerSha256": "09131269f6277f08da624424b7e1c355d5a46c70d79a291ddcdc5172751fbbee", "channels": { "stable": { - "version": null, + "version": "2.0.0", "headCid": null }, "canary": { - "version": "0.8.0-alpha.22", - "headCid": "QmXnA5ao7PMfwdj7pGaxpWs14gfgD15FtmhVQPj1EphFXm" + "version": "2.0.0", + "headCid": null } }, - "note": "Testing pin. Change \"active\" from canary to stable when a stable head is published, and fill channels.stable in that same edit. headCid is the UnixFS CID of release-head.json, not latest_release_cid. installerSha256 is the SHA-256 of the install.sh bytes this release will execute. Intel Mac has no signed release in this pin." + "note": "Version is the rollback floor. Heads follow the selected channel after DID signature verification. installerSha256 is an informational snapshot. Execution requires the hash in the signed release manifest bound by the verified head." } diff --git a/resources/tray/attention.png b/resources/tray/attention.png new file mode 100644 index 0000000..8cc3466 Binary files /dev/null and b/resources/tray/attention.png differ diff --git a/resources/tray/attentionTemplate.png b/resources/tray/attentionTemplate.png new file mode 100644 index 0000000..7f617e2 Binary files /dev/null and b/resources/tray/attentionTemplate.png differ diff --git a/resources/tray/busy.png b/resources/tray/busy.png new file mode 100644 index 0000000..bbb5fcf Binary files /dev/null and b/resources/tray/busy.png differ diff --git a/resources/tray/busyTemplate.png b/resources/tray/busyTemplate.png new file mode 100644 index 0000000..e1e02a7 Binary files /dev/null and b/resources/tray/busyTemplate.png differ diff --git a/resources/tray/running.png b/resources/tray/running.png new file mode 100644 index 0000000..12e3cbd Binary files /dev/null and b/resources/tray/running.png differ diff --git a/resources/tray/runningTemplate.png b/resources/tray/runningTemplate.png new file mode 100644 index 0000000..5626dc0 Binary files /dev/null and b/resources/tray/runningTemplate.png differ diff --git a/resources/tray/stopped.png b/resources/tray/stopped.png new file mode 100644 index 0000000..77bdd9f Binary files /dev/null and b/resources/tray/stopped.png differ diff --git a/resources/tray/stoppedTemplate.png b/resources/tray/stoppedTemplate.png new file mode 100644 index 0000000..810eb53 Binary files /dev/null and b/resources/tray/stoppedTemplate.png differ diff --git a/scripts/build-linux-pidfd.js b/scripts/build-linux-pidfd.js new file mode 100644 index 0000000..95a0057 --- /dev/null +++ b/scripts/build-linux-pidfd.js @@ -0,0 +1,13 @@ +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); + +if (process.platform !== 'linux') process.exit(0); +const output = path.join(__dirname, '../dist/native/linux-pidfd'); +fs.mkdirSync(path.dirname(output), { recursive: true }); +const result = spawnSync('cc', [ + '-Wall', '-Wextra', '-Werror', '-O2', + path.join(__dirname, '../src/native/linux-pidfd.c'), '-o', output, +], { stdio: 'inherit', timeout: 30000 }); +if (result.error) throw result.error; +process.exit(result.status ?? 1); diff --git a/scripts/build-mac-process-info.js b/scripts/build-mac-process-info.js new file mode 100644 index 0000000..47f49e8 --- /dev/null +++ b/scripts/build-mac-process-info.js @@ -0,0 +1,13 @@ +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); + +if (process.platform !== 'darwin') process.exit(0); +const output = path.join(__dirname, '../dist/native/mac-process-info'); +fs.mkdirSync(path.dirname(output), { recursive: true }); +const result = spawnSync('cc', [ + '-Wall', '-Wextra', '-Werror', '-O2', '-mmacosx-version-min=11.0', '-arch', 'arm64', '-arch', 'x86_64', + path.join(__dirname, '../src/native/mac-process-info.c'), '-lproc', '-o', output, +], { stdio: 'inherit', timeout: 30000 }); +if (result.error) throw result.error; +process.exit(result.status ?? 1); diff --git a/scripts/ci-plan.js b/scripts/ci-plan.js new file mode 100644 index 0000000..46c7a92 --- /dev/null +++ b/scripts/ci-plan.js @@ -0,0 +1,57 @@ +const fs = require('node:fs'); + +const allPlatforms = ['mac', 'linux', 'windows']; +const runtimeRows = [ + { os: 'macos-latest', platform: 'darwin-arm64', lane: 'mac', packages: '' }, + { + os: 'ubuntu-24.04', platform: 'linux-x64', lane: 'linux', + packages: 'xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2t64 libgtk-3-0t64 libxss1', + }, + { + os: 'ubuntu-22.04-arm', platform: 'linux-arm64', lane: 'linux', + packages: 'xvfb libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libasound2 libgtk-3-0 libxss1 libayatana-appindicator3-1', + }, +]; +const buildRows = [ + { os: 'macos-latest', platform: 'mac', lane: 'mac' }, + { os: 'ubuntu-latest', platform: 'linux', lane: 'linux' }, + { os: 'windows-latest', platform: 'win', lane: 'windows' }, +]; + +function plan({ eventName, ref = '', headRef = '', baseRef = '', requested = '' }) { + let platforms = []; + if (requested || eventName === 'workflow_dispatch') { + if (!['', 'none', 'all', ...allPlatforms].includes(requested)) { + throw new Error(`Invalid platforms: ${requested}`); + } + platforms = requested === 'all' ? allPlatforms : allPlatforms.filter((platform) => platform === requested); + } else if ((eventName === 'pull_request' && baseRef === 'main') || + (eventName === 'push' && (ref === 'refs/heads/main' || ref.startsWith('refs/tags/v')))) { + platforms = allPlatforms; + } else { + const branch = eventName === 'pull_request' ? headRef : ref.replace(/^refs\/heads\//, ''); + if (branch.startsWith('test/launcher-mac')) platforms = ['mac']; + if (branch.startsWith('test/launcher-jetson') || branch.startsWith('test/launcher-linux')) platforms = ['linux']; + if (branch.startsWith('test/launcher-windows')) platforms = ['windows']; + } + return { + platforms, + runtime: runtimeRows.filter((row) => platforms.includes(row.lane)), + build: buildRows.filter((row) => platforms.includes(row.lane)), + }; +} + +module.exports = { plan }; + +if (require.main === module) { + const result = plan({ + eventName: process.env.GITHUB_EVENT_NAME, ref: process.env.GITHUB_REF, + headRef: process.env.GITHUB_HEAD_REF, baseRef: process.env.GITHUB_BASE_REF, + requested: process.env.INPUT_PLATFORMS, + }); + console.log(JSON.stringify(result)); + if (process.env.GITHUB_OUTPUT) { + fs.appendFileSync(process.env.GITHUB_OUTPUT, Object.entries(result) + .map(([key, value]) => `${key}=${JSON.stringify(value)}\n`).join('')); + } +} diff --git a/scripts/electron-e2e.js b/scripts/electron-e2e.js index dcc1d42..b4a5309 100644 --- a/scripts/electron-e2e.js +++ b/scripts/electron-e2e.js @@ -1,7 +1,7 @@ #!/usr/bin/env node /** * Click Install in the Electron window and wait until the button says - * "Open my computer". Linux, macOS, and Windows CI run this against the pinned runtime. + * "Open Home". Linux, macOS, and Windows CI run this against the pinned runtime. */ const { spawn } = require('node:child_process'); const fs = require('node:fs'); @@ -9,6 +9,9 @@ const os = require('node:os'); const path = require('node:path'); const root = path.join(__dirname, '..'); +if (process.platform === 'darwin' && process.env.GITHUB_ACTIONS !== 'true') { + throw new Error('Mac installation e2e runs only on the GitHub runner.'); +} const electronPath = require('electron'); const { _electron: electron } = require('playwright'); const { HOME_URL, isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); @@ -133,136 +136,62 @@ async function main() { } try { + const { waitFor: poll, focusWindow } = require('./tray-e2e'); + const waitFor = (check, timeout, message) => poll(check, timeout, message, electronApp); + await electronApp.evaluate(({ shell }) => { + global.__openedHome = []; + shell.openExternal = async url => { global.__openedHome.push(url); }; + }); const page = await electronApp.firstWindow(); - const readyDeadline = Date.now() + 60000; - let clicked = ''; - while (Date.now() < readyDeadline && !clicked) { - const label = (await page.locator('#open-label').innerText({ timeout: 5000 })).trim(); - const disabled = await page.locator('#open-btn').isDisabled(); - if (label === 'Install' && !disabled) { - await page.click('#open-btn'); - clicked = label; - break; - } - await page.waitForTimeout(200); - } - if (!clicked) { - const label = (await page.locator('#open-label').innerText()).trim(); - const logs = await page.locator('#logs-content').innerText(); - console.log('----- install log -----'); - console.log(logs); - throw new Error(`Install button did not become ready (button is ${label})`); - } - console.log(`Clicked ${clicked}`); - - // Windows has no ElastOS distro yet, so Install stops on "Click Set up". - // Fix it imports that distro and leaves the gateway down, so the button - // returns to Install and the click has to run the real install. - const budgetMs = process.platform === 'win32' ? 45 * 60 * 1000 : 20 * 60 * 1000; - const deadline = Date.now() + budgetMs; - let lastPrinted = 0; - let label = ''; - let windowsFix = 'pending'; - while (Date.now() < deadline) { - label = (await page.locator('#open-label').innerText()).trim(); - const logs = await page.locator('#logs-content').innerText(); - const errorVisible = await page.locator('#error-box').evaluate((node) => !node.classList.contains('hidden')); - const errorText = (await page.locator('#error-text').innerText()).trim(); - const openDisabled = await page.locator('#open-btn').isDisabled(); - if (Date.now() - lastPrinted > 30000) { - const tail = logs.split('\n').filter(Boolean).slice(-3).join(' | '); - console.log(`button=${label} log=${tail || '(empty)'}`); - lastPrinted = Date.now(); - } - if (label === 'Open my computer') { - console.log('----- install log -----'); - console.log(logs); - for (const line of REQUIRED_LOGS) { - if (!logs.includes(line)) { - throw new Error(`Install log is missing: ${line}`); - } - } - if (HOME_URL !== EXPECTED_HOME) { - throw new Error(`The launcher opens ${HOME_URL}, not ${EXPECTED_HOME}`); + const native = process.platform === 'darwin' ? require('./mac-native').nativeControls(electronApp, page) : null; + await page.locator('#primary').waitFor({ state: 'visible' }); + if ((await page.locator('#primary').innerText()) !== 'Install') throw new Error('Expected Install'); + if (process.platform === 'darwin') { + await focusWindow(electronApp); + await native.drag(); + await native.click('#primary'); + } else await page.click('#primary'); + let fixedWindows = false; + await waitFor(async () => { + const kind = await page.getAttribute('body', 'data-state'); + const label = await page.locator('#primary').innerText(); + if (kind === 'error') { + const message = await page.locator('#message').innerText(); + if (process.platform === 'win32' && !fixedWindows) { + fixedWindows = true; + await electronApp.evaluate(({ dialog }) => { + dialog.showMessageBox = async (...args) => ({ + response: args.at(-1).buttons?.includes('Set Up') ? 1 : 0, + checkboxChecked: false, + }); + }); + await page.click('#primary'); + await page.waitForFunction(() => !document.querySelector('#primary').disabled, null, { timeout: 45 * 60 * 1000 }); + return false; } - const shown = (await page.locator('#url-value').innerText()).trim(); - if (shown !== 'localhost:8090/home') { - throw new Error(`The window shows ${shown}, not localhost:8090/home`); - } - const health = await probeGatewayHealth(); - if (!isHealthOk(health)) { - throw new Error(`/healthz on localhost was not OK (${health ? `HTTP ${health.status}` : 'no answer'})`); - } - console.log(`Home is ${HOME_URL}; /healthz is OK on ${health.addresses.join(', ')}`); - const browserRowHidden = await page.locator('#browser-row').evaluate((node) => node.classList.contains('hidden')); - const browserText = (await page.locator('#browser-note').innerText()).trim(); - if (process.platform === 'win32') { - if (browserRowHidden || browserText !== 'Browser is not available on this computer yet.') { - throw new Error(`Windows must say the Browser is not available yet (shown: ${browserRowHidden ? 'hidden' : browserText})`); - } - console.log(`Browser note: ${browserText}`); - } else if (!browserRowHidden) { - throw new Error(`Only Windows shows a Browser note (shown: ${browserText})`); - } - console.log('Install reached Open my computer'); - return; - } - if (errorVisible && errorText && /Set up ElastOS on Windows|Windows needs Linux support|Windows needs one step/.test(errorText)) { - const fixHidden = await page.locator('#fix-btn').evaluate((node) => node.classList.contains('hidden')); - const fixDisabled = await page.locator('#fix-btn').isDisabled(); - if (process.platform === 'win32' && windowsFix === 'pending' && !fixHidden && !fixDisabled) { - await page.click('#fix-btn'); - windowsFix = 'running'; - console.log('Clicked Fix it to add the ElastOS Linux environment'); - } else if (process.platform === 'win32' && windowsFix === 'running' && !fixHidden && !fixDisabled) { - // Fix it imports the distro and leaves the gateway down, so the - // screen can say it still needs attention. Install is the next click. - if ((label === 'Install' || label === 'Try again') && !openDisabled) { - await page.click('#open-btn'); - windowsFix = 'installing'; - console.log('Clicked Install after Windows setup'); - await page.waitForTimeout(1000); - continue; - } - console.log('----- install log -----'); - console.log(logs); - throw new Error(errorText); - } - await page.waitForTimeout(1000); - continue; - } - const fixHidden = errorVisible - ? await page.locator('#fix-btn').evaluate((node) => node.classList.contains('hidden')) - : true; - const fixDisabled = await page.locator('#fix-btn').isDisabled(); - if (process.platform === 'win32' && windowsFix === 'running' && (label === 'Install' || label === 'Try again') && !openDisabled && fixHidden && !fixDisabled) { - await page.click('#open-btn'); - windowsFix = 'installing'; - console.log('Clicked Install after Windows setup'); - await page.waitForTimeout(1000); - continue; - } - if ((windowsFix === 'running' || windowsFix === 'installing') && (label === 'Working…' || openDisabled)) { - await page.waitForTimeout(1000); - continue; - } - const windowsSetupRunning = process.platform === 'win32' && windowsFix === 'running'; - if (errorVisible && errorText && !(windowsSetupRunning && errorText === 'That still needs attention.')) { - console.log('----- install log -----'); - console.log(logs); - throw new Error(errorText); + throw new Error(message); } - if (label === 'Try again') { - console.log('----- install log -----'); - console.log(logs); - throw new Error(errorText || 'Install ended on Try again'); + if (fixedWindows && kind === 'install' && label === 'Install') { await page.click('#primary'); return false; } + return label === 'Open Home' && kind === 'install'; + }, process.platform === 'win32' ? 45*60*1000 : 20*60*1000, 'Install did not reach Home is ready'); + if (await page.locator('#message').innerText() !== 'Home is ready.') throw new Error('Missing ready confirmation'); + const diagnostics = await page.evaluate(() => window.elastos.copyDiagnostics()); + const text = await electronApp.evaluate(({clipboard})=>clipboard.readText()); + for (const line of REQUIRED_LOGS) if (!text.includes(line)) throw new Error(`Missing install evidence: ${line}`); + if (HOME_URL !== EXPECTED_HOME || !isHealthOk(await probeGatewayHealth())) throw new Error('Home is not healthy'); + console.log('PASS install through window reaches Home is ready with signed-install evidence'); + if (process.platform === 'darwin') { + if ((await electronApp.evaluate(() => global.__openedHome)).length !== 0) { + throw new Error('Mac Install opened a duplicate browser tab after home --browser'); } - await page.waitForTimeout(1000); + await native.click('#primary'); } - const logs = await page.locator('#logs-content').innerText(); - console.log('----- install log -----'); - console.log(logs); - throw new Error(`Install did not reach Open my computer (button is ${label})`); + else await page.click('#primary'); + await waitFor(()=>electronApp.evaluate(()=>global.__openedHome.includes('http://localhost:8090/home/')),10000,'Open Home did not open localhost'); + await require('./tray-e2e').noWindow(electronApp); + const options = {executablePath:electronPath,cwd:root,args,env,timeout:120000}; + electronApp = await require(`./${process.platform === 'darwin' ? 'mac' : process.platform === 'win32' ? 'windows' : 'linux'}-lifecycle-e2e`)(electronApp, page, home, options); + return; } finally { const exiting = electronApp.evaluate(({ app }) => { app.exit(0); @@ -279,7 +208,7 @@ async function main() { } } -const capMs = process.platform === 'win32' ? 50 * 60 * 1000 : 22 * 60 * 1000; +const capMs = process.platform === 'win32' ? 50 * 60 * 1000 : process.platform === 'linux' ? 45 * 60 * 1000 : 35 * 60 * 1000; setTimeout(() => { console.error(`e2e did not finish within ${capMs / 60000} minutes`); process.exit(1); diff --git a/scripts/electron-main.js b/scripts/electron-main.js new file mode 100644 index 0000000..c47d1e3 --- /dev/null +++ b/scripts/electron-main.js @@ -0,0 +1,11 @@ +// Inspector requests can arrive inside a macOS native menu/window callback. +// Run the observation on Node's event loop so its result settles there. +async function readMain(app, read, arg) { + return app.evaluate((electron, { source, arg }) => new Promise((resolve, reject) => { + setImmediate(() => { + try { resolve((0, eval)(`(${source})`)(electron, arg)); } + catch (error) { reject(error); } + }); + }), { source: String(read), arg }); +} +module.exports = { readMain }; diff --git a/scripts/legacy-upgrade-e2e.js b/scripts/legacy-upgrade-e2e.js index 684337d..5841073 100644 --- a/scripts/legacy-upgrade-e2e.js +++ b/scripts/legacy-upgrade-e2e.js @@ -59,18 +59,10 @@ async function main() { }); try { - const page = await electronApp.firstWindow(); - const deadline = Date.now() + 90000; - let visible = false; - while (Date.now() < deadline) { - visible = await page.locator('#remove-pc2-btn').evaluate((node) => !node.classList.contains('hidden')); - if (visible) break; - await page.waitForTimeout(200); - } - const label = (await page.locator('#remove-pc2-btn').innerText()).trim(); - if (!visible || label !== 'Remove PC2') { - throw new Error(`Remove PC2 was not offered (visible=${visible}, label=${label})`); - } + const { waitFor } = require('./tray-e2e'); + await waitFor(() => electronApp.evaluate(() => global.__elastosTrayMenu?.items + .find(item => item.label === 'Troubleshoot')?.submenu.items + .some(item => item.label === 'Remove Old PC2 Files…')), 90000, 'PC2 menu item was not offered'); const pkg = JSON.parse(fs.readFileSync(path.join(pc2, 'package.json'), 'utf8')); if (pkg.name !== 'puter') throw new Error('~/.pc2 was changed before Remove PC2 was confirmed'); if (!server.listening) throw new Error('the listener on port 4200 is gone'); diff --git a/scripts/linux-lifecycle-e2e.js b/scripts/linux-lifecycle-e2e.js new file mode 100644 index 0000000..1ce8ec4 --- /dev/null +++ b/scripts/linux-lifecycle-e2e.js @@ -0,0 +1,102 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { waitFor: poll, clickMenu, trayState, noWindow } = require('./tray-e2e'); +const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); + +async function liveController(data) { + const statusPath = path.join(data, 'update-controller', 'status.json'); + const deadline = Date.now() + 180000; + let last = 'absent'; + while (Date.now() < deadline) { + try { + const record = JSON.parse(fs.readFileSync(statusPath, 'utf8')); + const pid = record.controller_pid; + if (record.phase === 'ready' && Number.isInteger(pid) && pid > 0) { + const command = Buffer.alloc(4096); + const fd = fs.openSync(`/proc/${pid}/cmdline`, 'r'); + let bytes = 0; + try { + bytes = fs.readSync(fd, command, 0, command.length, 0); + } finally { + fs.closeSync(fd); + } + if (command.subarray(0, bytes).includes('__update-controller')) return record; + last = `pid ${pid} is not the update controller`; + } else { + last = `phase ${record.phase}`; + } + } catch (err) { + last = err && err.code ? err.code : 'unread'; + } + await new Promise((resolve) => setTimeout(resolve, 500)); + } + throw new Error(`Home system update check did not reach a live controller (${last})`); +} + + +function portClosed(port, host) { + const net = require('node:net'); + return new Promise((resolve) => { + const socket = net.connect({ port, host }); + const finish = (closed) => { + socket.removeAllListeners(); + socket.destroy(); + resolve(closed); + }; + socket.once('connect', () => finish(false)); + socket.once('error', () => finish(true)); + }); +} + +module.exports = async function (app, page, home, launch) { + const waitFor = (check, timeout, message) => poll(check, timeout, message, app); + const health = wanted => waitFor(async () => isHealthOk(await probeGatewayHealth()) === wanted, 180000, `Home health did not become ${wanted}`); + await trayState(app, 'running'); + console.log('PASS the tray icon is ready'); + + await app.evaluate(({ shell }) => { + global.__openedHome = []; + shell.openExternal = async (url) => { global.__openedHome.push(url); }; + }); + await clickMenu(app, 'Open Home'); + await waitFor(() => app.evaluate(() => global.__openedHome.includes('http://localhost:8090/home/')), 10000, 'Open Home did not open localhost'); + assert.deepEqual(await app.evaluate(() => global.__openedHome), ['http://localhost:8090/home/']); + const response = await fetch('http://localhost:8090/home/'); + assert.equal(response.status, 200); + console.log('PASS Open Home invokes the browser with localhost:8090/home/ and Home returns HTTP 200'); + + await noWindow(app); + await health(true); + await clickMenu(app, 'Stop Home'); + await trayState(app, 'stopped'); + await health(false); + console.log('PASS Stop Home closes the listener'); + await clickMenu(app, 'Start Home'); + await trayState(app, 'running'); + await health(true); + console.log('PASS Start Home becomes healthy'); + + const data = path.join(home, '.local', 'share', 'elastos'); + const controller = await liveController(data); + assert.equal(controller.phase, 'ready'); + console.log('PASS Home system update check reaches the live controller'); + console.log('NOT EXERCISED a full System update because no newer signed release exists'); + console.log('NOT EXERCISED the owner System summary because that route needs a wallet token'); + + const nativeUpdate = path.join(data, 'update-check.json'); + const update = JSON.parse(fs.readFileSync(fs.existsSync(nativeUpdate) ? nativeUpdate + : path.join(home, '.elastos-launcher', 'update-check.json'), 'utf8')); + assert.equal(update.outcome, 'up_to_date'); + console.log('PASS elastos update --check writes up_to_date'); + + const stoppedPid = controller.controller_pid; + const closed = app.waitForEvent('close'); + await clickMenu(app, 'Quit ElastOS'); await closed; + await health(false); + assert.equal(await portClosed(8090, '127.0.0.1'), true); + assert.equal(await portClosed(8090, '::1'), true); + assert.equal(fs.existsSync(`/proc/${stoppedPid}`), false); + console.log('PASS Quit ElastOS stops Home and its controller'); + return app; +}; diff --git a/scripts/mac-click.swift b/scripts/mac-click.swift new file mode 100644 index 0000000..eaeeba4 --- /dev/null +++ b/scripts/mac-click.swift @@ -0,0 +1,25 @@ +import AppKit +import CoreGraphics + +// Never prompt for Accessibility permission on an unattended runner. +guard CGPreflightPostEventAccess() else { + print("OS events unavailable: CGPreflightPostEventAccess=false") + exit(77) +} +if CommandLine.arguments.count == 3 || CommandLine.arguments.count == 5 { + let start = CGPoint(x: Double(CommandLine.arguments[1])!, y: Double(CommandLine.arguments[2])!) + CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: start, mouseButton: .left)!.post(tap: .cghidEventTap) + usleep(100_000) + var end = start + if CommandLine.arguments.count == 5 { + end = CGPoint(x: Double(CommandLine.arguments[3])!, y: Double(CommandLine.arguments[4])!) + for step in 1...20 { + let progress = Double(step) / 20.0 + let point = CGPoint(x: start.x + (end.x - start.x) * progress, y: start.y + (end.y - start.y) * progress) + CGEvent(mouseEventSource: nil, mouseType: .leftMouseDragged, mouseCursorPosition: point, mouseButton: .left)!.post(tap: .cghidEventTap) + usleep(20_000) + } + } + CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: end, mouseButton: .left)!.post(tap: .cghidEventTap) +} +print("OS events permitted") diff --git a/scripts/mac-dialog-e2e.js b/scripts/mac-dialog-e2e.js new file mode 100644 index 0000000..224662c --- /dev/null +++ b/scripts/mac-dialog-e2e.js @@ -0,0 +1,90 @@ +// Packaged native UI with a fixture controller; lifecycle e2e uses the real signed Home. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { _electron: electron } = require('playwright'); +const { readMain } = require('./electron-main'); +const { nativeControls } = require('./mac-native'); +const { clickMenu, waitFor, trayState, noWindow } = require('./tray-e2e'); +if (process.platform !== 'darwin' || process.env.GITHUB_ACTIONS !== 'true') throw new Error('Packaged Mac dialog e2e runs only on the disposable GitHub Mac runner.'); +async function main() { + const home=fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()),'launcher-dialog-home-')); + const env={...process.env, HOME:home, USERPROFILE:home, ELASTOS_HIDE_HOST_TOOLS:'1', + PATH:(process.env.PATH||'').split(path.delimiter).filter(dir=>!fs.existsSync(path.join(dir,'elastos'))).join(path.delimiter)}; + delete env.ELECTRON_RUN_AS_NODE; + const app=await electron.launch({executablePath:path.resolve(process.argv[2],'Contents/MacOS/ElastOS'),env,timeout:60000}); + const watchdog=setTimeout(()=>app.process().kill('SIGKILL'),180000); + try { + const page=await app.firstWindow(); + const native=nativeControls(app,page); + await page.locator('#primary').waitFor(); + await app.evaluate(({app,dialog,shell})=>{ + const root=app.getAppPath(); + const fromApp=process.mainModule.require.bind(process.mainModule); + const {launch}=fromApp(root+'/dist/main/index.js'); + global.__fixture={calls:[],dialogs:[],answer:{response:0,checkboxChecked:false},status:'not-installed'}; + const f=global.__fixture; + launch.getStatus=async()=>f.status; + launch.getOpenAtLogin=()=>false; launch.setOpenAtLogin=v=>f.calls.push(['login',v]); + launch.install=async progress=>{f.calls.push(['install']);progress('Setting up');f.status='stopped';}; + launch.start=async()=>{f.calls.push(['start']);f.status='running';}; + launch.stop=async()=>{f.calls.push(['stop']);f.status='stopped';}; + launch.shutdown=async()=>{}; + launch.openInBrowser=()=>f.calls.push(['open','http://localhost:8090/home/']); + launch.checkForUpdate=async()=>({latest:'2.0.1',updateAvailable:true,releaseUrl:'https://example.com/releases/2.0.1'}); + launch.update=async progress=>{f.calls.push(['update']);progress('Downloading');f.status='running';}; + launch.describeResetBackup=async()=>({present:true,enough:true}); + launch.resetRuntime=async choice=>{f.calls.push(['reset',choice]);}; + launch.uninstall=async(_confirm,deleteData)=>{f.calls.push(['uninstall',deleteData]);}; + launch.getDiagnostics=async()=> 'fixture diagnostics'; + launch.describeFailure=async()=>({message:'The download stopped.',fixLabel:null}); + shell.openExternal=async url=>f.calls.push(['external',url]); + dialog.showMessageBox=async(...args)=>{f.dialogs.push(args.at(-1));return f.answer;}; + const pc2=fromApp(root+'/dist/main/legacyPc2Removal.js'); + pc2.describeLegacyPc2OnThisComputer=async()=>f.removed?[]:[{path:'/Users/runner/.pc2',label:'PC2 data'}]; + pc2.removeLegacyPc2OnThisComputer=async choice=>{f.calls.push(['pc2',choice]);f.removed=true;return {ok:true};}; + }); + await native.drag(); + await native.click('#login'); + await waitFor(async()=>!(await page.locator('#login').isChecked()),10000,'Native login click did not uncheck Open at Login'); + await native.click('#primary'); + await waitFor(async()=>await page.locator('#primary').innerText()==='Open Home',10000,'No ready screen'); + assert.equal(await page.locator('#message').innerText(),'Home is ready.'); + assert.ok(await readMain(app,()=>global.__fixture.calls.some(c=>c[0]==='login'&&c[1]===false))); + await native.click('#primary'); await waitFor(()=>readMain(app,()=>global.__fixture.calls.some(c=>c[0]==='open')),10000,'Native Open Home did not open Home'); + await noWindow(app); await trayState(app,'running'); + for(const [label,action] of [['Reset ElastOS…','reset'],['Uninstall ElastOS…','uninstall'],['Remove Old PC2 Files…','pc2']]) { + const before=await readMain(app,()=>global.__fixture.dialogs.length); + await app.evaluate(()=>{global.__fixture.answer={response:0,checkboxChecked:false};}); + await clickMenu(app,label); + await waitFor(()=>readMain(app,(_e,b)=>global.__fixture.dialogs.length>b,before),10000,'Native dialog did not open'); + const options=await readMain(app,()=>global.__fixture.dialogs.at(-1)); + assert.equal(options.defaultId,0);assert.equal(options.cancelId,0);assert.equal(options.buttons[0],'Cancel'); + assert.equal(await readMain(app,(_e,action)=>global.__fixture.calls.some(c=>c[0]===action),action),false); + await app.evaluate(()=>{global.__fixture.answer={response:1,checkboxChecked:true};}); + await clickMenu(app,label); + await waitFor(()=>readMain(app,(_e,action)=>global.__fixture.calls.some(c=>c[0]===action),action),10000,'Confirm did not reach controller'); + console.log(`PASS real menu ${label} opens native dialog, defaults to Cancel, and honors choice`); + } + const calls=await readMain(app,()=>global.__fixture.calls); + assert.ok(calls.some(c=>c[0]==='reset'&&c[1].backup)); + assert.ok(calls.some(c=>c[0]==='uninstall'&&c[1]===true)); + assert.ok(calls.some(c=>c[0]==='pc2'&&c[1].backup&&c[1].paths[0]==='/Users/runner/.pc2')); + await clickMenu(app,'Update to 2.0.1…'); + const update=await app.firstWindow();const updateNative=nativeControls(app,update); + await update.locator('#cancel').waitFor(); + await updateNative.click('#cancel');await noWindow(app); + await clickMenu(app,'Update to 2.0.1…'); + const confirming=await app.firstWindow();const confirmingNative=nativeControls(app,confirming); + await confirming.locator('#primary').waitFor(); + await confirmingNative.click('#primary'); + await waitFor(()=>readMain(app,()=>global.__fixture.calls.some(c=>c[0]==='update')),10000,'Update did not run'); + await noWindow(app); + console.log('PASS native update window supports Not Now and Update then closes'); + } finally { + await app.evaluate(({app})=>app.exit(0)).catch(()=>{});clearTimeout(watchdog); + if(app.process().exitCode===null)app.process().kill('SIGKILL'); + } +} +main().catch(error=>{console.error(error);process.exitCode=1;}); diff --git a/scripts/mac-lifecycle-e2e.js b/scripts/mac-lifecycle-e2e.js new file mode 100644 index 0000000..581a841 --- /dev/null +++ b/scripts/mac-lifecycle-e2e.js @@ -0,0 +1,72 @@ +const assert = require('node:assert/strict'); +const { spawn, spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const http = require('node:http'); +const path = require('node:path'); +const { _electron: electron } = require('playwright'); +const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); +const { runtimeChildEnv } = require('../dist/main/targets/releaseHead'); +const { waitFor: poll, clickMenu, trayState, noWindow } = require('./tray-e2e'); +module.exports = async function(app, page, home, options) { + const waitFor = (check, timeout, message, target = app) => poll(check, timeout, message, target); + const health = (wanted, target = app) => waitFor(async()=>isHealthOk(await probeGatewayHealth())===wanted,180000,`Home health did not become ${wanted}`, target); + await trayState(app,'running'); await noWindow(app); + await app.evaluate(({ shell }) => { + global.__openedHome = []; + shell.openExternal = async url => { global.__openedHome.push(url); }; + }); + await clickMenu(app,'Open Home'); + await waitFor(()=>app.evaluate(()=>global.__openedHome.includes('http://localhost:8090/home/')),10000,'Open Home did not open localhost'); + assert.deepEqual(await app.evaluate(()=>global.__openedHome), ['http://localhost:8090/home/']); + assert.equal((await fetch('http://localhost:8090/home/')).status,200); + console.log('PASS Open Home opens localhost:8090/home/ through the real menu'); + await clickMenu(app,'Stop Home'); await trayState(app,'stopped'); await health(false); + console.log('PASS Stop Home closes the listener and changes the icon'); + // A second process, rather than app.emit, exercises the actual single-instance lock. + const second = spawnSync(options.executablePath,options.args,{cwd:options.cwd,env:options.env,timeout:30000,encoding:'utf8'}); + assert.equal(second.status,0,second.stderr); + await trayState(app,'running'); await health(true); await noWindow(app); + console.log('PASS second launch starts stopped Home and opens it without a window'); + await clickMenu(app,'Stop Home'); await trayState(app,'stopped'); + await clickMenu(app,'Start Home'); await trayState(app,'running'); await health(true); + console.log('PASS Start Home becomes healthy and changes the icon'); + const data=path.join(home,'Library','Application Support','elastos'); + const controller=path.join(data,'update-controller','status.json'); + const started=JSON.parse(fs.readFileSync(controller,'utf8')).controller_pid; + process.kill(started,'SIGKILL'); + await trayState(app,'attention'); + // Starting uses the existing supervisor's proved recovery path. + await clickMenu(app,'Start Home'); await trayState(app,'running'); await health(true); + console.log('PASS controller crash changes the icon and explicit Start recovers'); + const closed = app.waitForEvent('close'); + await clickMenu(app,'Quit ElastOS'); await closed; await health(false); + console.log('PASS Quit ElastOS stops Home'); + const binary=path.join(home,'.local','bin','elastos'); + const external=spawn(binary,['home','--browser'],{detached:true,stdio:'ignore',env:runtimeChildEnv(options.env)}); + let adopted, foreign; + try { + await health(true); + adopted=await electron.launch(options); await trayState(adopted,'running'); await noWindow(adopted); + console.log('PASS opening an installed running Home adopts it without a window'); + await clickMenu(adopted,'Stop Home'); await trayState(adopted,'stopped'); await health(false,adopted); + console.log('PASS Stop Home stops the proved adopted Home'); + await clickMenu(adopted,'Start Home'); await trayState(adopted,'running'); + const closed = adopted.waitForEvent('close'); await clickMenu(adopted,'Quit ElastOS'); await closed; await health(false,adopted); + foreign=http.createServer((_req,res)=>res.end('OK')); + await new Promise((resolve,reject)=>{foreign.once('error',reject);foreign.listen(8090,'127.0.0.1',resolve);}); + adopted=await electron.launch(options); + const errorWindow=await adopted.firstWindow(); + await waitFor(async()=>/another|8090/i.test(await errorWindow.locator('#message').innerText()),30000,'Missing foreign-port error',adopted); + assert.equal(foreign.listening,true); + const foreignClosed = adopted.waitForEvent('close'); + await clickMenu(adopted,'Quit ElastOS'); await foreignClosed; + assert.equal(foreign.listening,true); + console.log('PASS foreign listener receives no signal on open or Quit'); + console.log('NOT EXERCISED signed update replacement: no newer signed Stable release is available'); + return adopted; + } finally { + if(adopted) await adopted.close().catch(()=>{}); + if(foreign) await new Promise(resolve=>foreign.close(resolve)); + if(external.exitCode===null && external.signalCode===null) external.kill('SIGTERM'); + } +}; diff --git a/scripts/mac-native.js b/scripts/mac-native.js new file mode 100644 index 0000000..6d55563 --- /dev/null +++ b/scripts/mac-native.js @@ -0,0 +1,43 @@ +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const os = require('node:os'); +const path = require('node:path'); +const { focusWindow } = require('./tray-e2e'); +function nativeControls(app, page) { + const helper = path.join(os.tmpdir(), `elastos-click-${process.pid}`); + const compiled = spawnSync('swiftc', [path.join(__dirname,'mac-click.swift'), '-o', helper], {encoding:'utf8',timeout:120000}); + assert.equal(compiled.status,0,compiled.stderr); + function event(args) { + const result=spawnSync(helper,args.map(String),{encoding:'utf8',timeout:5000}); + assert.equal(result.status,0,`Native OS events required: ${result.stdout} ${result.stderr}`); + } + async function bounds() {return app.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].getContentBounds());} + return { + async click(selector) { + await focusWindow(app); + const deadline = Date.now() + 10000; + let before = await bounds(); + while (Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 100)); + const win = await bounds(); + if (['x', 'y', 'width', 'height'].every(key => win[key] === before[key])) { + const box = await page.locator(selector).boundingBox(); assert.ok(box); + event([win.x+box.x+box.width/2,win.y+box.y+box.height/2]); + return; + } + before = win; + } + throw new Error(`Window content bounds did not stabilize: ${JSON.stringify(before)}`); + }, + async drag() { + const before=await bounds(); const strip=await page.locator('.title-bar').boundingBox(); + assert.equal(strip.width,before.width); + const x=before.x+strip.width*.7,y=before.y+strip.height/2; + event([x,y,x+60,y+45]); await page.waitForTimeout(300); + const after=await bounds(); + assert.ok(after.x-before.x>=30 && after.y-before.y>=20,JSON.stringify({before,after})); + console.log('PASS real OS drag moves the full top strip'); + }, + }; +} +module.exports={nativeControls}; diff --git a/scripts/notarize.js b/scripts/notarize.js index b171396..65254bc 100644 --- a/scripts/notarize.js +++ b/scripts/notarize.js @@ -1,76 +1,72 @@ -const { execSync } = require("child_process"); -const path = require("path"); +const { execFileSync } = require('node:child_process'); +const path = require('node:path'); -/** - * electron-builder afterAllArtifactBuild hook. - * - * Submits macOS DMG/ZIP artifacts to Apple's notary service. - * Does NOT block on --wait (Apple's in-depth analysis for new accounts - * can exceed CI timeouts). Prints submission UUIDs for manual follow-up. - * - * To check status later: - * xcrun notarytool info --apple-id ... --team-id ... --password ... - * - * To staple after acceptance: - * xcrun stapler staple - * - * Requires APPLE_ID, APPLE_APP_SPECIFIC_PASSWORD, APPLE_TEAM_ID env vars. - */ -module.exports = async function (context) { - if (process.platform !== "darwin") return []; - - const notarizableExts = [".dmg", ".zip"]; - const artifacts = context.artifactPaths.filter((p) => - notarizableExts.some((ext) => p.endsWith(ext)) - ); - - if (artifacts.length === 0) return []; - - const appleId = process.env.APPLE_ID; - const appPassword = process.env.APPLE_APP_SPECIFIC_PASSWORD; - const teamId = process.env.APPLE_TEAM_ID; +// Ported from SashaMIT's v1.4.0 fix, commit 6e28656 (PR #5). +// Keep the Apple password in the child's environment and secure prompt. Never +// interpolate it into a command, process argument, exception, or saved file. +const submit = ` +set timeout 1800 +log_user 0 +spawn -noecho xcrun notarytool submit $env(ELASTOS_NOTARY_ARTIFACT) --apple-id $env(APPLE_ID) --team-id $env(APPLE_TEAM_ID) --wait --timeout 25m --output-format json +expect { + -nocase -re {password[^:]*:} { send -- "$env(APPLE_APP_SPECIFIC_PASSWORD)\\r" } + timeout { puts "Timed out waiting for the password prompt"; exit 124 } + eof { puts $expect_out(buffer); exit 1 } +} +expect { + -re {\\{.*\\}} { puts $expect_out(0,string); exp_continue } + timeout { exit 124 } + eof { puts $expect_out(buffer); set result [wait]; exit [lindex $result 3] } +} +`; - if (!appleId || !appPassword || !teamId) { - console.log("[notarize] Apple credentials not set, skipping notarization"); - console.log("[notarize] Set APPLE_ID, APPLE_APP_SPECIFIC_PASSWORD, APPLE_TEAM_ID to enable"); - return artifacts; +async function notarize(context) { + const artifacts = context.artifactPaths.filter((file) => /\.(dmg|zip)$/.test(file)); + if (!artifacts.length) throw new Error('No macOS artifact was produced.'); + for (const name of ['APPLE_ID', 'APPLE_APP_SPECIFIC_PASSWORD', 'APPLE_TEAM_ID']) { + if (!process.env[name]) throw new Error(`Missing required notarization credential ${name}.`); } - - const submissionIds = []; - - for (const artifactPath of artifacts) { + for (const artifact of artifacts) { + const name = path.basename(artifact); + console.log(`[notarize] Submitting ${name} and waiting for Apple.`); + let result; try { - console.log(`[notarize] Submitting ${path.basename(artifactPath)} for notarization...`); - - const result = execSync( - `xcrun notarytool submit "${artifactPath}" ` + - `--apple-id "${appleId}" --team-id "${teamId}" --password "${appPassword}"`, - { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], timeout: 5 * 60 * 1000 } - ); - - const idMatch = result.match(/id:\s*([0-9a-f-]{36})/); - if (idMatch) { - submissionIds.push({ file: path.basename(artifactPath), id: idMatch[1] }); - console.log(`[notarize] Submitted ${path.basename(artifactPath)} → UUID: ${idMatch[1]}`); + const output = execFileSync('/usr/bin/expect', ['-c', submit], { + env: { ...process.env, ELASTOS_NOTARY_ARTIFACT: artifact }, + encoding: 'utf8', timeout: 30 * 60 * 1000, stdio: ['ignore', 'pipe', 'pipe'], + }); + result = JSON.parse(output.trim()); + } catch (error) { + let diagnostic = [error.stdout, error.stderr].filter(Boolean).map(String).join('\n'); + for (const key of ['CSC_LINK', 'CSC_KEY_PASSWORD', 'APPLE_ID', 'APPLE_APP_SPECIFIC_PASSWORD', 'APPLE_TEAM_ID']) { + const secret = process.env[key]; + if (secret) diagnostic = diagnostic.split(secret).join('[redacted]'); } - console.log(result); - } catch (err) { - console.error(`[notarize] Submission failed for ${path.basename(artifactPath)}: ${err.message}`); - if (err.stdout) console.error(err.stdout); - if (err.stderr) console.error(err.stderr); + throw new Error(`[notarize] Submission failed for ${name} (exit ${error.status ?? 'unknown'}). ${diagnostic.slice(-8000)}`); } - } - - if (submissionIds.length > 0) { - console.log("\n[notarize] ═══════════════════════════════════════════════"); - console.log("[notarize] Submissions sent (check status manually):"); - for (const s of submissionIds) { - console.log(`[notarize] ${s.file} → ${s.id}`); + console.log(`[notarize] ${name} status=${result.status} id=${result.id}`); + if (result.status !== 'Accepted') throw new Error(`[notarize] ${name} was not Accepted.`); + if (artifact.endsWith('.dmg')) { + execFileSync('xcrun', ['stapler', 'staple', artifact], { stdio: 'inherit', timeout: 120000 }); + execFileSync('xcrun', ['stapler', 'validate', artifact], { stdio: 'inherit', timeout: 120000 }); } - console.log("[notarize] Check: xcrun notarytool info --keychain-profile "); - console.log("[notarize] Staple: xcrun stapler staple "); - console.log("[notarize] ═══════════════════════════════════════════════\n"); } - return artifacts; +} + +module.exports = async function (context) { + if (process.platform !== 'darwin') return []; + const strict = process.env.MAC_RELEASE_STRICT === 'true'; + if (process.env.NOTARIZE_MAC !== 'true') { + if (strict) throw new Error('[notarize] A release build must be notarized.'); + console.log('[notarize] Skipped because notarization was not requested.'); + return []; + } + try { + return await notarize(context); + } catch (error) { + if (strict) throw error; + console.warn(`[notarize] Test build continues without notarization: ${error.message}`); + return []; + } }; diff --git a/scripts/prove-launch-redesign.js b/scripts/prove-launch-redesign.js new file mode 100644 index 0000000..6ce4039 --- /dev/null +++ b/scripts/prove-launch-redesign.js @@ -0,0 +1,22 @@ +const assert = require('node:assert/strict'); +const {execFileSync}=require('node:child_process'); +const fs=require('node:fs'); +const path=require('node:path'); +const ts=require('typescript'); +const {mainFixture}=require('../test/main-fixture'); +async function main(){ + const raw=execFileSync('git',['show','1fd5f798e3a6ce481c06b97cc26dd79c12ec1068:src/main/index.ts'],{encoding:'utf8'}); + const baseline=path.resolve(__dirname,'../dist/main/test3-baseline.cjs'); + fs.writeFileSync(baseline,ts.transpileModule(raw,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,esModuleInterop:true}}).outputText); + try { + const before=await mainFixture({entry:baseline,status:'running'}); + assert.equal(before.windows.length,1); + assert.throws(()=>assert.equal(before.windows.length,0)); + console.log('FAIL BEFORE 1fd5f798: installed/running app creates 1 standing window; expected 0.'); + const after=await mainFixture({status:'running'}); + assert.equal(after.windows.length,0); + assert.equal(after.calls.filter(c=>c==='open').length,1); + console.log('PASS AFTER: installed/running app creates 0 windows and opens Home once.'); + } finally {fs.unlinkSync(baseline);} +} +main().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/scripts/render-menu.js b/scripts/render-menu.js new file mode 100644 index 0000000..0ff5903 --- /dev/null +++ b/scripts/render-menu.js @@ -0,0 +1,28 @@ +// Review artifacts use the same menu template as Electron, never a second label set. +const fs = require('node:fs/promises'); +const path = require('node:path'); +const { chromium } = require('playwright'); +const { buildHomeMenu } = require('../dist/main/homeMenu'); +const actions = Object.fromEntries(['open','start','stop','update','login','diagnostics','logs','removePc2','reset','uninstall','about','quit'].map(k=>[k,()=>{}])); +const escape = s => String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +async function main() { + const out = process.argv[2]; if(!out) throw new Error('Pass an output directory'); + await fs.mkdir(out,{recursive:true}); + const base = { observed: 'running', inFlight: null, failure: null, quitting: false }; + const cases = ['running','stopped','starting','stopping','error','other-home','not-installed'].map(observed=>({observed})); + cases.push(...['start','stop','update','open','maintenance'].map(kind=>({inFlight:{kind,generation:1}})), + {quitting:true,inFlight:{kind:'update',generation:1}}, {observed:'starting',failure:'The download stopped.'}); + cases.push({observed:'running',update:{latest:'2.0.1',updateAvailable:true}}, {observed:'running',pc2:true}, {observed:'running',login:true}, {observed:'stopped',login:false,pc2:false}); + function tree(items,indent='') { return items.map(i=>indent+(i.type==='separator'?'────────':`${i.type==='checkbox'?(i.checked?'[✓] ':'[ ] '):''}${i.label}${i.enabled===false?' (disabled)':''}${i.sublabel?' · '+i.sublabel:''}${i.accelerator?' · '+i.accelerator:''}`)+(i.submenu?'\n'+tree(i.submenu,indent+' '):'')).join('\n'); } + await fs.writeFile(path.join(out,'menus.txt'), cases.map(state=>JSON.stringify(state)+'\n'+tree(buildHomeMenu({...base,platform:'darwin',...state},actions))).join('\n\n')+'\n'); + const browser = await chromium.launch({headless:true}); + try { for (const status of ['running','stopped']) { + const items=buildHomeMenu({...base,observed:status,platform:'darwin',login:true},actions); + const page=await browser.newPage({viewport:{width:344,height:440},deviceScaleFactor:2}); + await page.setContent(``); + const height = Math.ceil((await page.locator('.menu').boundingBox()).height) + 20; + await page.setViewportSize({width:344,height}); + await page.screenshot({path:path.join(out,`menu-${status}.png`)}); await page.close(); + }} finally {await browser.close();} +} +main().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/scripts/runtime-rollback.sh b/scripts/runtime-rollback.sh deleted file mode 100755 index 1afa306..0000000 --- a/scripts/runtime-rollback.sh +++ /dev/null @@ -1,194 +0,0 @@ -#!/usr/bin/env bash -# Install the pinned runtime (0.8.0-alpha.22), roll back to the publisher's -# previous signed head (0.8.0-alpha.21), require /healthz OK, then update -# forward again and require /healthz OK. This runs the real elastos binary. -set -euo pipefail - -root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -real_home="${HOME}" -smoke_base="${ELASTOS_SMOKE_BASE:-${real_home}/.elastos-smoke}" -mkdir -p "${smoke_base}" -chmod 700 "${smoke_base}" -work="$(mktemp -d "${smoke_base}/rollback.XXXXXX")" -retain="${work}/home.path" - -echo "Installing the pinned release before rollback" -ELASTOS_RETAIN_FILE="${retain}" bash "${root}/scripts/runtime-smoke.sh" -if [[ ! -s "${retain}" ]]; then - echo "The install did not leave a home directory for rollback" >&2 - exit 1 -fi -export HOME -HOME="$(tr -d '\r\n' < "${retain}")" -export XDG_DATA_HOME="${HOME}/.local/share" -export PATH="${HOME}/.local/bin:${PATH}" -runtime_bin="${HOME}/.local/bin/elastos" -if [[ ! -x "${runtime_bin}" ]]; then - echo "Installer did not produce ${runtime_bin}" >&2 - exit 1 -fi - -pin_file="${root}/resources/runtime-pin.json" -python3 - "${pin_file}" "${work}/release-head.json" "${work}/prev-head.json" "${work}/rollback.env" <<'PY' -import json, re, sys, urllib.request - -def varint(value): - out = bytearray() - while True: - byte = value & 0x7F - value >>= 7 - if value: - out.append(byte | 0x80) - else: - out.append(byte) - return bytes(out) - -def unixfs_cid(raw): - import hashlib - unixfs = bytes([0x08, 0x02]) + bytes([0x12]) + varint(len(raw)) + raw + bytes([0x18]) + varint(len(raw)) - dag = bytes([0x0A]) + varint(len(unixfs)) + unixfs - digest = hashlib.sha256(dag).digest() - number = int.from_bytes(b"\x12\x20" + digest, "big") - alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" - cid = "" - while number: - number, digit = divmod(number, 58) - cid = alphabet[digit] + cid - return cid - -pin = json.load(open(sys.argv[1])) -channel = pin["channels"][pin["active"]] -gateway = pin["publisherGateway"].rstrip("/") -current = urllib.request.urlopen(gateway + "/release-head.json", timeout=60).read() -open(sys.argv[2], "wb").write(current) -current_doc = json.loads(current.decode()) -current_cid = unixfs_cid(current) -if current_doc["payload"]["version"] != "0.8.0-alpha.22": - sys.exit("publisher release-head.json is not 0.8.0-alpha.22") -if current_cid != channel["headCid"]: - sys.exit(f"publisher head {current_cid} is not the pin {channel['headCid']}") -prev = current_doc["payload"].get("prev_head_cid") or "" -if not re.fullmatch(r"Qm[1-9A-HJ-NP-Za-km-z]{20,}", prev): - sys.exit("publisher release head has no previous head CID") -prev_raw = urllib.request.urlopen(gateway + "/ipfs/" + prev, timeout=60).read() -open(sys.argv[3], "wb").write(prev_raw) -prev_doc = json.loads(prev_raw.decode()) -prev_cid = unixfs_cid(prev_raw) -if prev_cid != prev: - sys.exit(f"previous object CID {prev_cid} is not {prev}") -if prev_doc["payload"]["version"] != "0.8.0-alpha.21": - sys.exit(f"previous head is {prev_doc['payload'].get('version')}, not 0.8.0-alpha.21") -open(sys.argv[4], "w").write( - f"PREV_CID={prev}\nPIN_CID={channel['headCid']}\nMAINTAINER={pin['maintainerDid']}\n" -) -print(f"previous head {prev} is 0.8.0-alpha.21") -print(f"pinned head {channel['headCid']} is 0.8.0-alpha.22") -PY - -# shellcheck disable=SC1090 -source "${work}/rollback.env" -python3 "${root}/scripts/verify-release-head.py" "${work}/release-head.json" elastos.release.head.v1 "${MAINTAINER}" -python3 "${root}/scripts/verify-release-head.py" "${work}/prev-head.json" elastos.release.head.v1 "${MAINTAINER}" -echo "Release head signature matches the pinned maintainer" - -gw_pid="" -gw_log="${work}/gateway.log" - -stop_gateway() { - if [[ -z "${gw_pid}" ]]; then - return 0 - fi - echo "Stopping gateway pid ${gw_pid}" - kill -TERM -"${gw_pid}" 2>/dev/null || kill -TERM "${gw_pid}" 2>/dev/null || true - local i - for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do - if ! kill -0 "${gw_pid}" 2>/dev/null; then - break - fi - sleep 1 - done - if kill -0 "${gw_pid}" 2>/dev/null; then - kill -KILL -"${gw_pid}" 2>/dev/null || kill -KILL "${gw_pid}" 2>/dev/null || true - fi - wait "${gw_pid}" 2>/dev/null || true - gw_pid="" - if curl -fsS --max-time 2 http://localhost:8090/healthz >/dev/null 2>&1; then - echo "Gateway still answering /healthz after stop" >&2 - exit 1 - fi - echo "Gateway stopped cleanly" -} - -cleanup() { - local status=$? - stop_gateway || true - if [[ "${status}" -ne 0 && -f "${gw_log}" ]]; then - echo "----- gateway log -----" - tail -n 80 "${gw_log}" || true - fi - exit "${status}" -} -trap cleanup EXIT - -require_health() { - "${runtime_bin}" gateway --addr localhost:8090 >"${gw_log}" 2>&1 & - gw_pid=$! - local healthy=0 - local _ - for _ in $(seq 1 90); do - if ! kill -0 "${gw_pid}" 2>/dev/null; then - echo "Gateway exited before /healthz" >&2 - exit 1 - fi - local body - body="$(curl -fsS --max-time 2 http://localhost:8090/healthz 2>/dev/null || true)" - if [[ "${body}" == "OK" ]]; then - healthy=1 - break - fi - sleep 1 - done - if [[ "${healthy}" -ne 1 ]]; then - echo "Timed out waiting for /healthz" >&2 - exit 1 - fi - echo "/healthz is OK" - stop_gateway -} - -require_version() { - local want="$1" - local got - got="$("${runtime_bin}" version)" - echo "Installed version: ${got}" - if [[ "${got}" != "ElastOS Runtime v${want}" && "${got}" != "${want}" ]]; then - echo "Installed version is not exactly ${want}: ${got}" >&2 - exit 1 - fi -} - -run_update() { - echo "Running: ${runtime_bin} $*" - set +e - local out - out="$("${runtime_bin}" "$@" 2>&1)" - local code=$? - set -e - printf '%s\n' "${out}" - if [[ "${code}" -ne 0 ]]; then - echo "elastos update exited ${code}" >&2 - exit 1 - fi -} - -echo "Rolling back to 0.8.0-alpha.21 ${PREV_CID}" -run_update update --rollback-to "${PREV_CID}" --yes -require_version "0.8.0-alpha.21" -require_health - -echo "Updating back to the pinned release ${PIN_CID}" -run_update update --yes -require_version "0.8.0-alpha.22" -require_health -echo "Rollback returned to the pinned release" -trap - EXIT diff --git a/scripts/runtime-smoke.sh b/scripts/runtime-smoke.sh index 844d367..e78ae01 100755 --- a/scripts/runtime-smoke.sh +++ b/scripts/runtime-smoke.sh @@ -3,10 +3,14 @@ # require /healthz to be OK and /home/ to return 200, then stop the process group. # # Reads resources/runtime-pin.json. "active" selects canary or stable. -# If that pin does not match the publisher, install stops. +# If the signature, channel, or rollback floor fails, install stops. # # Uses an isolated HOME so it does not touch the runner's real data dir. set -euo pipefail +if [[ "$(uname -s)" == "Darwin" && "${GITHUB_ACTIONS:-}" != "true" ]]; then + echo "Mac installation smoke runs only on the GitHub runner." >&2 + exit 1 +fi root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" raw_pin="${ELASTOS_SMOKE_PIN:-${root}/resources/runtime-pin.json}" @@ -109,11 +113,15 @@ print(f"publisher channel={payload.get('channel')} version={payload.get('version print(f"pin channel={pin.get('channel')} version={pin.get('version')} head_cid={pin.get('headCid')}") matched = ( payload.get("channel") == pin.get("channel") - and payload.get("version") == pin.get("version") - and head_cid == pin.get("headCid") + and __import__("re").fullmatch(r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)", payload.get("version", "")) is not None + and tuple(map(int, payload["version"].split("."))) >= tuple(map(int, pin["version"].split("."))) and head.get("signer_did") == pin.get("maintainerDid") ) open(sys.argv[2], "w").write("yes\n" if matched else "no\n") +if matched: + pin["headCid"] = head_cid + pin["version"] = payload["version"] + json.dump(pin, open(sys.argv[1], "w")) PY matched="$(cat "${work}/pin.match")" @@ -127,7 +135,20 @@ fi echo "Pinned release matches the publisher. Verifying the signature and installer hash." maintainer="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["maintainerDid"])' "${pin_file}")" head_cid="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["headCid"])' "${pin_file}")" -want_sha="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["installerSha256"])' "${pin_file}")" +gateway="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["publisherGateway"])' "${pin_file}")" +curl -fsSL --max-time 60 "${gateway%/}/release.json" -o "${work}/release.json" +python3 - "${work}/release-head.json" "${work}/release.json" <<'PYMANIFEST' +import hashlib, json, sys +head = json.load(open(sys.argv[1]))["payload"] +raw = open(sys.argv[2], "rb").read() +if hashlib.sha256(raw).hexdigest() != head.get("release_sha256"): + sys.exit("Release manifest SHA-256 does not match the signed head") +manifest = json.loads(raw)["payload"] +if any(head.get(key) != manifest.get(key) for key in ("version", "channel")): + sys.exit("Release manifest identity does not match the signed head") +PYMANIFEST +python3 "${root}/scripts/verify-release-head.py" "${work}/release.json" elastos.release.v1 "${maintainer}" +want_sha="$(python3 -c 'import json,re,sys; value=json.load(open(sys.argv[1]))["payload"].get("installer_sha256", ""); assert re.fullmatch("[0-9a-f]{64}",value), "Signed installer hash missing"; print(value)' "${work}/release.json")" python3 "${root}/scripts/verify-release-head.py" "${work}/release-head.json" elastos.release.head.v1 "${maintainer}" echo "Release head signature matches the pinned maintainer" diff --git a/scripts/test.js b/scripts/test.js new file mode 100644 index 0000000..ab0824a --- /dev/null +++ b/scripts/test.js @@ -0,0 +1,26 @@ +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +// macOS /var is a symlink. Removal fixtures need the physical temporary root +// because the production removal guard deliberately refuses symlink parents. +const temp = fs.realpathSync(os.tmpdir()); +// Unit tests must never discover or run a host installation through HOME or PATH. +const home = fs.mkdtempSync(path.join(fs.realpathSync(os.homedir()), '.launcher-unit-')); +const safePath = (process.env.PATH ?? '').split(path.delimiter).filter((dir) => + !fs.existsSync(path.join(dir, 'elastos')) && !fs.existsSync(path.join(dir, 'elastos.exe'))).join(path.delimiter); +const files = fs.readdirSync('test').filter((file) => file.endsWith('.test.js')).map((file) => path.join('test', file)); +// Renderer Chromium and wall-clock process tests must not contend for the host. +const result = spawnSync(process.execPath, ['--test', '--test-concurrency=1', ...files], { + stdio: 'inherit', env: { + ...process.env, + ELASTOS_TEST_CHROMIUM: process.env.ELASTOS_TEST_CHROMIUM || require('playwright').chromium.executablePath(), + HOME: home, USERPROFILE: home, PATH: safePath, + XDG_DATA_HOME: path.join(home, '.local', 'share'), XDG_CONFIG_HOME: path.join(home, '.config'), + XDG_CACHE_HOME: path.join(home, '.cache'), TMPDIR: temp, TMP: temp, TEMP: temp, + }, +}); +// Keep nonempty failure fixtures for diagnosis. Remove only this empty directory. +try { fs.rmdirSync(home); } catch {} +process.exit(result.status ?? 1); diff --git a/scripts/tray-e2e.js b/scripts/tray-e2e.js new file mode 100644 index 0000000..3c17f3b --- /dev/null +++ b/scripts/tray-e2e.js @@ -0,0 +1,93 @@ +const fs = require('node:fs'); +const logPaths = new WeakMap(); + +async function diagnostics(app) { + let state; + try { + state = await app.evaluate(async ({ BrowserWindow }) => ({ + focused: BrowserWindow.getFocusedWindow()?.id ?? null, + windows: await Promise.all(BrowserWindow.getAllWindows().map(async win => ({ + id: win.id, title: win.getTitle(), visible: win.isVisible(), focused: win.isFocused(), + renderer: await win.webContents.executeJavaScript(`({ + kind: document.body.dataset.state, + message: document.querySelector('#message')?.textContent, + primary: document.querySelector('#primary')?.textContent, + disabled: document.querySelector('#primary')?.disabled + })`).catch(error => ({ error: error.message })), + }))), + openedHome: global.__openedHome, + })); + } catch (error) { + const unavailable = `unavailable: ${error.message}`; + state = { focused: unavailable, windows: unavailable, openedHome: unavailable }; + } + let tail; + let fd; + try { + fd = fs.openSync(logPaths.get(app), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + const size = fs.fstatSync(fd).size; + const bytes = Buffer.alloc(Math.min(size, 64 * 1024)); + const count = fs.readSync(fd, bytes, 0, bytes.length, Math.max(0, size - bytes.length)); + tail = bytes.subarray(0, count).toString('utf8').trimEnd().split('\n').slice(-60).join('\n'); + } catch (error) { tail = `unavailable: ${error.message}`; } + finally { if (fd !== undefined) fs.closeSync(fd); } + return `focused window: ${state.focused}\ncurrent window state: ${JSON.stringify(state.windows)}\n__openedHome: ${JSON.stringify(state.openedHome)}\nlauncher log (last 60 lines):\n${tail}`; +} + +async function waitFor(check, timeoutMs, message, app) { + // Health can time out after Quit, when Electron can no longer report its log path. + if (app && !logPaths.has(app)) { + try { + const file = await app.evaluate(() => global.__elastosLogPath); + if (file) logPaths.set(app, file); + } + catch { /* Diagnostics will name the unavailable connection if the app has exited. */ } + } + try { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await check()) return; + await new Promise(resolve => setTimeout(resolve, 250)); + } + throw new Error(typeof message === 'function' ? message() : message); + } catch (error) { + if (!app) throw error; + const detail = await diagnostics(app); + console.error(`${error.message}\n${detail}`); + throw new Error(`${error.message}\n${detail}`, { cause: error }); + } +} + +async function focusWindow(app) { + const id = await app.evaluate(({ app, BrowserWindow }) => { + const win = BrowserWindow.getAllWindows()[0]; + app.focus({ steal: true }); + win.focus(); + return win.id; + }); + // Dock-hidden apps can have no global focused window. Check this window itself. + await waitFor(() => app.evaluate(({ BrowserWindow }, id) => + BrowserWindow.getAllWindows().find(win => win.id === id)?.isFocused(), id), 10000, 'Launcher window did not gain focus', app); +} +async function clickMenu(app, label) { + await app.evaluate((_electron, label) => { + const menu = global.__elastosTrayMenu; + const items = menu.items.flatMap(item => [item, ...(item.submenu?.items || [])]); + const item = items.find(item => item.label === label); + if (!item || !item.enabled) throw new Error(`No enabled menu item: ${label}`); + item.click(); + }, label); +} +async function trayState(app, image) { + await waitFor(() => app.evaluate((_e, image) => global.__elastosTrayState === image, image), 180000, `Tray did not become ${image}`, app); +} +async function noWindow(app) { + let windows = []; + await waitFor(async () => { + windows = await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().map(window => ({ + id: window.id, title: window.getTitle(), visible: window.isVisible(), + }))); + return windows.every(window => !window.visible); + }, 10000, () => `No visible windows after 10000 ms: expected none; last window state: ${JSON.stringify(windows)}`, app); +} +module.exports = { waitFor, clickMenu, trayState, noWindow, focusWindow }; diff --git a/scripts/verify-mac-app.js b/scripts/verify-mac-app.js new file mode 100644 index 0000000..5e462cc --- /dev/null +++ b/scripts/verify-mac-app.js @@ -0,0 +1,95 @@ +const { spawnSync } = require('node:child_process'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +// macOS native Electron paths ignore HOME. Full launches belong only on the +// disposable CI runner. Local artifact verification must use --loader-only. +const loaderOnly = process.argv[3] === '--loader-only'; +if (!loaderOnly && process.env.GITHUB_ACTIONS !== 'true') { + throw new Error('Full packaged launch runs only on the GitHub runner. Use --loader-only locally.'); +} +const helper = path.join(process.argv[2], 'Contents', 'Resources', 'app.asar.unpacked', 'dist', 'native', 'mac-process-info'); +const identity = spawnSync(helper, [String(process.pid)], { encoding: 'utf8', timeout: 5000 }); +assert.equal(identity.status, 0, identity.error?.message || identity.stderr); +const newline = identity.stdout.indexOf('\n'); +assert.match(identity.stdout.slice(0, newline), /^\d+\.\d{6}$/); +assert.equal(identity.stdout.slice(newline + 1), fs.realpathSync(process.execPath)); +console.log('PASS packaged native helper reads the actual executable and process birth time'); +const loaderHome = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'launcher-app-check-')); +const binary = path.join(process.argv[2], 'Contents', 'MacOS', 'ElastOS'); +const marker = 'PASS packaged Electron starts'; +const result = spawnSync(binary, ['-e', `console.log(${JSON.stringify(marker)})`], { + env: { ...process.env, HOME: loaderHome, USERPROFILE: loaderHome, ELECTRON_RUN_AS_NODE: '1' }, + encoding: 'utf8', timeout: 15000, +}); +if (result.status !== 0 || result.stdout.trim() !== marker) { + console.error(`Packaged Electron failed: status=${result.status} signal=${result.signal} error=${result.error?.message ?? ''}`); + console.error(result.stderr); + process.exit(1); +} +console.log(marker); + +async function verifyProfile() { + const { _electron: electron } = require('playwright'); + // Use the runner's native home so Electron's old default and Runtime's path + // reproduce the case-insensitive collision. Refuse a preexisting Runtime. + const home = fs.realpathSync(os.homedir()); + const profile = path.join(home, '.elastos-launcher', 'electron'); + const runtime = path.join(home, 'Library', 'Application Support', 'elastos'); + assert.equal(fs.existsSync(runtime), false, 'packaged check requires a fresh CI Runtime directory'); + const sentinels = { identity: 'scratch identity', signing_key: 'scratch key', 'sources.json': '{"sources":[]}' }; + fs.mkdirSync(runtime, { recursive: true }); + for (const [name, contents] of Object.entries(sentinels)) { + fs.writeFileSync(path.join(runtime, name), contents); + } + const env = { + ...process.env, HOME: home, USERPROFILE: home, + XDG_DATA_HOME: path.join(home, '.local', 'share'), + XDG_CONFIG_HOME: path.join(home, '.config'), + PATH: (process.env.PATH ?? '').split(path.delimiter).filter((dir) => + !fs.existsSync(path.join(dir, 'elastos')) && !fs.existsSync(path.join(dir, 'elastos.exe'))).join(path.delimiter), + }; + delete env.ELECTRON_RUN_AS_NODE; + + for (const attempt of [1, 2]) { + const electronApp = await electron.launch({ executablePath: binary, env, timeout: 30000 }); + const watchdog = setTimeout(() => electronApp.process().kill('SIGKILL'), 90000); + try { + const page = await electronApp.firstWindow({ timeout: 15000 }); + await page.waitForLoadState('domcontentloaded'); + const stored = await page.evaluate(() => { + const prior = localStorage.getItem('packaged-profile-check'); + localStorage.setItem('packaged-profile-check', 'persisted'); + return prior; + }); + if (attempt === 2) assert.equal(stored, 'persisted', 'profile survives launcher restart'); + const actual = await electronApp.evaluate(({ app, session }) => ({ + home: app.getPath('home'), userData: app.getPath('userData'), + sessionData: app.getPath('sessionData'), storage: session.defaultSession.storagePath, + logs: app.getPath('logs'), + })); + console.log(`Packaged launch ${attempt}: ${JSON.stringify(actual)}`); + const entries = fs.readdirSync(runtime); + console.log(`Runtime entries after launch: ${entries.join(', ')}`); + assert.deepEqual(entries.sort(), Object.keys(sentinels).sort(), 'Runtime Home has no Chromium profile entries, including Singleton*'); + assert.equal(actual.home, home); + assert.equal(actual.userData, profile); + assert.equal(actual.sessionData, profile); + assert.equal(actual.storage, profile); + assert.equal(actual.logs, path.join(profile, 'logs')); + assert.ok(fs.statSync(path.join(profile, 'Local Storage')).isDirectory()); + } finally { + try { await electronApp.close(); } finally { clearTimeout(watchdog); } + } + assert.ok(fs.statSync(path.join(profile, 'Preferences')).isFile()); + assert.deepEqual(fs.readdirSync(runtime).sort(), Object.keys(sentinels).sort(), 'Runtime Home is unchanged after quit'); + for (const [name, contents] of Object.entries(sentinels)) { + assert.equal(fs.readFileSync(path.join(runtime, name), 'utf8'), contents); + } + } + console.log('PASS packaged launcher profile and logs use ~/.elastos-launcher/electron across restart; Runtime Home is unchanged'); +} + +if (!loaderOnly) verifyProfile().catch((err) => { console.error(err); process.exitCode = 1; }); diff --git a/scripts/windows-lifecycle-e2e.js b/scripts/windows-lifecycle-e2e.js new file mode 100644 index 0000000..2c17dee --- /dev/null +++ b/scripts/windows-lifecycle-e2e.js @@ -0,0 +1,168 @@ +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const path = require('node:path'); +const { waitFor: poll, clickMenu, trayState, noWindow } = require('./tray-e2e'); +const { isHealthOk, probeGatewayHealth } = require('../dist/main/targets/runtimeGateway'); +const { runtimeDataDir, runtimeUpdateCheckPath } = require('../dist/main/targets/runtimePaths'); + +function proveLiveController() { + const script = [ + 'import json, os, stat', + 'LIMIT = 16384', + 'ROOT = "/root/.local/share/elastos"', + 'LOCK = ROOT + "/host-process.lock"', + 'DIRECTORY = ROOT + "/update-controller"', + 'STATUS = DIRECTORY + "/status.json"', + 'REQUEST = DIRECTORY + "/request.json"', + 'ACTIVE = DIRECTORY + "/active-request.json"', + 'def read_text(path):', + ' current = ""', + ' parts = path.strip("/").split("/")', + ' info = None', + ' for index, part in enumerate(parts):', + ' current = current + "/" + part', + ' info = os.lstat(current)', + ' if stat.S_ISLNK(info.st_mode):', + ' raise SystemExit("refusing a link at " + current)', + ' if index == len(parts) - 1:', + ' if not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT:', + ' raise SystemExit("refusing " + path)', + ' fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)', + ' try:', + ' data = os.read(fd, LIMIT + 1)', + ' finally:', + ' os.close(fd)', + ' if len(data) > LIMIT:', + ' raise SystemExit("refusing " + path)', + ' return data.decode("utf-8", "replace")', + 'def start_id(pid):', + ' raw = read_text("/proc/%d/stat" % pid)', + ' tail = raw.rsplit(")", 1)[1].split()', + ' start = tail[19]', + ' boot = read_text("/proc/sys/kernel/random/boot_id").strip()', + ' if boot:', + ' return "linux:%s:%s" % (boot, start)', + ' return "linux:%s" % start', + 'def ppid_of(pid):', + ' for line in read_text("/proc/%d/status" % pid).splitlines():', + ' if line.startswith("PPid:"):', + ' return int(line.split()[1])', + ' raise SystemExit("no parent")', + 'def command_of(pid):', + ' fd = os.open("/proc/%d/cmdline" % pid, os.O_RDONLY | os.O_NOFOLLOW)', + ' try:', + ' data = os.read(fd, LIMIT)', + ' finally:', + ' os.close(fd)', + ' return data.replace(b"\\x00", b" ").decode("utf-8", "replace")', + 'status = json.loads(read_text(STATUS))', + 'lock = json.loads(read_text(LOCK))', + 'phase = status.get("phase")', + 'if phase not in ("ready", "updated", "restored", "failed"):', + ' raise SystemExit("phase " + str(phase))', + 'controller = status.get("controller_pid")', + 'host = status.get("host_pid")', + 'if type(controller) is not int or type(host) is not int or controller <= 1 or host <= 1:', + ' raise SystemExit("pid")', + 'if lock.get("pid") != host or lock.get("addr") != "localhost:8090":', + ' raise SystemExit("lock")', + 'if not status.get("generation") or lock.get("generation") != status.get("generation"):', + ' raise SystemExit("generation")', + 'if start_id(controller) != status.get("controller_start"):', + ' raise SystemExit("controller is not the live process")', + 'if ppid_of(host) != controller:', + ' raise SystemExit("host parent")', + 'controller_command = command_of(controller)', + 'host_command = command_of(host)', + 'if "update-controller/runtime" not in controller_command or "__update-controller" not in controller_command:', + ' raise SystemExit("controller command")', + 'if "home" not in host_command or "--browser" not in host_command:', + ' raise SystemExit("host command")', + 'if os.path.lexists(REQUEST) or os.path.lexists(ACTIVE):', + ' raise SystemExit("queue is not empty")', + 'print(json.dumps({"phase": phase, "queue": "empty", "controller": controller, "host": host}))', + ].join('\n'); + const result = spawnSync('wsl.exe', ['-d', 'ElastOS', '-u', 'root', '--', 'python3', '-'], { + input: script, + encoding: 'utf8', + timeout: 60000, + windowsHide: true, + }); + if (result.status !== 0) { + throw new Error((result.stderr || result.stdout || 'The update controller was not proved.').trim()); + } + const proof = JSON.parse(result.stdout); + assert.equal(proof.queue, 'empty'); + assert.equal(['ready', 'updated', 'restored', 'failed'].includes(proof.phase), true); + console.log(`PASS controller phase ${proof.phase} is live and the update queue is empty (controller ${proof.controller}, host ${proof.host})`); + console.log('NOT RUN: a System update apply. No newer signed release exists, and apply needs an owner step-up token.'); +} + +function distroUpdateCheck() { + const file = runtimeUpdateCheckPath(runtimeDataDir('linux', '/root', {})); + const result = spawnSync('wsl.exe', ['-d', 'ElastOS', '-u', 'root', '--', 'cat', file], { + encoding: 'utf8', + timeout: 60000, + windowsHide: true, + }); + if (result.status !== 0) { + const detail = `${result.stderr || ''} ${result.stdout || ''}`; + if (!/No such file or directory/.test(detail)) { + throw new Error(detail.trim() || 'The update check file could not be read.'); + } + return null; + } + return JSON.parse(result.stdout); +} + +function launcherUpdateCheck(home) { + const file = path.join(home, '.elastos-launcher', 'update-check.json'); + if (!fs.existsSync(file)) return null; + return JSON.parse(fs.readFileSync(file, 'utf8')); +} + +module.exports = async function (app, page, home) { + const waitFor = (check, timeout, message) => poll(check, timeout, message, app); + const health = wanted => waitFor(async () => isHealthOk(await probeGatewayHealth()) === wanted, 180000, `Home health did not become ${wanted}`); + await app.evaluate(({ shell }) => { + global.__openedHome = []; + shell.openExternal = async (url) => { global.__openedHome.push(url); }; + }); + await clickMenu(app, 'Open Home'); + await waitFor(() => app.evaluate(() => global.__openedHome.includes('http://localhost:8090/home/')), 10000, 'Open Home did not open localhost'); + assert.deepEqual(await app.evaluate(() => global.__openedHome), ['http://localhost:8090/home/']); + const response = await fetch('http://localhost:8090/home/'); + assert.equal(response.status, 200); + console.log('PASS Open Home invokes the browser with localhost:8090/home/ and Home returns HTTP 200'); + + await noWindow(app); + await health(true); + await clickMenu(app, 'Stop Home'); + await trayState(app, 'stopped'); + await health(false); + console.log('PASS Stop Home closes the listener'); + await clickMenu(app, 'Start Home'); + await trayState(app, 'running'); + await health(true); + console.log('PASS Start Home becomes healthy'); + assert.deepEqual(await app.evaluate(() => global.__openedHome), ['http://localhost:8090/home/']); + proveLiveController(); + const runtime = distroUpdateCheck(); + if (runtime) { + assert.equal(runtime.outcome, 'up_to_date'); + assert.equal(runtime.offered, false); + console.log('PASS elastos update --check keeps the Runtime up_to_date record'); + } else { + const launcher = launcherUpdateCheck(home); + assert.ok(launcher); + assert.equal(launcher.outcome, 'up_to_date'); + assert.equal(launcher.offered, false); + console.log('PASS elastos update --check stores up_to_date in the launcher record'); + } + const closed = app.waitForEvent('close'); + await clickMenu(app, 'Quit ElastOS'); await closed; + await health(false); + console.log('PASS Quit ElastOS stops Home'); + return app; +}; diff --git a/src/main/homeMenu.ts b/src/main/homeMenu.ts new file mode 100644 index 0000000..8725e4d --- /dev/null +++ b/src/main/homeMenu.ts @@ -0,0 +1,75 @@ +import type { MenuItemConstructorOptions } from 'electron'; +import type { TargetStatus, UpdateCheck } from './targets/types'; + +export type HomeActionKind = 'start' | 'stop' | 'update' | 'open' | 'maintenance'; +export interface HomeModel { + observed: TargetStatus; + inFlight: { kind: HomeActionKind; generation: number } | null; + failure: string | null; + quitting: boolean; +} +export interface MenuState extends HomeModel { + platform: string; + login?: boolean; + pc2?: boolean; + update?: Pick | null; +} +export interface MenuActions { + open(): void; start(): void; stop(): void; update(): void; login(enabled: boolean): void; + diagnostics(): void; logs(): void; removePc2(): void; reset(): void; uninstall(): void; about(): void; quit(): void; +} +const statusText: Record = { + running: 'Home is running', stopped: 'Home is stopped', starting: 'Home is starting', + stopping: 'Home is stopping', error: 'Home needs attention', + 'not-installed': 'Home is not installed', 'other-home': 'Another Home is running', +}; +const actionText: Record = { + start: 'Starting Home…', stop: 'Stopping Home…', update: 'Updating ElastOS…', + open: 'Opening Home…', maintenance: 'Working on ElastOS…', +}; +function presentation(state: HomeModel) { + const busy = state.quitting || state.inFlight !== null; + const status = busy ? 'starting' : state.failure ? 'error' : state.observed; + const label = state.quitting ? 'Stopping Home…' : state.inFlight ? actionText[state.inFlight.kind] + : state.failure || statusText[state.observed]; + return { status, label, idle: !busy && status !== 'other-home', busy }; +} +export function trayPresentation(state: HomeModel) { + const { status, label, busy } = presentation(state); + return { + image: busy ? 'busy' : status === 'running' ? 'running' + : ['error', 'other-home'].includes(status) ? 'attention' : 'stopped', + tooltip: `ElastOS: ${label}`, + }; +} + +/** This template is the menu on every platform, and the source of the review artifacts. */ +export function buildHomeMenu(state: MenuState, actions: MenuActions): MenuItemConstructorOptions[] { + const separator: MenuItemConstructorOptions = { type: 'separator' }; + const { idle, status, label } = presentation(state); + return [ + { label, enabled: false }, + separator, + { label: 'Open Home', accelerator: 'CommandOrControl+O', + ...(state.platform === 'darwin' ? { sublabel: 'localhost:8090' } : {}), + enabled: idle, click: actions.open }, + { label: status === 'running' ? 'Stop Home' : 'Start Home', + enabled: idle && ['running', 'stopped', 'starting', 'stopping', 'error'].includes(status), + click: status === 'running' ? actions.stop : actions.start }, + ...(state.update?.updateAvailable && state.update.latest ? [separator, + { label: `Update to ${state.update.latest}…`, enabled: idle, click: actions.update }] : []), + separator, + { label: 'Start Home at Login', type: 'checkbox', enabled: idle, checked: Boolean(state.login), click: item => actions.login(item.checked) }, + { label: 'Troubleshoot', submenu: [ + { label: 'Copy Diagnostics', click: actions.diagnostics }, + { label: 'Show Home Logs', click: actions.logs }, + ...(state.pc2 ? [{ label: 'Remove Old PC2 Files…', enabled: idle, click: actions.removePc2 }] : []), + separator, + { label: 'Reset ElastOS…', enabled: idle, click: actions.reset }, + { label: 'Uninstall ElastOS…', enabled: idle, click: actions.uninstall }, + ] }, + separator, + { label: 'About ElastOS', click: actions.about }, + { label: 'Quit ElastOS', accelerator: 'CommandOrControl+Q', click: actions.quit }, + ]; +} diff --git a/src/main/index.ts b/src/main/index.ts index 3200bc1..1badb31 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,287 +1,322 @@ -import { app, BrowserWindow, dialog, ipcMain, Tray, Menu, nativeImage, shell } from 'electron'; +import { app, BrowserWindow, clipboard, dialog, ipcMain, Tray, Menu, nativeImage, shell, screen } from 'electron'; +import * as fs from 'fs'; +import * as os from 'os'; import * as path from 'path'; import log from 'electron-log'; -import { createDefaultLaunchController, finishQuitAfterGatewayStop, TargetStatus } from './launchController'; +import { createDefaultLaunchController, finishQuitAfterGatewayStop, isLoginLaunch, startHomeAtLogin, homeLogFolder } from './launchController'; import { describeLegacyPc2OnThisComputer, removeLegacyPc2OnThisComputer, withSupportBundle } from './legacyPc2Removal'; +import { contentWindowBounds } from './launcherWindow'; +import { buildHomeMenu, HomeModel, HomeActionKind, trayPresentation } from './homeMenu'; +import { createOpenHome } from './openHome'; +import { scrubSupportText } from './targets/preflight'; +import type { UpdateCheck } from './targets/types'; -const launch = createDefaultLaunchController(process.env); +const platform = process.platform; -// Set app name for dock/taskbar and menu bar +// Chromium never shares the Runtime Home, even on case-insensitive Macs. +const electronData = path.join(os.homedir(), '.elastos-launcher', 'electron'); +fs.mkdirSync(electronData, { recursive: true, mode: 0o700 }); +app.setPath('userData', electronData); +app.setPath('sessionData', electronData); +if (!app.requestSingleInstanceLock()) app.exit(0); +app.setAppLogsPath(path.join(electronData, 'logs')); app.setName('ElastOS'); - -// For macOS, set the name before app is ready -if (process.platform === 'darwin') { - app.name = 'ElastOS'; -} - -// Set dock icon on macOS -if (process.platform === 'darwin') { - const iconPath = path.join(__dirname, '../../resources/icon.png'); - const { nativeImage } = require('electron'); - const icon = nativeImage.createFromPath(iconPath); - if (!icon.isEmpty()) { - app.dock?.setIcon(icon); - } -} - +log.transports.file.level = 'info'; +log.transports.console.level = 'debug'; +export const launch = createDefaultLaunchController(process.env); let mainWindow: BrowserWindow | null = null; let tray: Tray | null = null; -let isQuitting = false; +let actionGeneration = 0; +let menuSignature = ''; +const homeState: HomeModel = { observed: 'stopped', inFlight: null, failure: null, quitting: false }; +let offer: UpdateCheck | null = null; +let legacyItems: Awaited> = []; const quitGate = { started: false, ready: false }; -let currentStatus: TargetStatus = 'stopped'; +type WindowState = { + kind: 'install' | 'progress' | 'error' | 'update'; + ready?: boolean; message?: string; actionLabel?: string; releaseNotes?: boolean; +}; +let windowState: WindowState = { kind: 'install' }; +type HomeAction = (generation: number) => Promise; +let retry: HomeAction | null = null; +let failureError: unknown; -// Configure logging -log.transports.file.level = 'info'; -log.transports.console.level = 'debug'; - -function createWindow(): void { - mainWindow = new BrowserWindow({ - width: 500, - height: 860, - minWidth: 420, - minHeight: 560, - resizable: true, - webPreferences: { - preload: path.join(__dirname, '../preload/index.js'), - contextIsolation: true, - nodeIntegration: false - }, - titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default', - backgroundColor: '#121212', - show: false, - icon: path.join(__dirname, '../../resources/icon.png') - }); - - mainWindow.loadFile(path.join(__dirname, '../../src/renderer/index.html')); - - mainWindow.once('ready-to-show', async () => { - mainWindow?.show(); - // Replay into this window only. Writing the same lines back to the file - // log duplicates them each time macOS creates the window again. - const prior = await launch.getLogs(); - for (const line of prior.split('\n').filter(Boolean)) { - mainWindow?.webContents.send('elastos:log', line); - } - - // Check initial status - currentStatus = await launch.getStatus(); - mainWindow?.webContents.send('elastos:status', currentStatus); - }); - - mainWindow.on('close', (event) => { - if (!isQuitting) { - event.preventDefault(); - mainWindow?.hide(); - } - }); +// Reads own only the observation. An older request cannot replace a newer action/read. +async function readStatus(): Promise { + const generation = actionGeneration; + try { + const observed = await launch.getStatus(); + if (generation === actionGeneration) homeState.observed = observed; + } catch (error) { log.error(String(error)); } + updateMenu(); } -function createTray(): void { - // Simple tray icon - const iconPath = path.join(__dirname, '../../resources/icon.png'); - let icon: Electron.NativeImage; - +function setWindowState(state: WindowState): void { + windowState = state; + mainWindow?.webContents.send('elastos:windowState', state); +} +function showWindow(state: WindowState): void { + setWindowState(state); + if (!mainWindow) { + const window = new BrowserWindow({ + width: 360, height: 320, useContentSize: true, resizable: false, + webPreferences: { preload: path.join(__dirname, '../preload/index.js'), contextIsolation: true, nodeIntegration: false }, + titleBarStyle: platform === 'darwin' ? 'hiddenInset' : 'default', + backgroundColor: '#f5f5f5', show: false, autoHideMenuBar: true, + icon: path.join(__dirname, '../../resources/icon.png'), + }); + mainWindow = window; + window.loadFile(path.join(__dirname, '../../src/renderer/index.html')); + window.once('ready-to-show', () => { window.show(); window.focus(); }); + window.on('closed', () => { mainWindow = null; }); + } else { + if (mainWindow.isMinimized()) mainWindow.restore(); + mainWindow.show(); mainWindow.focus(); + } +} +function closeWindow(): void { mainWindow?.close(); } +async function showError(error: unknown, again: HomeAction | null = null, generation = actionGeneration): Promise { + log.error(error instanceof Error ? error.message : String(error)); + const failure = await launch.describeFailure(error).catch(() => null); + const message = failure?.message || 'ElastOS could not finish.'; + if (homeState.quitting || generation !== actionGeneration) return null; + retry = again; + failureError = error; + showWindow({ kind: 'error', message, + actionLabel: failure?.fixLabel ? 'Try Again' : (again ? 'Try Again' : 'Show Logs') }); + return message; +} +async function reportReadError(action: () => Promise): Promise { + const generation = actionGeneration; + try { await action(); } catch (error) { await showError(error, null, generation); } +} +async function perform(kind: HomeActionKind, action: HomeAction): Promise { + if (homeState.inFlight || homeState.quitting) return; + const generation = ++actionGeneration; + homeState.inFlight = { kind, generation }; + homeState.failure = null; + updateMenu(); + try { await action(generation); } catch (error) { homeState.failure = await showError(error, action, generation); } + finally { + homeState.inFlight = null; + updateMenu(); + await readStatus(); + } +} +// Signed 2.0.0's Home command opens the browser itself on a cold start. +async function startHome(): Promise { await launch.start(); } +async function stopHome(): Promise { await launch.stop(); } +async function openHome(): Promise { + await createOpenHome({ getStatus: () => launch.getStatus(), start: () => launch.start(), openInBrowser: () => launch.openInBrowser() }, () => showWindow({ kind: 'install' }), true)(); +} +async function openApp(): Promise { await perform('open', openHome); } +async function copyDiagnostics(): Promise { + const file = log.transports.file.getFile().path; + let tail = ''; + let fd: number | undefined; try { - icon = nativeImage.createFromPath(iconPath); - if (icon.isEmpty()) { - // Fallback to a simple icon - icon = nativeImage.createFromDataURL( - 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAA7AAAAOwBeShxvQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAH5SURBVFiF7Ze/axRBFMc/M7t3yUWjhYVYiI2NjQERbfwPrGxEOwsLsRAsLPwPbGwsxMbKQrCwEWzEQrDQRhALC8FCCYiIRuNdkuzujsXu3e7l7nKXM+D3wzDM8N7MZ+a9NzOQUXAIGAN2s+0CtXBkCfgD/AJ+ArPAT2ANWBdRFXgEZuUmcAEodshrA5yECcBTcBB4BZwGfOAZ8ETESv+X+i5wEbiY9H0Z2AmMA/uTvieqGuvpxfMYOJbSrqvOIEACMpAJSAJeAF5S9gM2U2OaAYmqhcAz8BpoBc+BzuuLdEiKZrLMSj0B7JIGFQK1wBM/xhp05QfsBKoNYC8wDzzvFyQJiCeJN8DFaJHXxXJV1tQ68IaYcLrpDyLoJ5APvCOLCRwNVCcJYy2wyQs7KiZlJuoB79oj/wBwtXNOtfYmGIrLWpLK+w5c60UYTANFJOsYcKRPCHPAAWASeMojwChWBxTpFrKu2vQC4BlwyUeFE0KxP0AqYT3JQE+B4SSwH6hnQAFYBO6JqPQKkQZYS5bXgccitP8N/oEKMCGi3C/IEPARuNcvRIb+yO4nngvMAe+Tzr5BkoBBYDfwot9qSOsUyxUNjQ8i6sMggmRoD7nHI/+wHTAGPBNR7hciCRj6LpjCxBpw00d5nyAZGgT2AEv/M/4vmHGRlTWP0ioAAAAASUVORK5CYII=' - ); + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + const stat = fs.fstatSync(fd); + if (stat.isFile()) { + const bytes = Buffer.alloc(Math.min(stat.size, 64 * 1024)); + const count = fs.readSync(fd, bytes, 0, bytes.length, Math.max(0, stat.size - bytes.length)); + tail = bytes.subarray(0, count).toString('utf8'); } - } catch (e) { - icon = nativeImage.createFromDataURL( - 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAA7AAAAOwBeShxvQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAH5SURBVFiF7Ze/axRBFMc/M7t3yUWjhYVYiI2NjQERbfwPrGxEOwsLsRAsLPwPbGwsxMbKQrCwEWzEQrDQRhALC8FCCYiIRuNdkuzujsXu3e7l7nKXM+D3wzDM8N7MZ+a9NzOQUXAIGAN2s+0CtXBkCfgD/AJ+ArPAT2ANWBdRFXgEZuUmcAEodshrA5yECcBTcBB4BZwGfOAZ8ETESv+X+i5wEbiY9H0Z2AmMA/uTvieqGuvpxfMYOJbSrqvOIEACMpAJSAJeAF5S9gM2U2OaAYmqhcAz8BpoBc+BzuuLdEiKZrLMSj0B7JIGFQK1wBM/xhp05QfsBKoNYC8wDzzvFyQJiCeJN8DFaJHXxXJV1tQ68IaYcLrpDyLoJ5APvCOLCRwNVCcJYy2wyQs7KiZlJuoB79oj/wBwtXNOtfYmGIrLWpLK+w5c60UYTANFJOsYcKRPCHPAAWASeMojwChWBxTpFrKu2vQC4BlwyUeFE0KxP0AqYT3JQE+B4SSwH6hnQAFYBO6JqPQKkQZYS5bXgccitP8N/oEKMCGi3C/IEPARuNcvRIb+yO4nngvMAe+Tzr5BkoBBYDfwot9qSOsUyxUNjQ8i6sMggmRoD7nHI/+wHTAGPBNR7hciCRj6LpjCxBpw00d5nyAZGgT2AEv/M/4vmHGRlTWP0ioAAAAASUVORK5CYII=' - ); + } catch { /* The current session diagnostics are still available. */ } + finally { if (fd !== undefined) fs.closeSync(fd); } + clipboard.writeText(scrubSupportText(`${await launch.getDiagnostics()}\n${tail}`)); +} +async function showLogs(): Promise { + const error = await shell.openPath(homeLogFolder(platform, os.homedir(), process.env)); + if (error) throw new Error(error); +} +async function confirm(options: Electron.MessageBoxOptions): Promise { + return mainWindow ? dialog.showMessageBox(mainWindow, options) : dialog.showMessageBox(options); +} +async function reset(): Promise { + const backup = await launch.describeResetBackup(); + if ('blocked' in backup && backup.blocked) throw new Error(String(backup.blocked)); + const answer = await confirm({ type: 'warning', title: 'Reset ElastOS', message: 'Reset ElastOS?', + detail: 'This removes ElastOS and your Home data so you can install it again.', + buttons: ['Cancel', 'Reset'], defaultId: 0, cancelId: 0, noLink: true, + ...(backup.present ? { checkboxLabel: backup.enough ? 'Back Up First' : 'Reset Without a Backup', checkboxChecked: backup.enough } : {}) }); + if (answer.response !== 1) return; + if (backup.present && !backup.enough && !answer.checkboxChecked) return; + await launch.resetRuntime({ backup: backup.present && backup.enough && answer.checkboxChecked }); + showWindow({ kind: 'install' }); +} +async function uninstall(): Promise { + const answer = await confirm({ type: 'warning', title: 'Uninstall ElastOS', message: 'Uninstall ElastOS?', + detail: 'This removes ElastOS from this computer and keeps your Home data unless you choose to delete it.', + checkboxLabel: 'Also delete my Home data', checkboxChecked: false, + buttons: ['Cancel', 'Uninstall'], defaultId: 0, cancelId: 0, noLink: true }); + if (answer.response !== 1) return; + const result = await launch.uninstall(async prompt => (await confirm({ type: 'warning', title: prompt.title, + message: prompt.message, detail: prompt.detail, buttons: [prompt.cancelLabel, prompt.confirmLabel], + defaultId: 0, cancelId: 0, noLink: true })).response === 1, answer.checkboxChecked); + if (result?.linuxCopyMessage) log.info(result.linuxCopyMessage); + launch.setOpenAtLogin(false); + closeWindow(); +} +async function removePc2(generation: number): Promise { + const items = await describeLegacyPc2OnThisComputer(); + if (!items.length) return; + const answer = await confirm({ type: 'warning', title: 'Remove Old PC2 Files', message: 'Remove old PC2 files?', + detail: `PC2 was the earlier ElastOS Personal Cloud app; this removes its old files.\n${items.map(item => item.path).join('\n')}`, + checkboxLabel: 'Back Up First', checkboxChecked: true, + buttons: ['Cancel', 'Remove'], defaultId: 0, cancelId: 0, noLink: true }); + if (answer.response !== 1) return; + const result = await removeLegacyPc2OnThisComputer({ backup: answer.checkboxChecked, paths: items.map(item => item.path) }); + if (!result.ok) { + const bundle = await launch.saveSupportBundle().catch(() => ''); + throw new Error(bundle ? withSupportBundle(result.message, bundle) : result.message); } - - tray = new Tray(icon.resize({ width: 16, height: 16 })); - tray.setToolTip('ElastOS'); - updateTrayMenu(); - - tray.on('click', () => { - if (mainWindow?.isVisible()) { - mainWindow.hide(); - } else { - mainWindow?.show(); - } + await refreshMaintenance(generation); +} +function updateMenu(): void { + if (!tray) return; + const state = { ...homeState, platform, login: launch.getOpenAtLogin(), pc2: legacyItems.length > 0, update: offer }; + const signature = JSON.stringify(state); + if (signature === menuSignature) return; + menuSignature = signature; + const presentation = trayPresentation(state); + const icon = nativeImage.createFromPath(path.join(__dirname, `../../resources/tray/${presentation.image}${platform === 'darwin' ? 'Template' : ''}.png`)).resize({ width: 18, height: 18 }); + if (platform === 'darwin') icon.setTemplateImage(true); + tray.setImage(icon); + tray.setToolTip(presentation.tooltip); + const template = buildHomeMenu(state, { + open: () => { void openApp(); }, start: () => { void perform('start', startHome); }, stop: () => { void perform('stop', stopHome); }, + update: () => { if (offer) showWindow({ kind: 'update', message: `Update ElastOS to ${offer.latest}?`, releaseNotes: Boolean(offer.releaseUrl) }); }, + login: enabled => { void perform('maintenance', async () => { launch.setOpenAtLogin(enabled); }); }, + diagnostics: () => { void reportReadError(copyDiagnostics); }, logs: () => { void reportReadError(showLogs); }, + removePc2: () => { void perform('maintenance', removePc2); }, reset: () => { void perform('maintenance', reset); }, uninstall: () => { void perform('maintenance', uninstall); }, + about: () => app.showAboutPanel(), quit: () => app.quit(), }); + const menu = Menu.buildFromTemplate(template); + tray.setContextMenu(menu); + if (platform === 'darwin') Menu.setApplicationMenu(Menu.buildFromTemplate([ + { label: 'ElastOS', submenu: template }, { role: 'editMenu' }, + ])); + // Real Electron menu objects, used by the packaged CI tests. + (global as typeof globalThis & { __elastosTrayMenu?: Menu; __elastosTrayState?: string }).__elastosTrayMenu = menu; + (global as typeof globalThis & { __elastosTrayState?: string }).__elastosTrayState = presentation.image; } - -function updateTrayMenu(): void { - const statusLabels: Record = { - 'running': '🟢 Running', - 'stopped': '⚫ Stopped', - 'starting': '🟡 Starting...', - 'stopping': '🟡 Stopping...', - 'error': '🔴 Error', - 'not-installed': '⚪ Not Installed' - }; - - const contextMenu = Menu.buildFromTemplate([ - { label: `Status: ${statusLabels[currentStatus]}`, enabled: false }, - { type: 'separator' }, - { - label: 'Start', - enabled: currentStatus === 'stopped' || currentStatus === 'error', - click: () => { void launch.start(); } - }, - { - label: 'Stop', - enabled: currentStatus === 'running', - click: () => { void launch.stop(); } - }, - { type: 'separator' }, - { - label: 'Open my computer', - enabled: currentStatus === 'running', - click: () => launch.openInBrowser() - }, - { type: 'separator' }, - { label: 'Show Window', click: () => mainWindow?.show() }, - { - label: 'Quit', - click: () => { - isQuitting = true; - app.quit(); - } - } - ]); - - tray?.setContextMenu(contextMenu); +async function refreshMaintenance(generation = actionGeneration): Promise { + const items = await describeLegacyPc2OnThisComputer().catch(error => { log.warn(String(error)); return []; }); + const update = await launch.checkForUpdate().catch(error => { log.warn(String(error)); return null; }); + if (generation !== actionGeneration || homeState.quitting) return; + legacyItems = items; offer = update; + updateMenu(); } - -// Set up status change listener -launch.onStatusChange((status) => { - currentStatus = status; - mainWindow?.webContents.send('elastos:status', status); - updateTrayMenu(); -}); - -// Set up log listener -launch.onLog((logMessage) => { - mainWindow?.webContents.send('elastos:log', logMessage); -}); - -// IPC handlers. The preload exposes these as window.elastos. -ipcMain.handle('elastos:getStatus', () => launch.getStatus()); -ipcMain.handle('elastos:start', () => launch.start()); -ipcMain.handle('elastos:stop', () => launch.stop()); -ipcMain.handle('elastos:restart', () => launch.restart()); -ipcMain.handle('elastos:getLogs', (_, lines) => launch.getLogs(lines)); -ipcMain.handle('elastos:isInstalled', () => launch.isInstalled()); -ipcMain.handle('elastos:openBrowser', () => launch.openInBrowser()); -ipcMain.handle('elastos:install', async (event) => { - return launch.install((msg) => { - event.sender.send('elastos:installProgress', msg); +function step(message: string): void { + log.info(message); + setWindowState({ kind: 'progress', message: /start|home ready/i.test(message) ? 'Starting Home' : /download|fetch/i.test(message) ? 'Downloading' : 'Setting up' }); +} +async function install(login: boolean): Promise { + await perform('start', async generation => { + launch.setOpenAtLogin(login); + showWindow({ kind: 'progress', message: 'Downloading' }); + await launch.install(step); + if (homeState.quitting || generation !== actionGeneration) return; + step('Starting Home'); + await launch.start(); + if (homeState.quitting || generation !== actionGeneration) return; + setWindowState({ kind: 'install', ready: true, message: 'Home is ready.' }); + void refreshMaintenance(generation); }); -}); - -ipcMain.handle('elastos:uninstall', () => { - // The second question on Windows, asked here in the main process so the - // window alone cannot answer it. Cancel is the default button. - const confirmRemoval = async (prompt: { title: string; message: string; detail: string; confirmLabel: string; cancelLabel: string }) => { - const options = { - type: 'warning' as const, - title: prompt.title, - message: prompt.message, - detail: prompt.detail, - buttons: [prompt.cancelLabel, prompt.confirmLabel], - defaultId: 0, - cancelId: 0, - noLink: true, - }; - const answer = mainWindow ? await dialog.showMessageBox(mainWindow, options) : await dialog.showMessageBox(options); - return answer.response === 1; - }; - return launch.uninstall(confirmRemoval); -}); -ipcMain.handle('elastos:resetRuntime', (_event, choice: unknown) => { - const backup = choice && typeof choice === 'object' ? (choice as { backup?: unknown }).backup : undefined; - return launch.resetRuntime({ backup }); -}); -ipcMain.handle('elastos:describeResetBackup', () => launch.describeResetBackup()); - -// Version and updates -ipcMain.handle('elastos:getVersion', () => launch.getVersion()); -ipcMain.handle('elastos:checkForUpdate', () => launch.checkForUpdate()); -ipcMain.handle('elastos:update', async (event) => { - return launch.update((msg) => { - event.sender.send('elastos:updateProgress', msg); +} +async function update(): Promise { + if (!offer?.updateAvailable) return; + await perform('update', async generation => { + showWindow({ kind: 'progress', message: 'Downloading' }); + await launch.update(step); + if (await launch.getStatus() !== 'running') await launch.start(); + if (generation === actionGeneration) offer = null; + closeWindow(); }); -}); +} +// Only the action catch records a failure; controller notifications do not own menu state. +launch.onLog(message => log.info(message)); -ipcMain.handle('elastos:getLaunchInfo', () => launch.getLaunchInfo()); -ipcMain.handle('elastos:getPreflight', () => launch.getPreflight()); -ipcMain.handle('elastos:getDiagnostics', () => launch.getDiagnostics()); -ipcMain.handle('elastos:saveSupportBundle', () => launch.saveSupportBundle()); -ipcMain.handle('elastos:describeLegacyPc2', async () => ({ items: await describeLegacyPc2OnThisComputer() })); -ipcMain.handle('elastos:removeLegacyPc2', async (_event, backup: unknown, paths: unknown) => { - const confirmed = Array.isArray(paths) ? paths.filter((entry): entry is string => typeof entry === 'string') : []; - const result = await removeLegacyPc2OnThisComputer({ backup: backup === true, paths: confirmed }); - if (result.ok) return result; - let bundle = ''; - try { - bundle = await launch.saveSupportBundle(); - } catch { - bundle = ''; - } - const message = bundle ? withSupportBundle(result.message, bundle) : result.message; - throw new Error(message); -}); -ipcMain.handle('elastos:describeFailure', () => launch.describeFailure()); -ipcMain.handle('elastos:fixFailure', () => launch.fixFailure()); -ipcMain.handle('elastos:resumeInstallPlan', () => launch.resumeInstallPlan()); -ipcMain.handle('elastos:finishResumeInstall', (_event, ok: unknown) => { - launch.finishResumeInstall(ok === true); -}); -ipcMain.handle('elastos:setOpenAtLogin', (_, enabled: boolean) => { - launch.setOpenAtLogin(enabled); - return launch.getOpenAtLogin(); -}); -ipcMain.handle('elastos:rollback', async (event) => { - return launch.rollback((msg) => { - event.sender.send('elastos:updateProgress', msg); +// Only the current small window may invoke its actions. No destructive renderer IPC. +function handle(name: string, action: (...args: any[]) => unknown): void { + ipcMain.handle(`elastos:${name}`, (event, ...args) => { + if (event.sender !== mainWindow?.webContents) throw new Error('Unknown window.'); + return action(...args); }); +} +handle('getWindowState', () => windowState); +handle('install', login => windowState.kind === 'install' && !windowState.ready ? install(login === true) : undefined); +handle('update', () => windowState.kind === 'update' ? update() : undefined); +handle('retry', () => perform('maintenance', async generation => { + const error = failureError; + const failure = await launch.describeFailure(error); + if (failure.fixLabel) { + if (platform === 'win32' && failure.kind === 'windows') { + const answer = await confirm({ type: 'question', title: 'Set Up ElastOS', message: 'Set up ElastOS on this computer?', + detail: 'Windows may ask for permission to enable Linux support and may need to restart.', + buttons: ['Cancel', 'Set Up'], defaultId: 0, cancelId: 0, noLink: true }); + if (answer.response !== 1) return; + } + const result = await launch.fixFailure(error); + const windowsReady = failure.kind === 'windows' && !(await launch.getPreflight()).checks + .some(check => check.id === 'windows' && check.level === 'block'); + if (windowsReady && retry) await retry(generation); + else if (result === 'ready') { + if (await launch.isInstalled()) { await openHome(); closeWindow(); } + else showWindow({ kind: 'install' }); + } + else throw error; + } else if (retry) await retry(generation); + else await showLogs(); +})); +handle('openHome', async () => { await openApp(); if (windowState.kind !== 'error') closeWindow(); }); +handle('copyDiagnostics', copyDiagnostics); +handle('releaseNotes', () => { if (offer?.releaseUrl && /^https:\/\//.test(offer.releaseUrl)) return shell.openExternal(offer.releaseUrl); }); +handle('closeWindow', closeWindow); +ipcMain.on('elastos:contentSize', (event, height: unknown) => { + if (!mainWindow || event.sender !== mainWindow.webContents || typeof height !== 'number' || !Number.isFinite(height) || height <= 0) return; + const bounds = mainWindow.getBounds(); + mainWindow.setBounds(contentWindowBounds(Math.max(320, height), bounds, mainWindow.getContentBounds(), screen.getDisplayMatching(bounds).workArea)); }); - -// App lifecycle -app.whenReady().then(() => { - createWindow(); - createTray(); +app.on('second-instance', () => { void app.whenReady().then(openApp); }); +app.on('activate', () => { void openApp(); }); +app.on('window-all-closed', () => {}); +app.whenReady().then(async () => { + app.dock?.hide(); + app.setAboutPanelOptions({ applicationName: 'ElastOS', applicationVersion: '2.0.0', version: '', copyright: 'Copyright © Elacity Labs', iconPath: path.join(__dirname, '../../resources/icon.png') }); + if (platform !== 'darwin') Menu.setApplicationMenu(null); + tray = new Tray(nativeImage.createFromPath(path.join(__dirname, '../../resources/tray/stoppedTemplate.png'))); + (global as typeof globalThis & { __elastosTray?: true }).__elastosTray = true; + (global as typeof globalThis & { __elastosLogPath?: string }).__elastosLogPath = log.transports.file.getFile().path; + updateMenu(); + // macOS and Linux show their attached context menu on primary activation. + if (platform === 'win32') tray.on('click', () => tray?.popUpContextMenu()); + const login = isLoginLaunch(platform, process.argv, platform === 'darwin' ? app.getLoginItemSettings() : {}); if (launch.getOpenAtLogin()) launch.setOpenAtLogin(true); -}); - -app.on('window-all-closed', () => { - if (process.platform !== 'darwin') { - isQuitting = true; - app.quit(); - } -}); - -app.on('activate', () => { - if (BrowserWindow.getAllWindows().length === 0) { - createWindow(); - } else { - mainWindow?.show(); - } -}); - -app.on('before-quit', (event) => { - isQuitting = true; - void finishQuitAfterGatewayStop(quitGate, event, () => launch.shutdown(), () => { - app.quit(); - }, { - log: (line) => log.error(line), - onBudget: () => launch.forceStopGateway(), - onStopping: () => { - currentStatus = 'stopping'; - tray?.setToolTip('Stopping ElastOS…'); - mainWindow?.webContents.send('elastos:status', 'stopping'); - updateTrayMenu(); - log.info('Stopping ElastOS before quit.'); - }, - }).catch((err: unknown) => { - log.error(err instanceof Error ? err.message : String(err)); - }); + if (login) await perform('start', () => startHomeAtLogin(launch.getOpenAtLogin(), launch)); + else if (await launch.resumeInstallPlan() === 'install') { + await install(launch.getOpenAtLogin()); + launch.finishResumeInstall(windowState.ready === true); + } else await openApp(); + void refreshMaintenance(); + let checkingStatus = false; + const statusTimer = setInterval(async () => { + if (homeState.inFlight || homeState.quitting || checkingStatus) return; + checkingStatus = true; + try { await readStatus(); } + finally { checkingStatus = false; } + }, 2000); + statusTimer.unref(); + const updateTimer = setInterval(() => { if (!homeState.inFlight && !homeState.quitting) void refreshMaintenance(); }, 60 * 60 * 1000); + updateTimer.unref(); +}).catch(error => { void showError(error); }); +app.on('before-quit', event => { + if (!homeState.quitting) ++actionGeneration; + homeState.quitting = true; + updateMenu(); + void finishQuitAfterGatewayStop(quitGate, event, () => launch.shutdown(), () => app.quit(), { + log: line => log.error(line), onBudget: () => launch.forceStopGateway(), + onStopping: () => log.info('Stopping Home before quit.'), + }).catch(error => log.error(String(error))); }); diff --git a/src/main/launchController.ts b/src/main/launchController.ts index a109b59..27cacdb 100644 --- a/src/main/launchController.ts +++ b/src/main/launchController.ts @@ -1,7 +1,13 @@ import * as os from 'os'; +import { runtimeDataDir, runtimeJoin } from './targets/runtimePaths'; +import { DISTRO_HOME, DISTRO_NAME } from './targets/windowsRuntime'; +export { isLoginLaunch, startHomeAtLogin } from './targets/openAtLogin'; + import { applyOpenAtLogin, readOpenAtLogin } from './targets/openAtLogin'; import { buildDiagnostics, collectPreflight, PreflightReport, saveCollectedSupportBundle } from './targets/preflight'; -import { confirmInstalledGateway, isForeignGatewayError, isHealthOk, probeGatewayHealth, STOP_GRACE_MS } from './targets/runtimeGateway'; +import { confirmInstalledGateway, homeLaunchForPlatform, isForeignGatewayError, isHealthOk, probeGatewayHealth, STOP_GRACE_MS } from './targets/runtimeGateway'; + +export { homeLaunchForPlatform }; import { collectFailureFacts, failureScreen, FailureScreen, fixCollectedFailure, windowsFixResult } from './targets/runtimeRecovery'; import { resolveLaunchTargetId } from './targets/preferences'; import { LAUNCH_TARGET_ENV, retiredPc2Notice } from './targets/registry'; @@ -10,16 +16,22 @@ import { setRuntimeLogSink } from './targets/runtimeGateway'; import { loadActiveRuntimePin } from './targets/runtimePin'; import { browserNote } from './targets/runtimeSupport'; import { runtimeHeadStore } from './targets/runtimeUpdate'; -import { rollbackRuntimeUpdate } from './targets/runtimeTarget'; import { BackupDescription, describeRuntimeBackupOnThisComputer } from './targets/runtimeBackup'; import { resetRuntimeOnThisComputer, ResetResult } from './targets/runtimeUninstall'; import { describeDistroBackupOnThisComputer, resetRuntimeInDistroOnThisComputer } from './targets/windowsReset'; -import { UninstallPrompt, UninstallResult, uninstallRuntimeInDistroOnThisComputer } from './targets/windowsUninstall'; +import { UninstallPrompt, UninstallResult, uninstallRuntimeInDistroOnThisComputer, uninstallDistroProgramOnThisComputer } from './targets/windowsUninstall'; import { finishResumeInstall as clearResumeInstall, fixWindowsOnThisComputer, resumeInstallPlanOnThisComputer, ResumeInstallPlan } from './targets/windowsHost'; -import { LaunchTarget, LaunchTargetId, TargetStatus, UpdateCheck } from './targets/types'; +import { HomeStartResult, LaunchTarget, LaunchTargetId, TargetStatus, UpdateCheck } from './targets/types'; export type { TargetStatus }; +export function homeLogFolder(platform: string, home: string, env: NodeJS.ProcessEnv): string { + if (platform === 'win32') { + return `\\\\wsl.localhost\\${DISTRO_NAME}${runtimeDataDir('linux', DISTRO_HOME, {}).replace(/\//g, '\\')}\\logs`; + } + return runtimeJoin(runtimeDataDir(platform, home, env), 'logs'); +} + export interface LaunchControllerOptions { explicit?: string | null; env?: NodeJS.ProcessEnv; @@ -29,14 +41,15 @@ export interface LaunchController { readonly target: LaunchTarget; onStatusChange(listener: (status: TargetStatus) => void): void; onLog(listener: (line: string) => void): void; + onActionSuccess(listener: () => void): void; getStatus(): Promise; - start(): Promise; + start(): Promise; stop(): Promise; restart(): Promise; install(onProgress: (message: string) => void): Promise; update(onProgress: (message: string) => void): Promise; /** On Windows `confirmRemoval` asks the second question before the Linux environment is saved and removed. */ - uninstall(confirmRemoval?: (prompt: UninstallPrompt) => Promise): Promise; + uninstall(confirmRemoval?: (prompt: UninstallPrompt) => Promise, deleteData?: boolean): Promise; /** `choice.backup` must be true or false. Anything else resets nothing. */ resetRuntime(choice?: { backup?: unknown }): Promise; describeResetBackup(): Promise; @@ -50,8 +63,8 @@ export interface LaunchController { getPreflight(): Promise; getDiagnostics(): Promise; saveSupportBundle(): Promise; - describeFailure(): Promise; - fixFailure(): Promise<'ready' | 'still-blocked'>; + describeFailure(error?: unknown): Promise; + fixFailure(error?: unknown): Promise<'ready' | 'still-blocked'>; resumeInstallPlan(): Promise; finishResumeInstall(ok: boolean): void; setOpenAtLogin(enabled: boolean): void; @@ -122,13 +135,17 @@ export interface LaunchInfo { openUrl: string; status: TargetStatus; platformNote: string | null; + error: string | null; /** Shown in the info panel. Windows only: its Browser is not available yet. */ browserNote: string | null; /** Windows: Uninstall saves the whole Linux environment as one file, then removes it. */ uninstallRemovesLinux: boolean; + /** `home --browser` opens one tab. The launcher does not open a second one after Start. */ + runtimeOpensBrowser: boolean; preflight: PreflightReport; openAtLogin: boolean; canRollback: boolean; + openBrowserAfterInstall: boolean; } function messageOf(err: unknown): string { @@ -147,10 +164,12 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L env: options.env, }); const active = createLaunchTarget(id); + let shuttingDown = false; let lastError = ''; const statusListeners: Array<(status: TargetStatus) => void> = []; const logListeners: Array<(line: string) => void> = []; const runtimeLogs: string[] = []; + const actionListeners: Array<() => void> = []; const emitStatus = (status: TargetStatus) => { for (const listener of statusListeners) listener(status); @@ -163,9 +182,16 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L setRuntimeLogSink(emitLog); if (retired) emitLog(retired); - async function runRuntime(action: () => Promise): Promise { + function clearLastError(): void { + lastError = ''; + for (const listener of actionListeners) listener(); + } + + async function runRuntime(action: () => Promise, clearsError = false): Promise { try { - return await action(); + const result = await action(); + if (clearsError) clearLastError(); + return result; } catch (err) { lastError = messageOf(err); emitLog(lastError); @@ -174,9 +200,16 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L } } - function runRuntimeSync(action: () => T): T { + // Also refuse new update/rollback commands and UI success events after Quit. + function runWhileActive(action: () => Promise): Promise { + return shuttingDown ? Promise.resolve() : runRuntime(action, true); + } + + function runRuntimeSync(action: () => T, clearsError = false): T { try { - return action(); + const result = action(); + if (clearsError) clearLastError(); + return result; } catch (err) { lastError = messageOf(err); emitLog(lastError); @@ -186,7 +219,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L } async function currentStatus(): Promise { - return runRuntime(() => active.getStatus()); + return active.getStatus(); } async function diagnosticsText(): Promise { @@ -216,7 +249,7 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L const probed = await probeGatewayHealth({ timeoutMs: 800 }); const health = isHealthOk(probed) ? 'OK' : 'not answering'; return buildDiagnostics({ - launcherVersion: '1.4.0', + launcherVersion: require('../../package.json').version, runtimeVersion, target: active.id, channel, @@ -241,40 +274,45 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L onLog(listener) { logListeners.push(listener); }, + onActionSuccess(listener) { + actionListeners.push(listener); + }, getStatus: () => currentStatus(), - start: () => runRuntime(() => active.start()), - stop: () => runRuntime(() => active.stop()), - restart: () => runRuntime(() => active.restart()), - install: (onProgress) => runRuntime(() => active.install(onProgress)), - update: (onProgress) => runRuntime(() => active.update(onProgress)), - // On Windows, Uninstall removes the ElastOS Linux environment, after the Reset checks and a second question. - uninstall: (confirmRemoval) => runRuntime(() => (process.platform === 'win32' - ? uninstallRuntimeInDistroOnThisComputer(() => active.stopForRemoval(), confirmRemoval ?? (async () => false)) - : active.uninstall())), + start: () => shuttingDown ? Promise.resolve('stopped') : runRuntime(() => active.start(), true), + stop: () => runRuntime(() => active.stop(), true), + restart: () => runWhileActive(() => active.restart()), + install: (onProgress) => runRuntime(() => active.install(onProgress), true), + update: (onProgress) => runWhileActive(() => active.update(onProgress)), + // Windows preserves the Home in place, or exports and removes its environment after a second question. + uninstall: (confirmRemoval, deleteData = false) => runRuntime(() => (process.platform === 'win32' + ? (deleteData ? uninstallRuntimeInDistroOnThisComputer(() => active.stopForRemoval(), confirmRemoval ?? (async () => false)) : uninstallDistroProgramOnThisComputer(() => active.stopForRemoval())) + : active.uninstall(deleteData)), true), // On Windows the ElastOS data is inside the ElastOS Linux environment, so Reset works there. resetRuntime: (choice) => runRuntime(() => (process.platform === 'win32' ? resetRuntimeInDistroOnThisComputer(() => active.stopForRemoval(), choice ?? {}) - : resetRuntimeOnThisComputer(() => active.stopForRemoval(), choice ?? {}))), + : resetRuntimeOnThisComputer(() => active.stopForRemoval(), choice ?? {})), true), describeResetBackup: () => (process.platform === 'win32' ? describeDistroBackupOnThisComputer() : describeRuntimeBackupOnThisComputer()), - rollback: (onProgress) => runRuntime(() => rollbackRuntimeUpdate(onProgress)), - getVersion: () => runRuntimeSync(() => active.getVersion()), - checkForUpdate: () => runRuntime(() => active.checkForUpdate()), + rollback: (onProgress) => runWhileActive(() => active.rollback(onProgress)), + getVersion: () => active.getVersion(), + checkForUpdate: () => active.checkForUpdate(), openInBrowser: () => { - runRuntimeSync(() => active.openInBrowser()); + runRuntimeSync(() => active.openInBrowser(), true); }, getLogs: (lines) => { const count = lines ?? runtimeLogs.length; return Promise.resolve(runtimeLogs.slice(-count).join('\n')); }, - isInstalled: () => runRuntime(() => active.isInstalled()), + isInstalled: () => active.isInstalled(), async getLaunchInfo() { let status: TargetStatus = 'stopped'; + let error = lastError; try { status = await currentStatus(); - } catch { + } catch (err) { status = 'error'; + error = messageOf(err); } const preflight = await collectPreflight(); const platform = preflight.checks.find((check) => check.id === 'platform' && check.level === 'block'); @@ -283,22 +321,25 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L displayName: active.descriptor.displayName, openUrl: active.descriptor.openUrl, status, + error: status === 'error' ? error : null, platformNote: platform?.message ?? null, browserNote: browserNote(process.platform), + runtimeOpensBrowser: homeLaunchForPlatform(process.platform).args[0] === 'home', uninstallRemovesLinux: process.platform === 'win32', preflight, openAtLogin: readOpenAtLogin(), canRollback: Boolean(runtimeHeadStore().get()), + openBrowserAfterInstall: homeLaunchForPlatform(process.platform).openBrowserAfterInstall, }; }, getPreflight: () => collectPreflight(), - async describeFailure() { + async describeFailure(error?: unknown) { const preflight = await collectPreflight(); - return failureScreen(collectFailureFacts(lastError, preflight.checks)); + return failureScreen(collectFailureFacts(error === undefined ? lastError : messageOf(error), preflight.checks)); }, - async fixFailure() { + async fixFailure(error?: unknown) { const preflight = await collectPreflight(); - const facts = collectFailureFacts(lastError, preflight.checks); + const facts = collectFailureFacts(error === undefined ? lastError : messageOf(error), preflight.checks); if (failureScreen(facts).kind === 'windows') { return windowsFixResult( () => fixWindowsOnThisComputer(), @@ -323,6 +364,9 @@ export function createLaunchController(options: LaunchControllerOptions = {}): L return readOpenAtLogin(); }, async shutdown() { + // Shutdown ends this controller's lifetime, even if stopping fails. + shuttingDown = true; + active.beginShutdown(); try { await active.stop(); } catch (err) { diff --git a/src/main/launcherWindow.ts b/src/main/launcherWindow.ts new file mode 100644 index 0000000..fa40404 --- /dev/null +++ b/src/main/launcherWindow.ts @@ -0,0 +1,16 @@ +/** Clamp renderer content and the native frame to the current display's work area. */ +export function contentWindowBounds( + contentHeight: number, + bounds: { x: number; y: number; width: number; height: number }, + content: { width: number; height: number }, + workArea: { x: number; y: number; width: number; height: number }, +): { x: number; y: number; width: number; height: number } { + const width = Math.min(bounds.width, workArea.width); + const height = Math.min(Math.ceil(contentHeight) + bounds.height - content.height, workArea.height); + return { + x: Math.max(workArea.x, Math.min(bounds.x, workArea.x + workArea.width - width)), + y: Math.max(workArea.y, Math.min(bounds.y, workArea.y + workArea.height - height)), + width, + height, + }; +} diff --git a/src/main/openHome.ts b/src/main/openHome.ts new file mode 100644 index 0000000..bcf00e2 --- /dev/null +++ b/src/main/openHome.ts @@ -0,0 +1,27 @@ +import type { HomeStartResult } from './targets/types'; + +/** Coalesce Finder, second-instance and menu opens while Home is starting. */ +export function createOpenHome(launch: { + getStatus(): Promise; + start(): Promise; + openInBrowser(): void; +}, install: () => void, startOpensBrowser = false): () => Promise { + let opening: Promise | null = null; + return () => { + if (opening) return opening; + opening = (async () => { + const status = await launch.getStatus(); + if (status === 'not-installed') { install(); return; } + if (status === 'other-home') throw new Error('Another Home is running on this computer.'); + if (status !== 'running') { + const result = await launch.start(); + if (result === 'stopped') return; + if (startOpensBrowser && (result === 'started' || result === 'already-running')) return; + // A reused controller waits for health in start(), but does not run + // home --browser again. This click must open the ready Home itself. + } + launch.openInBrowser(); + })().finally(() => { opening = null; }); + return opening; + }; +} diff --git a/src/main/targets/descriptors.ts b/src/main/targets/descriptors.ts index 80f4a57..a663efa 100644 --- a/src/main/targets/descriptors.ts +++ b/src/main/targets/descriptors.ts @@ -3,8 +3,8 @@ import { LaunchTargetDescriptor } from './types'; /** * Facts taken from elastos-runtime. - * `elastos gateway` is the supervised entry: `elastos home --browser` - * also opens the system browser itself. + * Desktop platforms start `home --browser` from homeLaunchForPlatform. + * `startArgs` describes the legacy gateway command. * Health is GET /healthz → "OK" on the gateway. * darwin/x64 is included because a runtime build for Intel Mac is planned. * Native win32 is absent: Windows uses a WSL2 distro. diff --git a/src/main/targets/distroResetHelper.ts b/src/main/targets/distroResetHelper.ts index de7485d..b81baf2 100644 --- a/src/main/targets/distroResetHelper.ts +++ b/src/main/targets/distroResetHelper.ts @@ -546,7 +546,22 @@ def do_remove(): except OSError: raise Refused('changed') try: - if now == 'dir': + if now == 'dir' and req.get('keepData') is True: + dfd = os.open(os.path.basename(data), DIR_FLAGS, dir_fd=pfd) + try: + if place(dfd) != place(pfd) or entries_at(dfd) != req['entries']: + raise Refused('changed') + if req['recordSha256'] is not None and record_at(dfd).get('sha256') != req['recordSha256']: + raise Refused('changed') + if crossings(dfd, place(dfd), '', []): + raise Refused('mount') + removed = [] + for p in (binary, stage): + if unlink_file(p): + removed.append(p) + finally: + os.close(dfd) + elif now == 'dir': removed = remove_with_data(pfd, data, binary, stage) else: removed = [] @@ -556,7 +571,7 @@ def do_remove(): removed.append(p) except (OSError, Refused): raise partial('program', removed, True, None, []) - left = sweep(pfd, parent, ('elastos',)) if pfd is not None else [] + left = sweep(pfd, parent, ('elastos',)) if pfd is not None and req.get('keepData') is not True else [] finally: if pfd is not None: os.close(pfd) diff --git a/src/main/targets/hostToolEntry.ts b/src/main/targets/hostToolEntry.ts index 1ddaa9d..744aec4 100644 --- a/src/main/targets/hostToolEntry.ts +++ b/src/main/targets/hostToolEntry.ts @@ -284,9 +284,24 @@ function isAbort(err: unknown): boolean { return !!err && typeof err === 'object' && 'name' in err && (err as { name?: string }).name === 'AbortError'; } +export async function installerFetch(input: string | URL | Request, init?: RequestInit): Promise { + const metadataPath = process.env.ELASTOS_LAUNCHER_METADATA_PATH; + if (metadataPath) { + if (fs.statSync(metadataPath).size > 2 * 1024 * 1024) throw new Error('Installer metadata exceeds its limit.'); + const bytes = fs.readFileSync(metadataPath); + if (createHash('sha256').update(bytes).digest('hex') !== process.env.ELASTOS_LAUNCHER_METADATA_SHA256) { + throw new Error('Installer metadata changed after verification.'); + } + const metadata = JSON.parse(bytes.toString('utf8')) as Record; + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + if (Object.prototype.hasOwnProperty.call(metadata, url)) return new Response(metadata[url]); + } + return fetch(input, init); +} + function defaultDeps(): CurlDeps { return { - fetch, + fetch: installerFetch, writeFile: (file, data) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, data); diff --git a/src/main/targets/hostTools.ts b/src/main/targets/hostTools.ts index 8efe06f..f296d19 100644 --- a/src/main/targets/hostTools.ts +++ b/src/main/targets/hostTools.ts @@ -80,8 +80,9 @@ export function detectLinuxLibc( // That directory is not on this computer. } } - if (names.some((name) => name.startsWith('ld-musl-'))) return 'musl'; + // The glibc loader is the system libc when a leftover musl loader is also present. if (names.some((name) => name.startsWith('ld-linux') || name === 'libc.so.6')) return 'glibc'; + if (names.some((name) => name.startsWith('ld-musl-'))) return 'musl'; return 'unknown'; } diff --git a/src/main/targets/openAtLogin.ts b/src/main/targets/openAtLogin.ts index 527b2fa..720c014 100644 --- a/src/main/targets/openAtLogin.ts +++ b/src/main/targets/openAtLogin.ts @@ -10,13 +10,33 @@ export function linuxAutostartPath(homeDir: string): string { return path.join(homeDir, '.config', 'autostart', 'elastos.desktop'); } +/** A mounted AppImage reports a temporary exec path. `$APPIMAGE` is the file the user keeps. */ +export function linuxAutostartExecPath(env: NodeJS.ProcessEnv, execPath: string): string { + const image = typeof env.APPIMAGE === 'string' ? env.APPIMAGE.trim() : ''; + return image || execPath; +} + +/** Quote a desktop Exec value when it contains a reserved character. */ +export function desktopExecValue(execPath: string): string { + if (/[\r\n\0]/.test(execPath)) { + throw new Error('The sign-in program path is not valid.'); + } + if (!/[\s"'\\><~|&;$*?#()`]/.test(execPath)) return execPath; + const escaped = execPath + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') + .replace(/`/g, '\\`') + .replace(/\$/g, '\\$'); + return `"${escaped}"`; +} + export function linuxAutostartFile(execPath: string): string { return [ '[Desktop Entry]', 'Type=Application', 'Name=ElastOS', - 'Comment=Open your computer', - `Exec=${execPath}`, + 'Comment=Start ElastOS when you log in to this computer', + `Exec=${desktopExecValue(execPath)} --login`, 'X-GNOME-Autostart-enabled=true', '', ].join('\n'); @@ -63,7 +83,7 @@ export function syncLinuxAutostart( export function applyOpenAtLogin(enabled: boolean, homeDir: string = os.homedir()): void { writeOpenAtLogin(enabled, homeDir); if (process.platform === 'linux') { - syncLinuxAutostart(enabled, homeDir, process.execPath, { + syncLinuxAutostart(enabled, homeDir, linuxAutostartExecPath(process.env, process.execPath), { mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }), writeFile: (file, contents) => fs.writeFileSync(file, contents), remove: (file) => fs.rmSync(file, { force: true }), @@ -71,9 +91,24 @@ export function applyOpenAtLogin(enabled: boolean, homeDir: string = os.homedir( return; } try { - const electron = require('electron') as { app?: { setLoginItemSettings: (settings: { openAtLogin: boolean }) => void } }; - electron.app?.setLoginItemSettings?.({ openAtLogin: enabled }); + const electron = require('electron') as { app?: { setLoginItemSettings: (settings: { openAtLogin: boolean; openAsHidden?: boolean; args?: string[] }) => void } }; + electron.app?.setLoginItemSettings?.({ + openAtLogin: enabled, + ...(process.platform === 'darwin' ? { openAsHidden: true } : { args: ['--login'] }), + }); } catch { // Unit tests are not inside Electron. } } + +/** Login launches keep the app in the tray while Home starts. */ +export function isLoginLaunch(platform: string, argv: readonly string[], settings: { wasOpenedAtLogin?: boolean }): boolean { + return platform === 'darwin' ? settings.wasOpenedAtLogin === true : argv.includes('--login'); +} + +export async function startHomeAtLogin(enabled: boolean, launch: { + getStatus(): Promise; + start(): Promise; +}): Promise { + if (enabled && await launch.getStatus() === 'stopped') await launch.start(); +} diff --git a/src/main/targets/preflight.ts b/src/main/targets/preflight.ts index aa7dc48..063f0b6 100644 --- a/src/main/targets/preflight.ts +++ b/src/main/targets/preflight.ts @@ -3,7 +3,7 @@ import * as fs from 'fs'; import * as net from 'net'; import * as os from 'os'; import * as path from 'path'; -import { GATEWAY_ADDR, GATEWAY_PORT, LOOPBACK_ADDRESSES } from './gatewayAddress'; +import { GATEWAY_PORT, LOOPBACK_ADDRESSES } from './gatewayAddress'; import { isHealthOk, localhostIsLoopback, probeGatewayHealth, resolveLocalhost } from './runtimeGateway'; import { BIP39_ENGLISH } from './bip39English'; import { launcherOwnedDirectories } from './runtimePaths'; @@ -44,7 +44,7 @@ export interface PreflightInput { } export const LOCALHOST_MESSAGE = - 'On this computer, the name localhost does not point to this computer. ElastOS needs it to. Ask the person who looks after this computer to fix the hosts file, then try again.'; + 'ElastOS could not connect to Home on this computer.'; export function evaluatePreflight(input: PreflightInput): PreflightReport { const checks: PreflightCheck[] = []; @@ -55,23 +55,23 @@ export function evaluatePreflight(input: PreflightInput): PreflightReport { wslInstalled: input.wslInstalled ?? false, distroReady: input.distroReady ?? false, }); - const message = `${prompt.title}. ${prompt.body}`; + const message = prompt.body; const ready = prompt.kind === 'ready'; checks.push({ id: 'windows', level: ready ? 'pass' : 'block', - message, + message: ready ? '' : message, }); checks.push({ id: 'platform', level: ready ? 'pass' : 'block', - message: ready ? 'This computer can run ElastOS.' : message, + message: ready ? '' : message, }); } else { const platform = runtimeInstallBlock(input.platform, input.arch); checks.push(platform ? { id: 'platform', level: 'block', message: platform } - : { id: 'platform', level: 'pass', message: 'This computer can run ElastOS.' }); + : { id: 'platform', level: 'pass', message: '' }); } if (input.freeBytes == null) { @@ -79,29 +79,29 @@ export function evaluatePreflight(input: PreflightInput): PreflightReport { } else if (input.freeBytes < DISK_FLOOR_BYTES) { checks.push({ id: 'disk', level: 'block', message: 'This computer needs about 2 GB free to install ElastOS.' }); } else { - checks.push({ id: 'disk', level: 'pass', message: 'There is enough free disk space.' }); + checks.push({ id: 'disk', level: 'pass', message: '' }); } if (input.healthOk) { - checks.push({ id: 'port', level: 'pass', message: 'Your computer is already running.' }); + checks.push({ id: 'port', level: 'pass', message: '' }); } else if (input.portBusy) { - checks.push({ id: 'port', level: 'block', message: `Port ${GATEWAY_PORT} is being used by another program. Quit that program and try again.` }); + checks.push({ id: 'port', level: 'block', message: 'Another app is preventing Home from starting.' }); } else { - checks.push({ id: 'port', level: 'pass', message: `Port ${GATEWAY_PORT} is free.` }); + checks.push({ id: 'port', level: 'pass', message: '' }); } if (input.localhostAddresses !== undefined) { checks.push(input.localhostAddresses && localhostIsLoopback(input.localhostAddresses) - ? { id: 'localhost', level: 'pass', message: `${GATEWAY_ADDR} points to this computer.` } + ? { id: 'localhost', level: 'pass', message: '' } : { id: 'localhost', level: 'block', message: LOCALHOST_MESSAGE }); } if (input.networkChecked === false) { - checks.push({ id: 'network', level: 'pass', message: 'The network is checked when Install starts.' }); + checks.push({ id: 'network', level: 'pass', message: '' }); } else { checks.push(input.offline - ? { id: 'network', level: 'block', message: 'You appear to be offline. Connect to the internet and try again.' } - : { id: 'network', level: 'pass', message: 'The network is reachable.' }); + ? { id: 'network', level: 'block', message: 'ElastOS could not connect to the internet.' } + : { id: 'network', level: 'pass', message: '' }); } if (input.platform === 'linux' && input.libc === 'musl') { diff --git a/src/main/targets/releaseHead.ts b/src/main/targets/releaseHead.ts index a2f70f5..7e62103 100644 --- a/src/main/targets/releaseHead.ts +++ b/src/main/targets/releaseHead.ts @@ -1,6 +1,5 @@ import { createHash, createPublicKey, timingSafeEqual, verify } from 'crypto'; -const DOMAIN = 'elastos.release.head.v1'; const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; export class ReleaseHeadError extends Error { @@ -31,9 +30,23 @@ export function verifyReleaseHead(text: string, expectedDid: string): { channel: string; version: string; latestReleaseCid: string; + releaseSha256: string; signerDid: string; headCid: string; } { + const body = verifyEnvelope(text, expectedDid, 'elastos.release.head.v1'); + return { + channel: typeof body.channel === 'string' ? body.channel : '', + version: typeof body.version === 'string' ? body.version : '', + latestReleaseCid: typeof body.latest_release_cid === 'string' ? body.latest_release_cid : '', + releaseSha256: typeof body.release_sha256 === 'string' ? body.release_sha256 : '', + signerDid: expectedDid, + headCid: releaseHeadCid(text), + }; +} + +function verifyEnvelope(text: string, expectedDid: string, domain: string): Record { + if (Buffer.byteLength(text, 'utf8') > 256 * 1024) throw new ReleaseHeadError('Signed release metadata exceeds its limit.'); let envelope: unknown; try { envelope = parseJsonUnique(text); @@ -61,19 +74,28 @@ export function verifyReleaseHead(text: string, expectedDid: string): { throw new ReleaseHeadError('Signature must contain 64 hex-encoded bytes.'); } const digest = createHash('sha256') - .update(Buffer.concat([Buffer.from(`${DOMAIN}\0`), Buffer.from(canonicalJson(body), 'utf8')])) + .update(Buffer.concat([Buffer.from(`${domain}\0`), Buffer.from(canonicalJson(body), 'utf8')])) .digest(); const ok = verify(null, digest, didKeyToPublic(signer), Buffer.from(signature, 'hex')); if (!ok) { throw new ReleaseHeadError('Release head signature does not match the pinned maintainer DID.'); } - return { - channel: typeof body.channel === 'string' ? body.channel : '', - version: typeof body.version === 'string' ? body.version : '', - latestReleaseCid: typeof body.latest_release_cid === 'string' ? body.latest_release_cid : '', - signerDid: signer, - headCid: releaseHeadCid(text), - }; + return body; +} + +/** The head binds the exact manifest bytes. The signed manifest binds install.sh. */ +export function verifiedInstallerSha256(text: string, head: ReturnType): string { + if (!sha256Equals(sha256Hex(text), head.releaseSha256)) { + throw new ReleaseHeadError('Release manifest SHA-256 does not match the signed head.'); + } + const body = verifyEnvelope(text, head.signerDid, 'elastos.release.v1'); + if (body.schema !== 'elastos.release/v1' || body.channel !== head.channel || body.version !== head.version) { + throw new ReleaseHeadError('Release manifest identity does not match the signed head.'); + } + if (typeof body.installer_sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(body.installer_sha256)) { + throw new ReleaseHeadError('The signed release has no valid install.sh SHA-256. Install stopped.'); + } + return body.installer_sha256; } /** diff --git a/src/main/targets/runtimeGateway.ts b/src/main/targets/runtimeGateway.ts index f5db902..5560fa0 100644 --- a/src/main/targets/runtimeGateway.ts +++ b/src/main/targets/runtimeGateway.ts @@ -1,8 +1,10 @@ -import { execFile, execFileSync, spawn } from 'child_process'; +import type { HomeStartResult } from './types'; +import { ChildProcess, execFile, execFileSync, spawn, spawnSync } from 'child_process'; import * as dns from 'dns'; import * as fs from 'fs'; import * as http from 'http'; import * as os from 'os'; +import * as path from 'path'; import { GATEWAY_ADDR, GATEWAY_HOST, @@ -14,12 +16,37 @@ import { LOOPBACK_ADDRESSES, } from './gatewayAddress'; import { runtimeChildEnv } from './releaseHead'; -import { runtimeDataDir, runtimeHostLockPath } from './runtimePaths'; +import { runtimeBinaryPath, runtimeDataDir, runtimeHostLockPath } from './runtimePaths'; export { HEALTH_URL, HOME_URL, LEGACY_GATEWAY_ADDR, LOOPBACK_ADDRESSES }; /** Supervised command from the launcher contract. */ export const GATEWAY_ARGS: readonly string[] = ['gateway', '--addr', GATEWAY_ADDR]; +export const HOME_TERMINAL_LINE = 'Keep this terminal open. Press Ctrl+C to stop Home.'; + +export interface HomeLaunch { + args: readonly string[]; + quitWhenLastWindowCloses: boolean; + updateRestartsHome: boolean; + rollbackRestartsHome: boolean; + hideTerminalKeepLine: boolean; + openBrowserAfterInstall: boolean; + offerKeepHomeOnQuit: boolean; +} + +/** Each desktop platform starts the signed Home controller. */ +export function homeLaunchForPlatform(platform: string): HomeLaunch { + const browserHome = platform === 'darwin' || platform === 'linux' || platform === 'win32'; + return { + args: browserHome ? ['home', '--browser'] : GATEWAY_ARGS, + quitWhenLastWindowCloses: platform !== 'darwin' && platform !== 'linux', + updateRestartsHome: browserHome, + rollbackRestartsHome: browserHome, + hideTerminalKeepLine: platform === 'linux' || platform === 'win32', + openBrowserAfterInstall: platform !== 'linux' && platform !== 'win32', + offerKeepHomeOnQuit: platform === 'linux', + }; +} export const ALREADY_OWNS_TEXT = 'another ElastOS host already owns'; export const EXIT_BINARY_REPLACED = 75; export const STOP_GRACE_MS = 15_000; @@ -27,6 +54,9 @@ export const FOREIGN_LISTENER_MESSAGE = `Another program is answering at ${GATEWAY_ADDR}, so Home was not opened. Quit that program and click Try again.`; export const LEGACY_STILL_RUNNING_MESSAGE = 'An older ElastOS is still running and could not be stopped. Quit it, then click Start.'; +export const HOME_UNCONFIRMED_MESSAGE = + 'Home could not be confirmed; stop it with Ctrl+C in its terminal'; +export const OTHER_HOME_MESSAGE = 'another ElastOS Home is running'; /** A gateway this window did not start. Callers match the type, not the sentence. */ export class ForeignGatewayError extends Error { @@ -52,10 +82,14 @@ export interface HealthResult { export interface GatewayProcess { readonly pid: number; + /** True only for the ChildProcess this launcher created. Stop keeps that handle. */ + readonly spawnedHere?: boolean; onOutput(listener: (chunk: string) => void): void; onExit(listener: (code: number | null) => void): void; signal(signal: NodeJS.Signals): void; hasExited(): boolean | Promise; + /** Drop a stop helper. A process that has none does not implement this. */ + dispose?(): void; } /** @@ -92,7 +126,8 @@ export function signalProcessGroup( /** * `current` is a gateway on `localhost:8090`, the address this launcher * starts. `legacy` is one an earlier launcher started on `127.0.0.1:8090`. - * A legacy gateway is only stopped and started again. Home never opens on it. + * Linux does not signal a legacy gateway. Windows may stop its distro + * gateway and start `localhost:8090`. Home never opens on the legacy one. */ export type InstalledGatewayKind = 'current' | 'legacy'; @@ -109,6 +144,8 @@ export function lockAddressWants(kind: InstalledGatewayKind): readonly string[] export function installedGatewayKind(input: { lockText: string | null; command: string | null; + /** macOS caller already matched the kernel executable to an installed path. */ + verifiedExecutable?: string; pidAlive: (pid: number) => boolean; ownsSocket: (pid: number, wants: readonly string[]) => boolean; }): InstalledGatewayKind | null { @@ -128,7 +165,12 @@ export function installedGatewayKind(input: { if (!input.ownsSocket(parsed.pid, lockAddressWants(kind))) return null; if (!input.command) return null; const command = input.command.trim(); - if (!/(^|[\\/\s])elastos(\.exe)?(\s|$)/i.test(command) || !/\bgateway\b/.test(command)) return null; + if (input.verifiedExecutable) { + // argv[0] may be an alias or symlink; authority comes from the kernel path. + return /\bgateway\b|\bhome\s+--browser(?:\s|$)/.test(command) ? kind : null; + } + if (!/(^|[\\/\s])elastos(\.exe)?(\s|$)/i.test(command) + || !(/\bgateway\b/.test(command) || /\bhome\s+--browser(?:\s|$)/.test(command))) return null; return kind; } @@ -137,14 +179,34 @@ export function foreignListenerIsElastos(input: Parameters GatewayProcess; fetchHealth: () => Promise; sleep: (ms: number) => Promise; now: () => number; openUrl: (url: string) => void; log: (line: string) => void; + /** Linux drops the runtime's terminal sentence. Exit 75 still reads the raw stream. */ + hideTerminalKeepLine?: boolean; confirmForeign?: () => Promise; /** * True when the running gateway is one an earlier launcher started on @@ -152,6 +214,11 @@ export interface GatewaySupervisorDeps { * starts it again on `localhost:8090`. */ foreignIsLegacy?: () => Promise; + /** + * Linux sets this. A bare gateway on 127.0.0.1:8090 is another Home. + * Start reports that and does not signal it. Windows leaves this unset. + */ + reportLegacyHome?: () => Promise; /** * An OK body counts only when this returns true: the started gateway owns * every `localhost` address that answered. Without it, OK is enough. @@ -163,6 +230,11 @@ export interface GatewaySupervisorDeps { * Returning null leaves a listener that is not that gateway running. */ adoptInstalled?: () => GatewayProcess | null | Promise; + /** + * Linux Stop signals the process this window spawned. Mac Stop adopts the + * proved controller instead, including after that process has exited. + */ + keepSpawnedHandle?: boolean; graceMs?: number; healthTimeoutMs?: number; pollMs?: number; @@ -170,13 +242,13 @@ export interface GatewaySupervisorDeps { } export interface GatewaySupervisor { - start(): Promise<'started' | 'already-running'>; + start(): Promise; /** * Stop the gateway this window started. `adopt` is only for Reset and * Uninstall, after the person confirmed. Quit, Stop, and Restart omit it. */ stop(options?: { adopt?: boolean }): Promise; - /** SIGKILL the process group this supervisor is stopping. Used when quit runs out of time. */ + /** SIGKILL the process this supervisor is stopping. Used when quit runs out of time. */ forceKill(): void; openHome(): void; getLogs(lines?: number): string; @@ -247,6 +319,468 @@ export function procListenersFor(tcp: string, tcp6: string, fdLinks: readonly st return procNetListeners(tcp, tcp6, port).map((entry) => ({ address: entry.address, owned: owned.has(entry.inode) })); } +export interface ProcProcess { + pid: number; + ppid: number; + fdLinks: readonly string[]; +} + +/** `comm` may contain spaces. The kernel ends the name at the last `)`. */ +export function procStatParent(stat: string): { pid: number; ppid: number } | null { + const end = stat.lastIndexOf(')'); + const space = stat.indexOf(' '); + if (end < 0 || space <= 0 || space > end) return null; + const pid = Number(stat.slice(0, space)); + const ppid = Number(stat.slice(end + 2).split(' ')[1]); + if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(ppid) || ppid < 0) return null; + return { pid, ppid }; +} + +/** + * Sockets on `port` held by `root` itself. + * Home names the gateway pid in the controller status. A descendant is not that pid. + */ +export function listenersFromProcSnapshot( + tcp: string, + tcp6: string, + root: number, + rows: readonly ProcProcess[], + port = GATEWAY_PORT, +): PortListener[] { + const own = rows.find((row) => row.pid === root); + return procListenersFor(tcp, tcp6, own ? own.fdLinks : [], port); +} + +/** Field 22 of `/proc//stat`, the starttime tick. `comm` may contain spaces. */ +export function linuxStatStartTicks(stat: string): string | null { + const end = stat.lastIndexOf(')'); + if (end < 0) return null; + const ticks = stat.slice(end + 1).trim().split(/\s+/)[19]; + if (!ticks || !/^[0-9]+$/.test(ticks)) return null; + return ticks; +} + +/** + * The same birth string Runtime 2.0.0 stores in `controller_start` + * (`update_controller/child.rs` `process_identity`). + */ +export function linuxProcessIdentity(stat: string | null, bootId: string | null): string | null { + if (!stat) return null; + const ticks = linuxStatStartTicks(stat); + if (!ticks) return null; + const boot = (bootId ?? '').trim(); + if (!boot) return `linux:${ticks}`; + if (/[\r\n]/.test(boot)) return null; + return `linux:${boot}:${ticks}`; +} + +export interface LinuxHomeStatus { + controllerPid: number; + controllerStart: string; + hostPid: number; + generation: string; +} + +export interface HostLockRecord { + pid: number; + role: string; + addr: string; + generation: string; +} + +function positivePid(value: unknown): number | null { + return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null; +} + +/** `update-controller/status.json` from Runtime 2.0.0. A missing field is not a Home. */ +export function parseLinuxHomeStatus(text: string | null): LinuxHomeStatus | null { + if (!text || text.length > 16 * 1024) return null; + let parsed: { + controller_pid?: unknown; + controller_start?: unknown; + host_pid?: unknown; + generation?: unknown; + }; + try { + parsed = JSON.parse(text) as typeof parsed; + } catch { + return null; + } + const controllerPid = positivePid(parsed.controller_pid); + const hostPid = positivePid(parsed.host_pid); + const controllerStart = typeof parsed.controller_start === 'string' ? parsed.controller_start : ''; + const generation = typeof parsed.generation === 'string' ? parsed.generation : ''; + if (!controllerPid || !hostPid || !controllerStart || !generation) return null; + if (controllerStart.length > 200 || generation.length > 128) return null; + if (/[\r\n]/.test(controllerStart) || /[\r\n]/.test(generation)) return null; + return { controllerPid, controllerStart, hostPid, generation }; +} + +/** `host-process.lock`. `generation` may be empty for a gateway this controller did not start. */ +export function parseHostLockRecord(text: string | null): HostLockRecord | null { + if (!text || text.length > 16 * 1024) return null; + let parsed: { pid?: unknown; role?: unknown; addr?: unknown; generation?: unknown }; + try { + parsed = JSON.parse(text) as typeof parsed; + } catch { + return null; + } + const pid = positivePid(parsed.pid); + if (!pid || typeof parsed.role !== 'string' || typeof parsed.addr !== 'string') return null; + const generation = typeof parsed.generation === 'string' ? parsed.generation : ''; + if (generation.length > 128 || /[\r\n]/.test(generation)) return null; + return { pid, role: parsed.role, addr: parsed.addr, generation }; +} + +/** The controller Runtime 2.0.0 recorded, proved against the host lock and `/proc`. */ +export interface ProvedLinuxHome { + controllerPid: number; + controllerStart: string; + hostPid: number; + hostStart: string; + generation: string; +} + +/** + * Fail closed. The host lock must name this gateway on `localhost:8090`. + * The status file must name that same pid, generation, and controller birth. + * The host birth must be the same value on both sides of the descriptor read. + */ +export function proveLinuxHome(input: { + statusText: string | null; + lockText: string | null; + bootId: string | null; + controllerStat: string | null; + hostStatBefore: string | null; + hostFdLinks: readonly string[] | null; + hostStatAfter: string | null; + tcp: string; + tcp6: string; + answered?: readonly string[]; +}): ProvedLinuxHome | null { + const status = parseLinuxHomeStatus(input.statusText); + const lock = parseHostLockRecord(input.lockText); + if (!status || !lock) return null; + if (lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR) return null; + if (lock.pid !== status.hostPid || lock.generation !== status.generation) return null; + const controllerNow = linuxProcessIdentity(input.controllerStat, input.bootId); + const controllerParsed = input.controllerStat ? procStatParent(input.controllerStat) : null; + if (controllerNow !== status.controllerStart || !controllerParsed || controllerParsed.pid !== status.controllerPid) { + return null; + } + const before = linuxProcessIdentity(input.hostStatBefore, input.bootId); + const after = linuxProcessIdentity(input.hostStatAfter, input.bootId); + const hostParsed = input.hostStatBefore ? procStatParent(input.hostStatBefore) : null; + if (!before || before !== after || !hostParsed || hostParsed.pid !== status.hostPid) return null; + if (!input.hostFdLinks) return null; + const listeners = procListenersFor(input.tcp, input.tcp6, input.hostFdLinks); + if (listenerOwnership(listeners, LOOPBACK_ADDRESSES, input.answered ?? []) !== 'owned') return null; + return { + controllerPid: status.controllerPid, + controllerStart: status.controllerStart, + hostPid: status.hostPid, + hostStart: before, + generation: status.generation, + }; +} + +/** The pid to signal, or null when its birth no longer matches the proof. */ +export function linuxControllerSignalPid(proved: ProvedLinuxHome, identityNow: string | null): number | null { + if (!identityNow || identityNow !== proved.controllerStart) return null; + return proved.controllerPid; +} + +/** One fresh read of the controller record, the lock, and `/proc`. */ +export interface ControllerObservation { + statusText: string | null; + lockText: string | null; + bootId: string | null; + controllerStat: string | null; + exePath: string | null; + allowedExes: readonly string[]; +} + +export type ControllerRecord = Pick; + +export type ControllerProcView = Pick; + +/** A pidfd for one process. `send` cannot target a later occupant of the same pid number. */ +export interface Pidfd { + send(signal: NodeJS.Signals): void; + close(): void; +} + +/** + * The update controller pid, or null. The start time, the exe, and the host + * lock generation must all match this read. A host pid is not a target. + */ +export function confirmedControllerPid(observed: ControllerObservation): number | null { + const status = parseLinuxHomeStatus(observed.statusText); + const lock = parseHostLockRecord(observed.lockText); + if (!status || !lock) return null; + if (lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR) return null; + if (!status.generation || lock.generation !== status.generation) return null; + const identity = linuxProcessIdentity(observed.controllerStat, observed.bootId); + const parsed = observed.controllerStat ? procStatParent(observed.controllerStat) : null; + if (identity !== status.controllerStart || !parsed || parsed.pid !== status.controllerPid) return null; + const exe = observed.exePath; + if (!exe || exe.endsWith(' (deleted)')) return null; + if (!observed.allowedExes.includes(exe)) return null; + return status.controllerPid; +} + +export function signalRecordedController( + signal: NodeJS.Signals, + io: { + readRecord: () => ControllerRecord; + readProc: (pid: number) => ControllerProcView; + openPidfd: (pid: number) => Pidfd; + }, + held: { pidfd: Pidfd | null }, +): void { + if (!held.pidfd) { + const record = io.readRecord(); + const status = parseLinuxHomeStatus(record.statusText); + const lock = parseHostLockRecord(record.lockText); + if (!status || !lock || lock.role !== 'gateway' || lock.addr !== GATEWAY_ADDR + || !status.generation || lock.generation !== status.generation) { + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + let pidfd: Pidfd; + try { + pidfd = io.openPidfd(status.controllerPid); + } catch { + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + let proc: ControllerProcView; + try { + proc = io.readProc(status.controllerPid); + } catch { + pidfd.close(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + const confirmed = confirmedControllerPid({ + statusText: record.statusText, + lockText: record.lockText, + bootId: record.bootId, + allowedExes: record.allowedExes, + controllerStat: proc.controllerStat, + exePath: proc.exePath, + }); + if (confirmed !== status.controllerPid) { + pidfd.close(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + held.pidfd = pidfd; + } + try { + held.pidfd.send(signal); + } catch (err) { + if (signalErrorCode(err) === 'ESRCH') return; + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } +} + +export function controllerGateway( + readRecord: () => ControllerRecord, + readProc: (pid: number) => ControllerProcView, + openPidfd: (pid: number) => Pidfd, +): GatewayProcess { + const held: { pidfd: Pidfd | null } = { pidfd: null }; + function observation(): ControllerObservation | null { + const record = readRecord(); + const status = parseLinuxHomeStatus(record.statusText); + if (!status) return null; + const proc = readProc(status.controllerPid); + return { + statusText: record.statusText, + lockText: record.lockText, + bootId: record.bootId, + allowedExes: record.allowedExes, + controllerStat: proc.controllerStat, + exePath: proc.exePath, + }; + } + return { + pid: -1, + onOutput() {}, + onExit() {}, + hasExited() { + let gone = false; + try { + const observed = observation(); + gone = observed === null || confirmedControllerPid(observed) === null; + } catch { + return false; + } + if (gone && held.pidfd) { + held.pidfd.close(); + held.pidfd = null; + } + return gone; + }, + signal(signal) { + signalRecordedController(signal, { readRecord, readProc, openPidfd }, held); + }, + dispose() { + const pidfd = held.pidfd; + held.pidfd = null; + if (!pidfd) return; + try { + pidfd.close(); + } catch { + // Stop still reports its own error. close() has already dropped the helper. + } + }, + }; +} + +function throwSignalCode(code: string, message: string): never { + throw Object.assign(new Error(message), { code }); +} + +function linuxPidfdHelperPath(): string { + return path.join(__dirname, '../../native/linux-pidfd') + .replace(`${path.sep}app.asar${path.sep}`, `${path.sep}app.asar.unpacked${path.sep}`); +} + +function makeFifo(file: string): void { + const result = spawnSync('mkfifo', ['-m', '600', file], { timeout: 1000 }); + if (result.error || result.status !== 0) throwSignalCode('ENOSYS', 'pidfd is unavailable'); +} + +function waitBriefly(): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); +} + +function readPidfdLine(fd: number, deadline: number): string { + const buf = Buffer.alloc(64); + let text = ''; + while (!text.includes('\n')) { + if (text.length > 64) throwSignalCode('EIO', 'pidfd reply is too long'); + if (Date.now() >= deadline) throwSignalCode('ETIMEDOUT', 'pidfd helper timed out'); + try { + const n = fs.readSync(fd, buf, 0, buf.length, null); + if (n === 0) { + waitBriefly(); + continue; + } + text += buf.toString('utf8', 0, n); + } catch (err) { + const code = signalErrorCode(err); + if (code === 'EAGAIN' || code === 'EWOULDBLOCK') { + waitBriefly(); + continue; + } + throw err; + } + } + return text.slice(0, text.indexOf('\n')); +} + +function openFifoWrite(file: string, deadline: number): number { + const flags = fs.constants.O_WRONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW; + for (;;) { + if (Date.now() >= deadline) throwSignalCode('ETIMEDOUT', 'pidfd helper timed out'); + try { + return fs.openSync(file, flags); + } catch (err) { + if (signalErrorCode(err) === 'ENXIO') { + waitBriefly(); + continue; + } + throw err; + } + } +} + +export function openLinuxPidfd(pid: number, options?: { helper?: string }): Pidfd { + if (!Number.isInteger(pid) || pid <= 0) throwSignalCode('EINVAL', 'bad pid'); + const helper = options?.helper ?? linuxPidfdHelperPath(); + if (!options?.helper && process.platform !== 'linux') throwSignalCode('ENOSYS', 'pidfd is unavailable'); + if (!fs.existsSync(helper)) throwSignalCode('ENOENT', 'pidfd helper is missing'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'elastos-pidfd-')); + fs.chmodSync(dir, 0o700); + const replyPath = path.join(dir, 'reply'); + const cmdPath = path.join(dir, 'cmd'); + let child: ChildProcess | null = null; + let replyFd: number | null = null; + let cmdFd: number | null = null; + let settled = false; + const cleanup = (): void => { + if (settled) return; + settled = true; + if (cmdFd === null) { + try { + cmdFd = fs.openSync(cmdPath, fs.constants.O_WRONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW); + } catch (err) { + const code = signalErrorCode(err); + if (code !== 'ENXIO' && code !== 'ENOENT') throw err; + } + } + const command = cmdFd; + const reply = replyFd; + cmdFd = null; + replyFd = null; + let closeError: unknown = null; + if (command !== null) { + try { fs.closeSync(command); } catch (err) { closeError = err; } + } + if (reply !== null) { + try { fs.closeSync(reply); } catch (err) { if (!closeError) closeError = err; } + } + child?.unref(); + fs.rmSync(dir, { recursive: true, force: true }); + if (closeError) throw closeError; + }; + try { + makeFifo(replyPath); + makeFifo(cmdPath); + child = spawn(helper, [String(pid), replyPath, cmdPath], { stdio: 'ignore' }); + // Node crashes when the spawn error event has no listener. + child.on('error', () => {}); + if (!child.pid) throwSignalCode('ENOENT', 'pidfd helper is missing'); + const replyFlags = fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW; + replyFd = fs.openSync(replyPath, replyFlags); + const ready = readPidfdLine(replyFd, Date.now() + 2000); + if (ready.startsWith('errno ')) throwSignalCode(ready.slice('errno '.length), ready); + if (ready !== 'ready') throwSignalCode('EIO', 'pidfd helper did not become ready'); + cmdFd = openFifoWrite(cmdPath, Date.now() + 2000); + const reply = replyFd; + const cmd = cmdFd; + let closed = false; + return { + send(signal: NodeJS.Signals): void { + if (closed) throwSignalCode('EBADF', 'pidfd is closed'); + if (signal !== 'SIGTERM' && signal !== 'SIGKILL') throwSignalCode('EINVAL', 'unsupported signal'); + fs.writeSync(cmd, `${signal}\n`); + const line = readPidfdLine(reply, Date.now() + 2000); + if (line === 'sent') return; + if (line.startsWith('errno ')) throwSignalCode(line.slice('errno '.length), line); + throwSignalCode('EIO', 'pidfd helper reply was not a signal result'); + }, + close(): void { + if (closed) return; + closed = true; + try { + fs.writeSync(cmd, 'close\n'); + } catch (err) { + const code = signalErrorCode(err); + if (code !== 'EPIPE' && code !== 'EBADF') { + cleanup(); + throw err; + } + } + cleanup(); + }, + }; + } catch (err) { + cleanup(); + throw err; + } +} + /** * `lsof -nP -iTCP: -sTCP:LISTEN -Fpn` output. `n` names look like * `127.0.0.1:8090`, `[::1]:8090`, or `*:8090`. A socket of another account is @@ -308,14 +842,22 @@ export function isHealthOk(result: HealthResult | null): boolean { } /** Drop lines that can carry attach_secret. The coords files stay on disk, out of the log. */ -export function scrubRuntimeLog(chunk: string): string { +export function scrubRuntimeLog(chunk: string, platform: string = process.platform): string { if (/attach_secret|runtime-coords\.json|gateway-runtime-coords|home-runtime-coords/i.test(chunk)) { return '[elastos] omitted a line that can contain a local secret\n'; } - return chunk; + if (platform !== 'win32' || !chunk.includes(HOME_TERMINAL_LINE)) return chunk; + return chunk.split(HOME_TERMINAL_LINE).join(''); +} + +export function launcherLogText(text: string, hideTerminalKeepLine: boolean, platform: string = process.platform): string { + const clean = scrubRuntimeLog(text, platform); + if (!hideTerminalKeepLine) return clean; + return clean.split('\n').filter((line) => !line.includes(HOME_TERMINAL_LINE)).join('\n'); } export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySupervisor { + const lifetime = deps.lifetime ?? homeGatewayLifetime; const graceMs = deps.graceMs ?? STOP_GRACE_MS; const healthTimeoutMs = deps.healthTimeoutMs ?? 60_000; const pollMs = deps.pollMs ?? 250; @@ -326,19 +868,56 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup let intentionalStop = false; let restarts = 0; let current: 'running' | 'stopped' | 'starting' | 'stopping' | 'error' = 'stopped'; + const homeController = deps.args?.[0] === 'home'; const note = (line: string) => { - const clean = scrubRuntimeLog(line).replace(/\s+$/g, ''); + const clean = launcherLogText(line, deps.hideTerminalKeepLine === true, deps.platform).replace(/\s+$/g, ''); if (!clean) return; logs.push(clean); deps.log(clean); }; - async function launchOnce(): Promise<'ready' | 'replaced' | 'already'> { - intentionalStop = false; + function recordExit(proc: GatewayProcess, code: number | null): void { + if (owned !== proc) return; + owned = null; foreign = false; - const proc = deps.spawn(deps.binary, GATEWAY_ARGS); + if (intentionalStop || current !== 'running') return; + current = code === 0 ? 'stopped' : 'error'; + note(code === 0 ? 'ElastOS stopped.' : code === null + ? 'ElastOS stopped unexpectedly. Click Start to try again.' + : `ElastOS stopped (exit ${code}). Click Start to try again.`); + } + + function replaceOwned(proc: GatewayProcess | null): void { + if (owned && owned !== proc) owned.dispose?.(); owned = proc; + } + + function ownAdopted(proc: GatewayProcess | null): void { + replaceOwned(proc); + proc?.onExit((code) => recordExit(proc, code)); + } + + async function findInstalled(): Promise { + const attempts = deps.adoptForControls ? 3 : 1; + for (let attempt = 0; attempt < attempts; attempt++) { + const proc = await (deps.adoptInstalled?.() ?? null); + if (proc) return proc; + if (attempt + 1 < attempts) { + note('Checking Home ownership again.'); + await deps.sleep(pollMs); + } + } + return null; + } + + async function launchOnce(): Promise<'ready' | 'replaced' | 'already' | 'stopped'> { + // No await between this refusal and spawn, including replacement retries. + if (lifetime.shuttingDown) return 'stopped'; + intentionalStop = false; + foreign = false; + const proc = deps.spawn(deps.binary, deps.args ?? GATEWAY_ARGS); + replaceOwned(proc); let output = ''; let exited = false; let exitCode: number | null = null; @@ -349,6 +928,11 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup proc.onExit((code) => { exited = true; exitCode = code; + if (owned !== proc) return; + if (homeController) { + recordExit(proc, code); + return; + } if (current !== 'running' || intentionalStop) return; if (binaryReplacement(output, code)) { owned = null; @@ -369,7 +953,9 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup owned = null; current = 'error'; note('ElastOS stopped (exit 75) without a replaced binary. It was not started again.'); + return; } + recordExit(proc, code); }); const deadline = deps.now() + healthTimeoutMs; @@ -397,7 +983,7 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup function classifyExit(code: number | null, output: string): 'replaced' | 'already' { owned = null; - if (binaryReplacement(output, code)) { + if (!homeController && binaryReplacement(output, code)) { restarts += 1; if (restarts > maxRestarts) { throw new Error('ElastOS kept restarting after an update. Click Start to try again.'); @@ -406,12 +992,14 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup return 'replaced'; } if (code === EXIT_BINARY_REPLACED) { + current = 'error'; throw new Error('ElastOS stopped (exit 75) without a replaced binary. It was not started again.'); } if (output.includes(ALREADY_OWNS_TEXT)) { return 'already'; } - const tail = scrubRuntimeLog(output).trim().split('\n').slice(-3).join(' '); + const tail = launcherLogText(output, deps.hideTerminalKeepLine === true, deps.platform).trim().split('\n').slice(-3).join(' '); + current = 'error'; throw new Error( tail ? `ElastOS stopped before it was ready. ${tail}` @@ -441,42 +1029,71 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup async function stopProcess(proc: GatewayProcess): Promise { intentionalStop = true; current = 'stopping'; - proc.signal('SIGTERM'); - if (await confirmedStopped(proc, graceMs)) { - owned = null; - current = 'stopped'; - return; - } - proc.signal('SIGKILL'); - if (await confirmedStopped(proc, graceMs)) { - owned = null; - current = 'stopped'; - return; + try { + proc.signal('SIGTERM'); + if (await confirmedStopped(proc, graceMs)) { + proc.dispose?.(); + owned = null; + current = 'stopped'; + return; + } + proc.signal('SIGKILL'); + if (await confirmedStopped(proc, graceMs)) { + proc.dispose?.(); + owned = null; + current = 'stopped'; + return; + } + current = 'error'; + throw new Error('ElastOS is still running.'); + } catch (err) { + proc.dispose?.(); + throw err; } - current = 'error'; - throw new Error('ElastOS is still running.'); } const supervisor: GatewaySupervisor = { async start() { - if (owned && current === 'running') return 'started'; + if (lifetime.shuttingDown) return 'stopped'; + if (owned && current === 'running') { + const exited = await owned.hasExited(); + if (lifetime.shuttingDown) return 'stopped'; + if (!exited) { + const deadline = deps.now() + healthTimeoutMs; + while (deps.now() < deadline) { + const health = await deps.fetchHealth(); + if (lifetime.shuttingDown) return 'stopped'; + if (isHealthOk(health)) return 'running'; + await deps.sleep(pollMs); + } + throw new Error('ElastOS did not become ready in time. Try Open Home again.'); + } + owned = null; + } current = 'starting'; let legacyStopped = false; for (;;) { const result = await launchOnce(); + if (result === 'stopped') return 'stopped'; + if (lifetime.shuttingDown) return 'stopped'; if (result === 'replaced') continue; if (result === 'already') { + if (deps.reportLegacyHome && await deps.reportLegacyHome()) { + current = 'error'; + throw new Error(OTHER_HOME_MESSAGE); + } if (!legacyStopped && deps.foreignIsLegacy && await deps.foreignIsLegacy()) { // An earlier launcher started it on 127.0.0.1. Passkeys need // localhost, so stop it once and start it again here. legacyStopped = true; note('An older ElastOS is running on 127.0.0.1:8090. Starting it again on localhost:8090.'); - const adopted = await (deps.adoptInstalled?.() ?? null); + const adopted = await findInstalled(); if (!adopted) { current = 'error'; throw new Error(LEGACY_STILL_RUNNING_MESSAGE); } - owned = adopted; + if (lifetime.shuttingDown) { adopted.dispose?.(); return 'stopped'; } + ownAdopted(adopted); try { await stopProcess(adopted); } catch { @@ -489,15 +1106,18 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup const health = await deps.fetchHealth(); if (!isHealthOk(health)) { current = 'error'; - throw new Error('ElastOS is already running, but it is not answering yet. Wait a moment and click Open my computer.'); + throw new Error('ElastOS is already running, but it is not answering yet. Wait a moment and click Open Home.'); } const confirmed = deps.confirmForeign ? await deps.confirmForeign() : false; if (!confirmed) { current = 'error'; throw new Error('Something is answering on port 8090, but it is not the ElastOS gateway. Home was not opened.'); } + const adopted = deps.adoptForControls ? await findInstalled() : null; + if (lifetime.shuttingDown) { adopted?.dispose?.(); return 'stopped'; } foreign = true; - owned = null; + intentionalStop = false; + ownAdopted(adopted); current = 'running'; deps.openUrl(HOME_URL); return 'already-running'; @@ -507,29 +1127,47 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup } }, async stop(options?: { adopt?: boolean }) { + const currentProc = owned; + const keepSpawned = deps.keepSpawnedHandle === true + && currentProc !== null && currentProc.spawnedHere === true + && !(await currentProc.hasExited()); + if (!keepSpawned && deps.adoptForControls && isHealthOk(await deps.fetchHealth())) { + const installed = await findInstalled(); + if (!installed) throw new ForeignGatewayError(); + ownAdopted(installed); + } if (!owned) { const health = await deps.fetchHealth(); if (isHealthOk(health)) { - const adopted = options?.adopt - ? await (deps.adoptInstalled?.() ?? null) + const adopted = (options?.adopt || deps.adoptForControls) + ? await findInstalled() : null; if (!adopted) throw new ForeignGatewayError(); - owned = adopted; + ownAdopted(adopted); } else { foreign = false; current = 'stopped'; return; } } - await stopProcess(owned); + if (owned) { + try { + await stopProcess(owned); + } catch (err) { + current = 'error'; + throw err; + } + } }, forceKill() { if (!owned) return; + const failed = current === 'error'; try { owned.signal('SIGKILL'); } catch { // Quit still closes. The error from stop() is logged by the caller. } + if (failed) owned.dispose?.(); }, openHome() { deps.openUrl(HOME_URL); @@ -546,7 +1184,11 @@ export function createGatewaySupervisor(deps: GatewaySupervisorDeps): GatewaySup return supervisor; } -export function spawnGatewayProcess(binary: string, args: readonly string[]): GatewayProcess { +export function spawnGatewayProcess( + binary: string, + args: readonly string[], + platform: string = process.platform, +): GatewayProcess { const child = spawn(binary, [...args], { detached: true, stdio: ['ignore', 'pipe', 'pipe'], @@ -576,8 +1218,19 @@ export function spawnGatewayProcess(binary: string, args: readonly string[]): Ga hasExited() { return exited; }, + spawnedHere: true, signal(signal) { - signalProcessGroup(child.pid ?? -1, signal); + if (platform === 'darwin') { + signalProcessGroup(child.pid ?? -1, signal); + return; + } + try { + child.kill(signal); + } catch (err) { + if (signalErrorCode(err) === 'ESRCH') return; + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } }, }; } @@ -592,9 +1245,24 @@ export function emitRuntimeLog(line: string): void { logSink(line); } +function withDeadline(work: Promise, timeoutMs: number): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = setTimeout(() => { + reject(Object.assign(new Error('localhost lookup timed out'), { code: 'ETIMEDOUT' })); + }, timeoutMs); + }); + return Promise.race([work, timeout]).finally(() => { + if (timer !== undefined) clearTimeout(timer); + }); +} + /** The addresses `localhost` resolves to on this computer, in resolver order. */ -export async function resolveLocalhost(): Promise { - const found = await dns.promises.lookup(GATEWAY_HOST, { all: true, verbatim: true }); +export async function resolveLocalhost(timeoutMs = 2000): Promise { + const found = await withDeadline( + dns.promises.lookup(GATEWAY_HOST, { all: true, verbatim: true }), + timeoutMs, + ); return [...new Set(found.map((entry) => entry.address))]; } @@ -671,7 +1339,9 @@ export async function probeGatewayHealth(options: { const timeoutMs = options.timeoutMs ?? 2000; let addresses: string[]; try { - addresses = await (options.lookup ?? resolveLocalhost)(); + addresses = options.lookup + ? await withDeadline(options.lookup(), timeoutMs) + : await resolveLocalhost(timeoutMs); } catch { return null; } @@ -681,38 +1351,131 @@ export async function probeGatewayHealth(options: { return combineHealth(results); } -/** LISTEN sockets on the gateway port, marked by whether `pid` holds each. Null when they cannot be read. */ -export async function localListeners(pid: number, platform: string = process.platform): Promise { - if (!Number.isInteger(pid) || pid <= 0) return null; - if (platform === 'linux') { - let tcp: string; +const PROC_STAT_MAX = 4096; +const PROC_TEXT_MAX = 8 * 1024 * 1024; +const HOME_RECORD_MAX = 16 * 1024; + +function fdLinks(pid: number): string[] | null { + const links: string[] = []; + let names: string[]; + try { + names = fs.readdirSync(`/proc/${pid}/fd`); + } catch { + return null; + } + for (const name of names) { try { - tcp = fs.readFileSync('/proc/net/tcp', 'utf8'); + links.push(fs.readlinkSync(`/proc/${pid}/fd/${name}`)); } catch { - return null; + // A descriptor can disappear between readdir and readlink. } - let tcp6 = ''; - try { - tcp6 = fs.readFileSync('/proc/net/tcp6', 'utf8'); - } catch { - // No IPv6 on this kernel. Nothing can listen on ::1. - tcp6 = ''; + } + return links; +} + +/** `undefined` when the path is absent. `null` when the bytes are not a bounded file. */ +function readProcOptional(file: string, max: number): string | null | undefined { + let fd: number | null = null; + try { + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + const chunks: Buffer[] = []; + let total = 0; + const buf = Buffer.alloc(64 * 1024); + for (;;) { + const n = fs.readSync(fd, buf, 0, buf.length, null); + if (n <= 0) break; + total += n; + if (total > max) return null; + chunks.push(Buffer.from(buf.subarray(0, n))); } - const links: string[] = []; - try { - const dir = `/proc/${pid}/fd`; - for (const name of fs.readdirSync(dir)) { - try { - links.push(fs.readlinkSync(`${dir}/${name}`)); - } catch { - // A descriptor can disappear between readdir and readlink. - } - } - } catch { - return null; + return Buffer.concat(chunks).toString('utf8'); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err ? String((err as { code?: string }).code) : ''; + if (code === 'ENOENT') return undefined; + return null; + } finally { + if (fd !== null) { + try { fs.closeSync(fd); } catch { /* already closed */ } + } + } +} + +function readRegularText(file: string, max: number): string | null { + let fd: number | null = null; + try { + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + const info = fs.fstatSync(fd); + if (!info.isFile() || info.size > max) return null; + const buf = Buffer.alloc(info.size); + let offset = 0; + while (offset < info.size) { + const n = fs.readSync(fd, buf, offset, info.size - offset, offset); + if (n <= 0) return null; + offset += n; + } + return buf.toString('utf8'); + } catch { + return null; + } finally { + if (fd !== null) { + try { fs.closeSync(fd); } catch { /* already closed */ } } - return procListenersFor(tcp, tcp6, links); } +} + +/** Listeners held by `pid` itself. Null when `/proc` cannot prove that. */ +function linuxProcessListeners(pid: number): PortListener[] | null { + const tcp = readProcOptional('/proc/net/tcp', PROC_TEXT_MAX); + if (!tcp) return null; + const tcp6 = readProcOptional('/proc/net/tcp6', PROC_TEXT_MAX); + if (tcp6 === null) return null; + const links = fdLinks(pid); + if (!links) return null; + return procListenersFor(tcp, tcp6 ?? '', links); +} + +function readProvedLinuxHome(answered: readonly string[] = []): ProvedLinuxHome | null { + const data = runtimeDataDir('linux', os.homedir(), process.env); + const statusText = readRegularText(`${data}/update-controller/status.json`, HOME_RECORD_MAX); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + const bootId = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + if (bootId === null) return null; + const status = parseLinuxHomeStatus(statusText); + if (!status) return null; + const hostStatBefore = readProcOptional(`/proc/${status.hostPid}/stat`, PROC_STAT_MAX); + const hostFdLinks = fdLinks(status.hostPid); + const hostStatAfter = readProcOptional(`/proc/${status.hostPid}/stat`, PROC_STAT_MAX); + const controllerStat = readProcOptional(`/proc/${status.controllerPid}/stat`, PROC_STAT_MAX); + const tcp = readProcOptional('/proc/net/tcp', PROC_TEXT_MAX); + const tcp6 = readProcOptional('/proc/net/tcp6', PROC_TEXT_MAX); + if (!controllerStat || !hostStatBefore || !hostStatAfter || !tcp || tcp6 === null) return null; + return proveLinuxHome({ + statusText, + lockText, + bootId: bootId ?? null, + controllerStat, + hostStatBefore, + hostFdLinks, + hostStatAfter, + tcp, + tcp6: tcp6 ?? '', + answered, + }); +} + +function linuxControllerOwnsListeners(controllerPid: number, health: HealthResult): boolean { + const proved = readProvedLinuxHome(health.addresses ?? []); + if (!proved || proved.controllerPid !== controllerPid) return false; + const bootId = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + const stat = readProcOptional(`/proc/${proved.controllerPid}/stat`, PROC_STAT_MAX); + if (bootId === null || !stat) return false; + return linuxControllerSignalPid(proved, linuxProcessIdentity(stat, bootId ?? null)) === proved.controllerPid; +} + +/** LISTEN sockets on the gateway port, marked by whether `pid` itself holds each. Null when they cannot be read. */ +export async function localListeners(pid: number, platform: string = process.platform): Promise { + if (!Number.isInteger(pid) || pid <= 0) return null; + if (platform === 'linux') return linuxProcessListeners(pid); if (platform === 'darwin') { return new Promise((resolve) => { execFile('lsof', ['-nP', `-iTCP:${GATEWAY_PORT}`, '-sTCP:LISTEN', '-Fpn'], { @@ -744,30 +1507,64 @@ export async function pidOwnsGatewayPort( return listenerOwnership(listeners, wants, answered) === 'owned'; } -export function createDefaultGatewaySupervisor(binary: string): GatewaySupervisor { +/** Linux and Mac Stop and Quit take the installed Home. Windows does not. */ +export function platformAdoptsInstalledHome(platform: string): boolean { + return platform === 'darwin' || platform === 'linux'; +} + +export function createDefaultGatewaySupervisor(binary: string, platform: string = process.platform, lifetime: GatewayLifetime = homeGatewayLifetime): GatewaySupervisor { + const launch = homeLaunchForPlatform(platform); return createGatewaySupervisor({ + lifetime, binary, - spawn: spawnGatewayProcess, + platform, + args: launch.args, + hideTerminalKeepLine: launch.hideTerminalKeepLine, + adoptForControls: platformAdoptsInstalledHome(platform), + keepSpawnedHandle: platform === 'linux', + healthTimeoutMs: platform === 'darwin' ? 150000 : 60000, + spawn: (command, commandArgs) => spawnGatewayProcess(command, commandArgs, platform), fetchHealth: () => probeGatewayHealth(), sleep: (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }), now: () => Date.now(), openUrl: openRuntimeHome, log: (line) => logSink(line), confirmForeign: confirmInstalledGateway, - foreignIsLegacy: async () => (await installedGatewayOnThisComputer()) === 'legacy', - listenerOwned: (pid, health) => pidOwnsGatewayPort(pid, LOOPBACK_ADDRESSES, health.addresses ?? []), - adoptInstalled: adoptInstalledGatewayProcess, + foreignIsLegacy: platform === 'darwin' + ? async () => (await installedGatewayOnThisComputer(platform)) === 'legacy' + : undefined, + reportLegacyHome: platform === 'linux' + ? async () => (await installedGatewayOnThisComputer(platform)) === 'legacy' + : undefined, + listenerOwned: (pid, health) => platform === 'darwin' + ? installedGatewayOnThisComputer(platform).then((kind) => kind === 'current') + : platform === 'linux' + ? linuxControllerOwnsListeners(pid, health) + : pidOwnsGatewayPort(pid, LOOPBACK_ADDRESSES, health.addresses ?? []), + adoptInstalled: () => adoptInstalledGatewayProcess(platform), }); } -function readHostLock(): { text: string | null; pid: number } { - const lockPath = runtimeHostLockPath(runtimeDataDir(process.platform, os.homedir(), process.env)); - let text: string | null = null; +/** Read a regular control file through one fd; size changes cannot exceed the cap. */ +function readControlFile(file: string, maximum = 16 * 1024): string | null { + let fd: number | undefined; try { - text = fs.readFileSync(lockPath, 'utf8'); + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW); + const stat = fs.fstatSync(fd); + if (!stat.isFile() || stat.size > maximum) return null; + const bytes = Buffer.alloc(maximum + 1); + const count = fs.readSync(fd, bytes, 0, bytes.length, 0); + return count > maximum ? null : bytes.toString('utf8', 0, count); } catch { - text = null; + return null; + } finally { + if (fd !== undefined) fs.closeSync(fd); } +} + +function readHostLock(platform: string, homeDir: string): { text: string | null; pid: number } { + const lockPath = runtimeHostLockPath(runtimeDataDir(platform, homeDir, process.env)); + const text = readControlFile(lockPath); let pid = 0; try { const parsed = JSON.parse(text ?? '') as { pid?: unknown }; @@ -778,11 +1575,63 @@ function readHostLock(): { text: string | null; pid: number } { return { text, pid }; } -async function hostLockGatewayKind(text: string | null, pid: number): Promise { - const listeners = await localListeners(pid); - return installedGatewayKind({ +type MacProcessIdentity = { executable: string; start: string }; + +function psField(pid: number, field: string): string { + return execFileSync('ps', ['-p', String(pid), '-ww', '-o', `${field}=`], { + encoding: 'utf8', timeout: 1000, maxBuffer: 16 * 1024, env: { ...process.env, LC_ALL: 'C' }, + }).trim(); +} + +function macProcessIdentity(pid: number): MacProcessIdentity | null { + if (!Number.isInteger(pid) || pid <= 0) return null; + try { + const helper = path.join(__dirname, '../../native/mac-process-info') + .replace(`${path.sep}app.asar${path.sep}`, `${path.sep}app.asar.unpacked${path.sep}`); + const report = execFileSync(helper, [String(pid)], { + encoding: 'utf8', timeout: 1000, maxBuffer: 16 * 1024, + }); + const newline = report.indexOf('\n'); + const start = report.slice(0, newline); + const executable = report.slice(newline + 1); + if (!/^\d+\.\d{6}$/.test(start) || !path.isAbsolute(executable) || executable.includes('\0')) return null; + return { executable, start }; + } catch { + return null; + } +} + +function sameMacProcess(expected: MacProcessIdentity, actual: MacProcessIdentity | null): boolean { + return actual !== null && actual.start === expected.start && actual.executable === expected.executable; +} + +function installedMacExecutable(homeDir: string, executable: string): boolean { + const candidates = [runtimeBinaryPath(homeDir)]; + try { + const data = runtimeDataDir('darwin', homeDir, process.env); + const sources = JSON.parse(readControlFile(path.join(data, 'sources.json'), 256 * 1024) ?? '{}'); + const selected = sources.sources?.find((source: { name?: unknown }) => source.name === sources.default_source); + if (typeof selected?.install_path === 'string' && path.isAbsolute(selected.install_path)) { + candidates.push(selected.install_path); + } + } catch { + // The default installed binary remains usable without a sources record. + } + return candidates.some((candidate) => { + try { return fs.realpathSync(candidate) === executable; } catch { return false; } + }); +} + +async function hostLockGatewayKind( + text: string | null, pid: number, platform: string, homeDir: string, +): Promise { + const identity = platform === 'darwin' ? macProcessIdentity(pid) : null; + if (platform === 'darwin' && (!identity || !installedMacExecutable(homeDir, identity.executable))) return null; + const listeners = await localListeners(pid, platform); + const kind = installedGatewayKind({ lockText: text, - command: processCommand(pid), + command: processCommand(pid, platform), + verifiedExecutable: identity?.executable, pidAlive: (id) => { try { process.kill(id, 0); @@ -793,13 +1642,17 @@ async function hostLockGatewayKind(text: string | null, pid: number): Promise Boolean(listeners && listenerOwnership(listeners, wants) === 'owned'), }); + if (identity && !sameMacProcess(identity, macProcessIdentity(pid))) return null; + return kind; } /** The installed gateway's kind on Linux and macOS, from the host lock. Null when it is not proved. */ -export async function installedGatewayOnThisComputer(): Promise { - if (process.platform === 'win32') return null; - const { text, pid } = readHostLock(); - return hostLockGatewayKind(text, pid); +export async function installedGatewayOnThisComputer( + platform: string = process.platform, homeDir: string = os.homedir(), +): Promise { + if (platform === 'win32') return null; + const { text, pid } = readHostLock(platform, homeDir); + return hostLockGatewayKind(text, pid, platform, homeDir); } export function confirmInstalledGateway(): Promise { @@ -831,30 +1684,181 @@ export function localPidHasExited( } /** - * The installed gateway from the host lock, so Stop can signal a process this - * window did not spawn. A `127.0.0.1:8090` gateway from an earlier launcher is - * adopted too, so Start, Reset, and Uninstall can stop it. + * Stop can signal one process this window did not spawn: the update controller + * named by status.json. A `127.0.0.1:8090` gateway is not that process. */ -export async function adoptInstalledGatewayProcess(): Promise { - if (process.platform === 'win32') return null; - const { text, pid } = readHostLock(); - if (pid <= 0 || !(await hostLockGatewayKind(text, pid))) return null; +function signalErrorCode(err: unknown): string { + return err && typeof err === 'object' && 'code' in err ? String((err as { code?: string }).code) : ''; +} + +function resolvedFile(file: string): string | null { + try { + const real = fs.realpathSync(file); + return real ? real : null; + } catch { + return null; + } +} + +function controllerExeFromProc(pid: number): string | null { + let link: string; + try { + link = fs.readlinkSync(`/proc/${pid}/exe`); + } catch { + return null; + } + if (!link || link.endsWith(' (deleted)')) return null; + return resolvedFile(link); +} + +/** The installed binary, and the controller copy Runtime stores under the data dir. */ +function allowedControllerExes(homeDir: string, dataDir: string): string[] { + const files = [ + runtimeBinaryPath(homeDir), + `${dataDir}/update-controller/runtime`, + ]; + const allowed: string[] = []; + for (const file of files) { + const real = resolvedFile(file); + if (real && !allowed.includes(real)) allowed.push(real); + } + return allowed; +} + +function observeControllerRecord(homeDir: string): ControllerRecord { + const data = runtimeDataDir('linux', homeDir, process.env); + const statusText = readRegularText(`${data}/update-controller/status.json`, HOME_RECORD_MAX); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + const boot = readProcOptional('/proc/sys/kernel/random/boot_id', 128); + return { + statusText, + lockText, + bootId: boot ?? null, + allowedExes: allowedControllerExes(homeDir, data), + }; +} + +function observeControllerProc(pid: number): ControllerProcView { + if (!Number.isInteger(pid) || pid <= 0) return { controllerStat: null, exePath: null }; + const stat = readProcOptional(`/proc/${pid}/stat`, PROC_STAT_MAX); + return { + controllerStat: stat ?? null, + exePath: controllerExeFromProc(pid), + }; +} + +/** `controller` may be signaled. `other-home` is a legacy gateway and is never signaled. */ +export function linuxControllerAdopt(lockText: string | null): 'controller' | 'other-home' | 'none' { + const lock = parseHostLockRecord(lockText); + if (!lock || lock.role !== 'gateway') return 'none'; + if (lock.addr === LEGACY_GATEWAY_ADDR) return 'other-home'; + if (lock.addr !== GATEWAY_ADDR) return 'none'; + return 'controller'; +} + +/** Linux Home. Signal only the recorded update controller. A legacy gateway is not adopted. */ +async function adoptLinuxGatewayProcess(homeDir: string): Promise { + const data = runtimeDataDir('linux', homeDir, process.env); + const lockText = readRegularText(runtimeHostLockPath(data), HOME_RECORD_MAX); + if (linuxControllerAdopt(lockText) !== 'controller') return null; + return controllerGateway( + () => observeControllerRecord(homeDir), + (pid) => observeControllerProc(pid), + openLinuxPidfd, + ); +} + +export async function adoptInstalledGatewayProcess( + platform: string = process.platform, homeDir: string = os.homedir(), +): Promise { + if (platform === 'win32') return null; + if (platform === 'linux') return adoptLinuxGatewayProcess(homeDir); + const refused = (reason: string): null => { + logSink(`Home ownership check: ${reason}`); + return null; + }; + const { text, pid } = readHostLock(platform, homeDir); + if (pid <= 0) return refused('host-lock'); + const hostIdentity = platform === 'darwin' ? macProcessIdentity(pid) : null; + if (platform === 'darwin' && !hostIdentity) return refused('native-host'); + if (!(await hostLockGatewayKind(text, pid, platform, homeDir))) return refused('host-proof'); + if (platform === 'darwin' && (!hostIdentity || !sameMacProcess(hostIdentity, macProcessIdentity(pid)))) return refused('host-changed'); + let stopPid = pid; + let stopIdentity = hostIdentity; + if (platform === 'darwin') { + const data = runtimeDataDir(platform, homeDir, process.env); + const statusText = readControlFile(path.join(data, 'update-controller', 'status.json')); + try { + // A directly started gateway has no controller status file. + if (statusText !== null) { + const status = JSON.parse(statusText); + const lock = JSON.parse(text ?? '{}'); + const controller = status.controller_pid; + const identity = macProcessIdentity(controller); + if (status.host_pid === pid && typeof lock.generation === 'string' && status.generation === lock.generation + && identity && identity.executable === path.join(data, 'update-controller', 'runtime') + && processCommand(controller, platform)?.startsWith(`${identity.executable} __update-controller `) + && Number(psField(pid, 'ppid')) === controller) { + stopPid = controller; + stopIdentity = identity; + } + // A stale controller record grants no authority over that controller. + // The independently proved host can still be stopped after a crash. + } else if (fs.existsSync(path.join(data, 'update-controller', 'status.json'))) { + return refused('controller-status'); + } + } catch { + return refused('controller-metadata'); + } + } + let timer: ReturnType | undefined; + let notified = false; + const exitListeners: Array<(code: number | null) => void> = []; + function gone(target: number, identity: MacProcessIdentity | null): boolean { + if (localPidHasExited(target)) return true; + const actual = identity ? macProcessIdentity(target) : null; + return Boolean(identity && actual && !sameMacProcess(identity, actual)); + } + function observeExit(): void { + if (gone(stopPid, stopIdentity) && !notified) { + notified = true; + if (timer) clearInterval(timer); + for (const listener of exitListeners) listener(gone(pid, hostIdentity) ? 0 : null); + } + } + function hasExited(): boolean { + observeExit(); + return gone(pid, hostIdentity) && (stopPid === pid || gone(stopPid, stopIdentity)); + } return { pid, onOutput() {}, - onExit() {}, - hasExited() { - return localPidHasExited(pid); + onExit(listener) { + exitListeners.push(listener); + if (!timer && !notified) { + timer = setInterval(observeExit, 1000); + timer.unref(); + } }, + hasExited, signal(signal) { - signalProcessGroup(pid, signal); + // The controller drains its own children. Recheck the signal recipient, + // including its birth time, immediately before TERM or escalation to KILL. + if (platform === 'darwin') { + if (!stopIdentity || !sameMacProcess(stopIdentity, macProcessIdentity(stopPid))) { + throw new Error('ElastOS process identity changed. Refusing to signal a reused PID.'); + } + process.kill(stopPid, signal); + } else { + signalProcessGroup(pid, signal); + } }, }; } -function processCommand(pid: number): string | null { +function processCommand(pid: number, platform: string = process.platform): string | null { if (!Number.isInteger(pid) || pid <= 0) return null; - if (process.platform === 'linux') { + if (platform === 'linux') { try { return fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim(); } catch { @@ -864,7 +1868,7 @@ function processCommand(pid: number): string | null { try { return execFileSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', - timeout: 1000, + timeout: 1000, maxBuffer: 16 * 1024, }).trim(); } catch { return null; diff --git a/src/main/targets/runtimeInstall.ts b/src/main/targets/runtimeInstall.ts index 76e6797..a3c932b 100644 --- a/src/main/targets/runtimeInstall.ts +++ b/src/main/targets/runtimeInstall.ts @@ -2,7 +2,7 @@ import { execFile as execFileCb } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { installerChildEnv, ReleaseHeadError, sha256Equals, sha256Hex, verifyReleaseHead } from './releaseHead'; +import { installerChildEnv, ReleaseHeadError, sha256Equals, sha256Hex, verifyReleaseHead, verifiedInstallerSha256 } from './releaseHead'; import { ActiveRuntimePin, loadActiveRuntimePin } from './runtimePin'; import { runtimeBinaryPath, @@ -68,15 +68,43 @@ export class PinMismatchError extends Error { } } -/** The first field where the pin and the publisher are not the same value. */ -export function pinMismatchField(pin: ActiveRuntimePin, head: ReleaseHead | null): string | null { - if (!pin.publishable || !pin.version || !pin.headCid) { - return pin.version ? 'headCid' : 'version'; +/** Compare numeric SemVer components and prerelease identifiers, never string prefixes. */ +export function versionAtLeast(version: string | null, floor: string | null): boolean { + const parse = (value: string | null) => { + const parsed = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(value ?? ''); + if (parsed?.[4]?.split('.').some((part) => /^0\d+$/.test(part))) return null; + return parsed; + }; + const actual = parse(version?.replace(/^ElastOS Runtime v/, '') ?? null); + const minimum = parse(floor); + if (!actual || !minimum) return false; + for (let i = 1; i <= 3; i++) { + if (BigInt(actual[i]) !== BigInt(minimum[i])) return BigInt(actual[i]) > BigInt(minimum[i]); } + if (!actual[4]) return true; + if (!minimum[4]) return false; + const left = actual[4].split('.'); + const right = minimum[4].split('.'); + for (let i = 0; i < Math.max(left.length, right.length); i++) { + if (left[i] === right[i]) continue; + if (left[i] === undefined) return false; + if (right[i] === undefined) return true; + const numericLeft = /^\d+$/.test(left[i]); + const numericRight = /^\d+$/.test(right[i]); + if (numericLeft && numericRight) return BigInt(left[i]) > BigInt(right[i]); + if (numericLeft !== numericRight) return numericRight; + return left[i] > right[i]; + } + return true; +} + +/** A package pins the trust root and rollback floor, while the publisher selects the head. */ +export function pinMismatchField(pin: ActiveRuntimePin, head: ReleaseHead | null): string | null { + if (!pin.publishable || !versionAtLeast(pin.version, '2.0.0')) return 'version'; if (!head) return 'release-head'; if (head.channel !== pin.channel) return 'channel'; - if (head.version !== pin.version) return 'version'; - if (!head.headCid || head.headCid !== pin.headCid) return 'headCid'; + if (!versionAtLeast(head.version, pin.version)) return 'version'; + if (!head.headCid || !/^Qm[1-9A-HJ-NP-Za-km-z]{44}$/.test(head.headCid)) return 'headCid'; if (head.signerDid !== pin.maintainerDid) return 'signerDid'; return null; } @@ -90,9 +118,9 @@ export type InstallPlan = | { action: 'refused'; field: string }; /** - * ElastOS counts as installed only when the version, the head CID in - * sources.json, and the signed install record (installation/release-head.json, - * checked against the pinned maintainer DID) all match. Version and head CID + * ElastOS counts as installed when its version is at least the floor and + * sources.json matches its signed installation/release-head.json record. + * The record is checked against the pinned maintainer DID. Version and head CID * are read from files this account can edit, so they say which release is * there. The record is the proof that install.sh finished that release. With * no valid record, Install runs the pinned install.sh again, which writes it. @@ -109,8 +137,7 @@ export function planRuntimeInstall(input: { }): InstallPlan { const blocked = runtimeInstallBlock(input.platform, input.arch); if (blocked) return { action: 'blocked', message: blocked }; - const versionOk = installedVersionMatches(input.installedVersion, input.pin.version); - const headOk = Boolean(input.pin.headCid && input.installedHeadCid === input.pin.headCid); + const versionOk = versionAtLeast(input.installedVersion, input.pin.version); if (!input.publisher) { return input.pin.publishable ? { action: 'unchecked' } @@ -118,7 +145,7 @@ export function planRuntimeInstall(input: { } const field = pinMismatchField(input.pin, input.publisher); if (field) return { action: 'refused', field }; - const installed = versionOk && headOk && input.installRecordProved; + const installed = versionOk && input.installRecordProved; if (installed && input.componentsPresent) return { action: 'already-installed' }; if (installed && !input.componentsPresent) return { action: 'resume-setup' }; return { action: 'pinned' }; @@ -173,8 +200,9 @@ export async function installRuntime( const components = runtimeComponentsPath(dataDir); const probed = await probeInstalled(deps); let publisher: ReleaseHead | null = null; + let raw = ''; try { - const raw = await deps.fetchText(releaseHeadUrl(deps.pin)); + raw = await deps.fetchText(releaseHeadUrl(deps.pin)); publisher = verifyReleaseHead(raw, deps.pin.maintainerDid); onProgress('Release head signature matches the pinned maintainer'); } catch (err) { @@ -186,7 +214,7 @@ export async function installRuntime( arch: deps.arch, installedVersion: probed, installedHeadCid: readInstalledHeadCid(deps), - installRecordProved: await recordProved(deps, dataDir), + installRecordProved: await recordProved(deps, dataDir, probed, readInstalledHeadCid(deps)), componentsPresent: deps.exists(components), pin: deps.pin, publisher, @@ -208,16 +236,19 @@ export async function installRuntime( throw new PinMismatchError('version'); } - await runInstallerStep(deps, onProgress); + const manifest = await deps.fetchText(`${channelGateway(deps.pin)}/release.json`); + const installerSha256 = verifiedInstallerSha256(manifest, publisher as ReturnType); + const selected = { ...deps, pin: { ...deps.pin, version: publisher.version, headCid: publisher.headCid, installerSha256 } }; + await runInstallerStep(selected, onProgress, raw, manifest); const installed = await probeInstalled(deps); - if (!installedVersionMatches(installed, deps.pin.version)) { + if (!installedVersionMatches(installed, publisher.version)) { throw new PinMismatchError('version'); } - if (readInstalledHeadCid(deps) !== deps.pin.headCid) { + if (readInstalledHeadCid(deps) !== publisher.headCid) { throw new PinMismatchError('headCid'); } onProgress('Installed head CID matches the pin'); - if (!(await recordProved(deps, dataDir))) throw new Error(NO_RECORD_AFTER_INSTALL); + if (!(await recordProved(deps, dataDir, installed, publisher.headCid))) throw new Error(NO_RECORD_AFTER_INSTALL); onProgress('Signed install record matches the pinned maintainer'); if (!deps.exists(components)) { @@ -230,9 +261,12 @@ export async function installRuntime( /** Install finished, but install.sh left no valid record. Reset could not prove this install. */ export const NO_RECORD_AFTER_INSTALL = 'ElastOS was installed, but it did not save its signed install record, so ElastOS cannot prove this install. Click Install to try again.'; -async function recordProved(deps: RuntimeInstallDeps, dataDir: string): Promise { +async function recordProved(deps: RuntimeInstallDeps, dataDir: string, version: string | null, headCid: string | null): Promise { try { - return (await deps.installRecordProved(dataDir)) === true; + if (!(await deps.installRecordProved(dataDir))) return false; + const head = verifyReleaseHead(deps.readFile(runtimeJoin(dataDir, 'installation', 'release-head.json')), deps.pin.maintainerDid); + return (!headCid || head.headCid === headCid) && installedVersionMatches(version, head.version) + && versionAtLeast(head.version, deps.pin.version); } catch { return false; } @@ -254,8 +288,13 @@ function readInstalledHeadCid(deps: RuntimeInstallDeps): string | null { } } +export function channelGateway(pin: ActiveRuntimePin): string { + const origin = pin.publisherGateway.replace(/\/$/, ''); + return pin.channel === 'stable' ? origin : `${origin}/channels/${pin.channel}`; +} + function releaseHeadUrl(pin: ActiveRuntimePin): string { - return `${pin.publisherGateway.replace(/\/$/, '')}/release-head.json`; + return `${channelGateway(pin)}/release-head.json`; } async function probeInstalled(deps: RuntimeInstallDeps): Promise { @@ -276,6 +315,8 @@ async function probeInstalled(deps: RuntimeInstallDeps): Promise async function runInstallerStep( deps: RuntimeInstallDeps, onProgress: (message: string) => void, + head: string, + manifest: string, ): Promise { if (!deps.pin.installerSha256 || !deps.pin.headCid) { throw new PinMismatchError('installerSha256'); @@ -297,12 +338,23 @@ async function runInstallerStep( writeStage(deps, 'binary'); onProgress(INSTALLING); const launch = pinnedInstallerLaunch(deps.pin, deps.env); + // The installer re-fetches both metadata URLs. Serve the verified snapshot + // through the existing curl shim so a publisher move cannot change the floor + // decision between verification and activation. Artifact URLs still use HTTPS. + const metadata = JSON.stringify({ + [`${channelGateway(deps.pin)}/release-head.json`]: head, + [`${channelGateway(deps.pin)}/release.json`]: manifest, + }); + const metadataPath = runtimeJoin(dir, 'release-metadata.json'); + deps.writeFile(metadataPath, metadata); + launch.env.ELASTOS_LAUNCHER_METADATA_PATH = metadataPath; + launch.env.ELASTOS_LAUNCHER_METADATA_SHA256 = sha256Hex(metadata); await deps.runInstaller(scriptPath, launch.args, launch.env); } /** The pinned install.sh records the head from ELASTOS_HEAD_CID and rejects a head flag. */ export function pinnedInstallerLaunch( - pin: { headCid: string | null; maintainerDid: string }, + pin: { headCid: string | null; maintainerDid: string; channel?: string; publisherGateway?: string }, parent: NodeJS.ProcessEnv = {}, ): { args: readonly string[]; env: NodeJS.ProcessEnv } { if (!pin.headCid || !/^Qm[1-9A-HJ-NP-Za-km-z]{20,}$/.test(pin.headCid)) { @@ -311,7 +363,8 @@ export function pinnedInstallerLaunch( const env = installerChildEnv(parent); env.ELASTOS_HEAD_CID = pin.headCid; return { - args: ['--install-only', '--maintainer-did', pin.maintainerDid], + args: ['--install-only', '--maintainer-did', pin.maintainerDid, + ...(pin.publisherGateway ? ['--publisher-gateway', channelGateway(pin as ActiveRuntimePin)] : [])], env, }; } @@ -357,7 +410,7 @@ export function defaultRuntimeInstallDeps(pin: ActiveRuntimePin = loadActiveRunt homeDir, env: process.env, pin, - fetchText: fetchText, + fetchText: fetchRuntimeText, runInstaller: async (scriptPath, args, env) => { const prepared = await prepareInstallerEnvironment({ homeDir, @@ -404,12 +457,34 @@ function hideHostTools(): boolean { return process.env.ELASTOS_HIDE_HOST_TOOLS === '1'; } -async function fetchText(url: string): Promise { - const response = await fetch(url); - if (!response.ok) { - throw new Error(`Could not download ${url} (HTTP ${response.status}). Check your connection and try again.`); +/** Installer bytes and release metadata are bounded in size and total fetch time. */ +export async function fetchRuntimeText(url: string): Promise { + if (!url.startsWith('https://')) throw new Error('ElastOS downloads require HTTPS.'); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), 30000); + try { + const response = await fetch(url, { signal: controller.signal }); + if (!response.ok || !response.url.startsWith('https://')) { + throw new Error(`Could not download ${url} (HTTP ${response.status}).`); + } + const reader = response.body?.getReader(); + if (!reader) throw new Error('ElastOS download has no body.'); + const chunks: Buffer[] = []; + let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > 2 * 1024 * 1024) { + await reader.cancel(); + throw new Error('ElastOS metadata or installer exceeds the download limit.'); + } + chunks.push(Buffer.from(value)); + } + return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)); + } finally { + clearTimeout(timer); } - return response.text(); } /** What the runtime target calls. Tests replace this export; they do not hit the network. */ diff --git a/src/main/targets/runtimePin.ts b/src/main/targets/runtimePin.ts index 1d5eaf6..81c9a0a 100644 --- a/src/main/targets/runtimePin.ts +++ b/src/main/targets/runtimePin.ts @@ -5,6 +5,7 @@ import { LaunchTargetId } from './types'; export type RuntimeChannelName = 'stable' | 'canary'; export interface RuntimeChannelPin { + /** Minimum accepted version. Heads are selected after DID verification. */ version: string | null; headCid: string | null; } @@ -28,7 +29,7 @@ export interface ActiveRuntimePin { publisherGateway: string; fallbackInstallerUrl: string; installerSha256: string | null; - /** True when this channel has a version and a head CID to verify. */ + /** True when this channel has a rollback floor. */ publishable: boolean; } @@ -79,7 +80,7 @@ export function activeRuntimePin(pin: RuntimePinFile): ActiveRuntimePin { publisherGateway: pin.publisherGateway, fallbackInstallerUrl: pin.fallbackInstallerUrl, installerSha256: pin.installerSha256, - publishable: Boolean(version && headCid), + publishable: Boolean(version), }; } @@ -155,7 +156,7 @@ export function overrideKeepsTrustRoot(packaged: RuntimePinFile, override: Runti } if (override.active !== packaged.active) { const selected = packaged.channels[override.active]; - if (!selected.version || !selected.headCid) return false; + if (!selected.version) return false; } return true; } diff --git a/src/main/targets/runtimeRecovery.ts b/src/main/targets/runtimeRecovery.ts index 1700e46..571eb63 100644 --- a/src/main/targets/runtimeRecovery.ts +++ b/src/main/targets/runtimeRecovery.ts @@ -37,8 +37,8 @@ export interface FailureScreen { kind: FailureKind; title: string; message: string; - retryLabel: 'Try again'; - fixLabel: 'Fix it' | null; + retryLabel: 'Try Again'; + fixLabel: 'Try Again' | null; } export interface RecoveryDeps { @@ -51,7 +51,7 @@ export interface RecoveryDeps { gatewayIdentity?: () => Promise; } -const GENERIC = 'Something went wrong. Try again. If it keeps happening, copy diagnostics.'; +const GENERIC = 'ElastOS could not finish.'; export function lockPid(text: string | null): number | null { if (!text) return null; @@ -119,24 +119,23 @@ export function removeStaleLockNow(lockPath: string, deps: { export function failureScreen(facts: FailureFacts): FailureScreen { const kind = classify(facts); if (kind === 'windows') { - const check = facts.checks.find((item) => item.id === 'windows' && item.level === 'block'); return { kind, title: 'Windows needs one step', - message: check?.message || 'Windows needs Linux support. Click Fix it. You do not type any commands.', - retryLabel: 'Try again', - fixLabel: 'Fix it', + message: /restart|reboot/i.test(facts.error) ? 'Windows needs to restart before setup can continue.' : 'Windows needs permission to finish setup.', + retryLabel: 'Try Again', + fixLabel: 'Try Again', }; } if (kind === 'no-record') { - // The refusal names the folder and the next clicks (foreignRuntimeDataMessage). + // Keep the refusal's safety facts without exposing the folder or record details. return { kind, // Windows Uninstall needs the same record (windowsUninstall.ts). title: /click Uninstall/.test(facts.error) ? 'Install ElastOS again, then uninstall' : 'Install ElastOS again, then reset', - message: plainError(facts.error, facts.checks), - retryLabel: 'Try again', - fixLabel: 'Fix it', + message: 'ElastOS needs to be installed again; Home data is kept and nothing was deleted.', + retryLabel: 'Try Again', + fixLabel: 'Try Again', }; } const copy = kind === 'other' @@ -146,8 +145,8 @@ export function failureScreen(facts: FailureFacts): FailureScreen { kind, title: copy.title, message: copy.message, - retryLabel: 'Try again', - fixLabel: kind === 'other' ? null : 'Fix it', + retryLabel: 'Try Again', + fixLabel: kind === 'other' ? null : 'Try Again', }; } @@ -271,30 +270,37 @@ function blocked(facts: FailureFacts, id: string): boolean { return facts.checks.some((check) => check.id === id && check.level === 'block'); } +// Only known display copy crosses this boundary. Raw errors stay in diagnostics. function plainError(error: string, checks: FailureCheck[]): string { if (/attach_secret|runtime-coords|BEGIN [A-Z ]*PRIVATE KEY/i.test(error)) return GENERIC; - const line = error.split('\n').map((part) => part.trim()).find(Boolean) ?? ''; - if (line && !/^\s*at\s+/.test(line)) return line.replace(/^Error:\s*/, ''); + if (/nothing was deleted/i.test(error)) return 'ElastOS could not finish. Nothing was deleted.'; + if (/restart Windows|reboot/i.test(error)) return 'Windows needs to restart before setup can continue.'; + if (/already running|already owns/i.test(error)) return 'Another Home is running.'; + if (/download/i.test(error)) return 'The download stopped.'; const block = checks.find((check) => check.level === 'block'); - return block?.message || GENERIC; + if (block?.id === 'disk') return 'ElastOS needs more free space to install.'; + if (block?.id === 'localhost') return 'ElastOS could not connect to Home on this computer.'; + if (block?.id === 'platform') return /Intel Mac/.test(block.message) + ? 'Intel Mac is not supported yet.' : 'ElastOS is not supported on this computer.'; + return GENERIC; } const COPY: Record, { title: string; message: string }> = { offline: { title: 'You are offline', - message: 'ElastOS could not reach the internet, so nothing was installed. Connect, then click Fix it to check again.', + message: 'ElastOS could not connect to the internet.', }, port: { - title: 'Port 8090 is busy', - message: 'Another program is using the address ElastOS needs. Quit that program, then click Fix it. ElastOS will not close other programs for you.', + title: 'Home could not start', + message: 'Another app is preventing Home from starting; ElastOS will not close the other app.', }, interrupted: { title: 'The install did not finish', - message: 'ElastOS was downloaded, but setup did not finish. Click Fix it to check the signed release again and continue setup. The installer is not downloaded again.', + message: 'ElastOS setup did not finish.', }, 'stale-lock': { title: 'A previous ElastOS did not close', - message: 'The old session is gone, but it left a lock. Click Fix it to clear that lock. A running ElastOS is left alone.', + message: 'ElastOS did not close properly; a running Home is left alone.', }, }; diff --git a/src/main/targets/runtimeTarget.ts b/src/main/targets/runtimeTarget.ts index abe604b..a9ba56a 100644 --- a/src/main/targets/runtimeTarget.ts +++ b/src/main/targets/runtimeTarget.ts @@ -4,14 +4,19 @@ import * as os from 'os'; import { RUNTIME_TARGET } from './descriptors'; import { createDefaultGatewaySupervisor, + confirmInstalledGateway, + installedGatewayOnThisComputer, ForeignGatewayError, GatewaySupervisor, + GatewayLifetime, + homeGatewayLifetime, + homeLaunchForPlatform, isHealthOk, openRuntimeHome, probeGatewayHealth, } from './runtimeGateway'; import * as runtimeInstall from './runtimeInstall'; -import { runtimeBinaryPath, runtimeComponentsPath, runtimeDataDir, runtimeUpdateCheckPath } from './runtimePaths'; +import { runtimeBinaryPath, runtimeComponentsPath, runtimeDataDir, runtimeUpdateCheckPath, runtimeJoin, signedInstallRecord } from './runtimePaths'; import { findRuntimeBinary, parseRuntimeVersion, probeRuntimeInstallation, RUNTIME_VERSION_ARGS } from './runtimeProbe'; import { runtimeInstallBlock } from './runtimeSupport'; import { removeVerifiedTarget, uninstallRuntime } from './runtimeUninstall'; @@ -19,11 +24,13 @@ import { applyRuntimeUpdate, checkRuntimeUpdate, HeadVerify, + launcherUpdateStatusStore, rollbackRuntime, RuntimeCommand, runRuntimeCommand, runtimeHeadStore, toUpdateCheck, + writeSignedUpdateCheck, } from './runtimeUpdate'; import { loadActiveRuntimePin } from './runtimePin'; import { @@ -33,10 +40,58 @@ import { readDistroVersion, runDistroRuntimeCommand, } from './windowsRuntime'; -import { LaunchTarget, UpdateCheck } from './types'; +import { HomeStartResult, LaunchTarget, UpdateCheck } from './types'; -export function createRuntimeTarget(): LaunchTarget { +export function createRuntimeTarget(platform: NodeJS.Platform = process.platform, arch: string = process.arch, lifetime: GatewayLifetime = homeGatewayLifetime): LaunchTarget { let supervisor: GatewaySupervisor | null = null; + let updating = false; + let requestedRunning = false; + let lifecycle = Promise.resolve(); + + function serialize(action: () => Promise): Promise { + const next = lifecycle.then(action); + lifecycle = next.then(() => {}, () => {}); + return next; + } + + async function startGateway(): Promise { + if (!requestedRunning) return 'stopped'; + if (platform === 'win32') { + if (!distroIsInstalled()) throw new Error('ElastOS is not installed yet. Click Install.'); + if (!supervisor) supervisor = createDistroGatewaySupervisor(lifetime); + } else { + const block = runtimeInstallBlock(platform, arch); + if (block) throw new Error(block); + const file = binary(); + if (!file) throw new Error('ElastOS is not installed yet. Click Install.'); + if (!supervisor) supervisor = createDefaultGatewaySupervisor(file, platform, lifetime); + } + return supervisor.start(); + } + + function changeRuntime(action: () => Promise): Promise { + if (platform !== 'darwin' && platform !== 'win32') return serialize(action); + if (updating) return Promise.reject(new Error('An ElastOS update is already running.')); + updating = true; + requestedRunning = true; + return serialize(async () => { + // A failed Stop keeps its supervisor and must never lead to a new Start. + await stopGateway(true); + try { + await action(); + } finally { + if (requestedRunning) { + supervisor = null; + await startGateway(); + } + } + }).finally(() => { updating = false; }); + } + + function requestStop(adopt: boolean): Promise { + requestedRunning = false; + return serialize(() => stopGateway(adopt)); + } function binary(): string | null { return findRuntimeBinary(os.homedir(), process.env.PATH ?? ''); @@ -44,132 +99,172 @@ export function createRuntimeTarget(): LaunchTarget { async function stopGateway(adopt: boolean): Promise { if (!supervisor) { - supervisor = process.platform === 'win32' - ? createDistroGatewaySupervisor() - : createDefaultGatewaySupervisor(binary() ?? runtimeBinaryPath(os.homedir())); + supervisor = platform === 'win32' + ? createDistroGatewaySupervisor(lifetime) + : createDefaultGatewaySupervisor(binary() ?? runtimeBinaryPath(os.homedir()), platform, lifetime); } await supervisor.stop({ adopt }); } + async function runWithHomeRestart(action: () => Promise): Promise { + if (updating) throw new Error('An ElastOS update is already running.'); + updating = true; + try { + await stopGateway(true); + await action(); + } finally { + try { + if (requestedRunning) { + supervisor = null; + await startGateway(); + } + } finally { + updating = false; + } + } + } + return { id: 'runtime', descriptor: RUNTIME_TARGET, isInstalled: () => runtimeIsInstalled(), getStatus: async () => { + if (updating) return 'starting'; + if (platform === 'linux' && (await installedGatewayOnThisComputer(platform)) === 'legacy') { + return 'other-home'; + } + const observedSupervisor = supervisor; + const observedPhase = supervisor?.phase(); if (supervisor) { - const phase = supervisor.phase(); - if (phase === 'starting' || phase === 'stopping' || phase === 'running' || phase === 'error') { + const phase = observedPhase; + if (phase === 'starting' || phase === 'stopping' || phase === 'error' + || (phase === 'running' && platform !== 'darwin' && platform !== 'win32')) { return phase; } } - if (process.platform === 'win32') { + if (platform === 'win32') { if (!distroIsInstalled()) return 'not-installed'; - if (isHealthOk(await readHealth())) return 'running'; + if (isHealthOk(await readHealth())) { + // A live controller keeps Home up after the child pid changes. Health + // and the distro facts are the status, not the supervisor's old phase. + if (!(await confirmInstalledGateway())) { + throw new Error('Another program is answering on port 8090. Home was not adopted.'); + } + return 'running'; + } return 'stopped'; } - if (runtimeInstallBlock(process.platform, process.arch)) return 'not-installed'; - if (!(await runtimeIsInstalled())) return 'not-installed'; - if (isHealthOk(await readHealth())) return 'running'; - return 'stopped'; - }, - start: async () => { - if (process.platform === 'win32') { - if (!distroIsInstalled()) throw new Error('ElastOS is not installed yet. Click Install.'); - if (!supervisor) supervisor = createDistroGatewaySupervisor(); - await supervisor.start(); - return; + if (runtimeInstallBlock(platform, arch)) return 'not-installed'; + const installed = await runtimeIsInstalled(); + if (updating) return 'starting'; + if (!installed) return 'not-installed'; + const health = await readHealth(); + if (platform === 'darwin') { + const foreign = isHealthOk(health) && !(await confirmInstalledGateway()); + // A control action can finish while version, health and socket probes + // are in flight. Its new phase supersedes those earlier observations. + const latestPhase = supervisor?.phase(); + if (updating) return 'starting'; + if (supervisor !== observedSupervisor || latestPhase !== observedPhase) return latestPhase ?? 'stopped'; + if (foreign) throw new Error('Another program is answering on port 8090. Home was not adopted.'); } - const block = runtimeInstallBlock(process.platform, process.arch); - if (block) throw new Error(block); - const file = binary(); - if (!file) throw new Error('ElastOS is not installed yet. Click Install.'); - if (!supervisor) supervisor = createDefaultGatewaySupervisor(file); - await supervisor.start(); + return isHealthOk(health) ? 'running' : 'stopped'; }, - stop: () => stopGateway(false), - stopForRemoval: () => stopGateway(true), + start: () => { + requestedRunning = true; + return serialize(startGateway); + }, + beginShutdown: () => { lifetime.shutdown(); }, + stop: () => requestStop(false), + stopForRemoval: () => requestStop(true), forceStop: () => { + requestedRunning = false; supervisor?.forceKill(); }, - restart: async () => { - await stopGateway(false); - if (process.platform === 'win32') { - if (!distroIsInstalled()) throw new Error('ElastOS is not installed yet. Click Install.'); - if (!supervisor) supervisor = createDistroGatewaySupervisor(); - await supervisor.start(); - return; - } - const file = binary(); - if (!file) throw new Error('ElastOS is not installed yet. Click Install.'); - if (!supervisor) supervisor = createDefaultGatewaySupervisor(file); - await supervisor.start(); + restart: () => { + requestedRunning = true; + return serialize(async () => { + await stopGateway(false); + await startGateway(); + }); }, install: (onProgress) => runtimeInstall.installRuntimeOnThisComputer(onProgress), - update: (onProgress) => applyRuntimeUpdate(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress), + update: (onProgress) => { + const action = () => applyRuntimeUpdate(runtimeCommand(platform), runtimeHeadStore(), headVerify(platform), onProgress); + if (platform === 'darwin' || platform === 'win32') return changeRuntime(action); + if (!homeLaunchForPlatform(platform).updateRestartsHome) return serialize(action); + requestedRunning = true; + return serialize(() => runWithHomeRestart(action)); + }, + rollback: (onProgress) => { + const action = () => rollbackRuntime(runtimeCommand(platform), runtimeHeadStore(), headVerify(platform), onProgress); + if (platform === 'darwin' || platform === 'win32') return changeRuntime(action); + if (!homeLaunchForPlatform(platform).rollbackRestartsHome) return serialize(action); + requestedRunning = true; + return serialize(() => runWithHomeRestart(action)); + }, // On Windows the launch controller runs uninstallRuntimeInDistro (windowsUninstall.ts) with the two answers. - uninstall: () => (process.platform === 'win32' ? Promise.reject(new Error('Uninstall on Windows needs your answer in the Uninstall window. Nothing was removed.')) : runtimeUninstall(() => stopGateway(true))), - getVersion: () => (process.platform === 'win32' ? readDistroVersion() : readRuntimeVersion()), - checkForUpdate: () => runtimeCheckForUpdate(), + uninstall: (deleteData = false) => { + requestedRunning = false; + return platform === 'win32' + ? Promise.reject(new Error('Uninstall on Windows needs your answer in the Uninstall window. Nothing was removed.')) + : serialize(() => runtimeUninstall(() => stopGateway(true), deleteData)); + }, + getVersion: () => (platform === 'win32' ? readDistroVersion() : readRuntimeVersion(platform, arch)), + checkForUpdate: () => runtimeCheckForUpdate(platform, arch), openInBrowser: () => openRuntimeHome(), getLogs: async (lines) => supervisor?.getLogs(lines) ?? '', }; } -function runtimeCommand(): RuntimeCommand { - return process.platform === 'win32' ? runDistroRuntimeCommand : runRuntimeCommand; +function runtimeCommand(platform: NodeJS.Platform): RuntimeCommand { + return platform === 'win32' ? runDistroRuntimeCommand : runRuntimeCommand; } -function readHostUpdateStatus(): string { +function readHostUpdateStatus(platform: NodeJS.Platform): string { const home = os.homedir(); - return fs.readFileSync(runtimeUpdateCheckPath(runtimeDataDir(process.platform, home, process.env)), 'utf8'); + return fs.readFileSync(runtimeUpdateCheckPath(runtimeDataDir(platform, home, process.env)), 'utf8'); } -async function runtimeCheckForUpdate(): Promise { - let releaseUrl = ''; - try { - releaseUrl = loadActiveRuntimePin().publisherGateway; - } catch { - releaseUrl = ''; - } +async function runtimeCheckForUpdate(platform: NodeJS.Platform, arch: string): Promise { + // The signed offer has no release-notes URL. A publisher gateway is not release notes. + const releaseUrl = ''; const notInstalled = toUpdateCheck('not installed', { updateAvailable: false, detail: 'not installed', latest: null, }, releaseUrl); - if (process.platform === 'win32') { - if (!distroIsInstalled()) return notInstalled; - const parsed = await checkRuntimeUpdate(runDistroRuntimeCommand, readDistroUpdateStatus); - return toUpdateCheck(readDistroVersion(), parsed, releaseUrl); - } - if (runtimeInstallBlock(process.platform, process.arch)) return notInstalled; - if (!findRuntimeBinary(os.homedir(), process.env.PATH ?? '')) return notInstalled; - const parsed = await checkRuntimeUpdate(runRuntimeCommand, readHostUpdateStatus); - return toUpdateCheck(readRuntimeVersion(), parsed, releaseUrl); -} - -export async function rollbackRuntimeUpdate( - onProgress: (message: string) => void = () => {}, -): Promise { - await rollbackRuntime(runtimeCommand(), runtimeHeadStore(), headVerify(), onProgress); + const windows = platform === 'win32'; + if (windows ? !distroIsInstalled() : runtimeInstallBlock(platform, arch) + || !findRuntimeBinary(os.homedir(), process.env.PATH ?? '')) return notInstalled; + const current = windows ? readDistroVersion() : readRuntimeVersion(platform, arch); + const store = launcherUpdateStatusStore(os.homedir()); + const fallback = async () => { + await writeSignedUpdateCheck(current, loadActiveRuntimePin(), runtimeInstall.fetchRuntimeText, store.write); + return store.read(); + }; + const parsed = await checkRuntimeUpdate(windows ? runDistroRuntimeCommand : runRuntimeCommand, + windows ? readDistroUpdateStatus : () => readHostUpdateStatus(platform), fallback); + return toUpdateCheck(current, parsed, releaseUrl); } -function headVerify(): HeadVerify { +function headVerify(platform: NodeJS.Platform): HeadVerify { const pin = loadActiveRuntimePin(); return { maintainerDid: pin.maintainerDid, publisherGateway: pin.publisherGateway, - fetchText: async (url: string) => { - const response = await fetch(url); - if (!response.ok) { - throw new Error('Could not verify the ElastOS release head.'); - } - return response.text(); + fetchText: runtimeInstall.fetchRuntimeText, + minimumVersion: pin.version ?? '2.0.0', + readInstalledHead: platform === 'win32' ? undefined : () => { + const data = runtimeDataDir(platform, os.homedir(), process.env); + if (!signedInstallRecord(data, pin.maintainerDid)) throw new Error('The signed install record is not valid.'); + return fs.readFileSync(runtimeJoin(data, 'installation', 'release-head.json'), 'utf8'); }, }; } -function readRuntimeVersion(): string { - const block = runtimeInstallBlock(process.platform, process.arch); +function readRuntimeVersion(platform: NodeJS.Platform = process.platform, arch: string = process.arch): string { + const block = runtimeInstallBlock(platform, arch); if (block) return block; const file = findRuntimeBinary(os.homedir(), process.env.PATH ?? ''); if (!file) return 'not installed'; @@ -185,9 +280,10 @@ async function readHealth(): Promise<{ status: number; body: string } | null> { return probeGatewayHealth({ timeoutMs: 500 }); } -async function runtimeUninstall(stop: () => Promise): Promise { +async function runtimeUninstall(stop: () => Promise, deleteData: boolean): Promise { const home = os.homedir(); await uninstallRuntime({ + deleteData, binary: runtimeBinaryPath(home), dataDir: runtimeDataDir(process.platform, home, process.env), stop: async () => { @@ -214,6 +310,7 @@ async function runtimeIsInstalled(): Promise { pathEnv: process.env.PATH, }); if (probe.kind !== 'version') return false; + if (!runtimeInstall.versionAtLeast(probe.version, loadActiveRuntimePin().version)) return false; const components = runtimeComponentsPath(runtimeDataDir(process.platform, homeDir, process.env)); try { return fs.statSync(components).isFile(); diff --git a/src/main/targets/runtimeUninstall.ts b/src/main/targets/runtimeUninstall.ts index a76ec53..01bc0b1 100644 --- a/src/main/targets/runtimeUninstall.ts +++ b/src/main/targets/runtimeUninstall.ts @@ -427,6 +427,7 @@ export function sweepRemovalHoldings( } export async function uninstallRuntime(deps: { + deleteData?: boolean; binary: string; dataDir: string; stop: () => Promise; @@ -452,7 +453,7 @@ export async function uninstallRuntime(deps: { assertStableRemovalTarget(deps.binary, lstat); assertStableRemovalTarget(deps.dataDir, lstat); deps.remove(deps.binary); - deps.remove(deps.dataDir); + if (deps.deleteData === true) deps.remove(deps.dataDir); } export const RESET_CHOICE_MESSAGE = diff --git a/src/main/targets/runtimeUpdate.ts b/src/main/targets/runtimeUpdate.ts index 95a518d..c521c05 100644 --- a/src/main/targets/runtimeUpdate.ts +++ b/src/main/targets/runtimeUpdate.ts @@ -1,10 +1,14 @@ import { execFile as execFileCb } from 'child_process'; +import { randomUUID } from 'crypto'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { findRuntimeBinary } from './runtimeProbe'; import { runtimeChildEnv, verifyReleaseHead } from './releaseHead'; import { UpdateCheck } from './types'; +import { ActiveRuntimePin } from './runtimePin'; +import { removeVerifiedTarget } from './runtimeUninstall'; +import { channelGateway, pinMismatchField, PinMismatchError, versionAtLeast, installedVersionMatches } from './runtimeInstall'; export const UPDATE_CANCELLED_LINE = 'Update cancelled.'; export const UPDATE_STATUS_UNREADABLE = 'ElastOS update status is not readable.'; @@ -70,6 +74,8 @@ export interface HeadVerify { maintainerDid: string; publisherGateway: string; fetchText: (url: string) => Promise; + readInstalledHead?: () => string | Promise; + minimumVersion?: string; } export function isStoredHeadCid(value: string): boolean { @@ -87,24 +93,71 @@ export async function verifiedHeadForRollback(candidate: string, verify: HeadVer if (verified.headCid !== candidate) { throw new Error('Refusing to store a head CID this launcher did not verify.'); } + if (!versionAtLeast(verified.version, verify.minimumVersion ?? '2.0.0')) { + throw new Error('The previous ElastOS release is below the minimum version.'); + } return verified.headCid; } export async function checkRuntimeUpdate( run: RuntimeCommand, readStatus: () => string, + fallback?: () => Promise, ): Promise { const result = await run(['update', '--check']); if (result.code !== 0) { throw new Error(result.stderr.trim() || result.stdout.trim() || 'Could not check for an ElastOS update.'); } - let raw: string; - try { - raw = readStatus(); - } catch { - throw new Error(UPDATE_STATUS_UNREADABLE); - } - return parseUpdateCheckStatus(raw); + const native = () => { + try { return parseUpdateCheckStatus(readStatus()); } catch { return null; } + }; + const record = native(); + if (record) return record; + if (!fallback) throw new Error(UPDATE_STATUS_UNREADABLE); + const raw = await fallback(); + // Runtime may finish writing its refusal-aware decision while we fetch. + return native() ?? parseUpdateCheckStatus(raw); +} + +/** Runtime 2.0.0 has no status file. Keep this signed fallback launcher-owned. */ +export async function writeSignedUpdateCheck( + current: string, + pin: ActiveRuntimePin, + fetchText: (url: string) => Promise, + writeStatus: (raw: string) => void, +): Promise { + const head = verifyReleaseHead(await fetchText(`${channelGateway(pin)}/release-head.json`), pin.maintainerDid); + const field = pinMismatchField(pin, head); + if (field) throw new PinMismatchError(field); + const version = current.replace(/^ElastOS Runtime v/, ''); + if (!versionAtLeast(version, pin.version)) throw new Error(UPDATE_STATUS_UNREADABLE); + const offered = !versionAtLeast(version, head.version); + const newer = !versionAtLeast(head.version, version); + writeStatus(JSON.stringify({ + schema: UPDATE_CHECK_SCHEMA, + outcome: offered ? 'update_available' : newer ? 'installed_newer' : 'up_to_date', + current_version: version, + latest_version: head.version, + offered, + })); +} + +export function launcherUpdateStatusStore(homeDir: string): { read(): string; write(raw: string): void } { + const dir = path.join(homeDir, '.elastos-launcher'); + const file = path.join(dir, 'update-check.json'); + return { + read: () => fs.readFileSync(file, 'utf8'), + write(raw) { + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + const temporary = `${file}.${randomUUID()}.tmp`; + try { + fs.writeFileSync(temporary, raw, { flag: 'wx', mode: 0o600 }); + fs.renameSync(temporary, file); + } finally { + if (fs.existsSync(temporary)) removeVerifiedTarget(temporary); + } + }, + }; } export async function applyRuntimeUpdate( @@ -118,7 +171,16 @@ export async function applyRuntimeUpdate( if (shown.code !== 0) { throw new Error(shown.stderr.trim() || 'Could not read the installed ElastOS release.'); } - const candidate = parseHeadCid(shown.stdout); + let candidate = parseHeadCid(shown.stdout); + if ((!candidate || candidate === 'unknown') && verify.readInstalledHead) { + const installed = verifyReleaseHead(await verify.readInstalledHead(), verify.maintainerDid); + const binary = await run(['version']); + if (binary.code !== 0 || !installedVersionMatches(binary.stdout, installed.version) + || !versionAtLeast(installed.version, verify.minimumVersion ?? '2.0.0')) { + throw new Error('The signed install record does not match the installed ElastOS version.'); + } + candidate = installed.headCid; + } if (!candidate) { throw new Error('Refusing to store a head CID this launcher did not verify.'); } @@ -173,8 +235,20 @@ export function runtimeHeadStore(homeDir: string = os.homedir()): HeadCidStore { } }, set(cid: string) { - fs.mkdirSync(path.dirname(file), { recursive: true }); - fs.writeFileSync(file, JSON.stringify({ headCid: cid })); + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const temporary = `${file}.${randomUUID()}.tmp`; + try { + const fd = fs.openSync(temporary, 'wx', 0o600); + try { + fs.writeFileSync(fd, JSON.stringify({ headCid: cid })); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + fs.renameSync(temporary, file); + } finally { + if (fs.existsSync(temporary)) removeVerifiedTarget(temporary); + } }, }; } diff --git a/src/main/targets/types.ts b/src/main/targets/types.ts index dcf0dce..ce09a15 100644 --- a/src/main/targets/types.ts +++ b/src/main/targets/types.ts @@ -12,7 +12,8 @@ export type TargetStatus = | 'starting' | 'stopping' | 'error' - | 'not-installed'; + | 'not-installed' + | 'other-home'; export interface TargetPlatform { platform: 'darwin' | 'linux' | 'win32'; @@ -40,7 +41,7 @@ export interface LaunchTargetDescriptor { /** Arguments for a launcher-owned start. Not invoked by the registry. */ startArgs: readonly string[]; health: HealthProbe; - /** Page "Open my computer" should open once health passes. */ + /** Page "Open Home" should open once health passes. */ openUrl: string; platforms: readonly TargetPlatform[]; } @@ -52,13 +53,18 @@ export interface UpdateCheck { releaseUrl: string; } +/** Whether this call launched Home, opened an existing Home, reused it, or was stopped. */ +export type HomeStartResult = 'started' | 'already-running' | 'running' | 'stopped'; + export interface LaunchTarget { readonly id: LaunchTargetId; readonly descriptor: LaunchTargetDescriptor; isInstalled(): Promise; getStatus(): Promise; - start(): Promise; - /** Stop a gateway this window started. Does not adopt one it did not start. */ + start(): Promise; + /** Permanently refuse Home starts before waiting for shutdown work. */ + beginShutdown(): void; + /** Stop this window's gateway; on macOS, also adopt a proved installed Home. */ stop(): Promise; /** Reset and Uninstall, after the confirm dialog, may adopt the installed gateway. */ stopForRemoval(): Promise; @@ -66,7 +72,8 @@ export interface LaunchTarget { restart(): Promise; install(onProgress: (message: string) => void): Promise; update(onProgress: (message: string) => void): Promise; - uninstall(): Promise; + rollback(onProgress?: (message: string) => void): Promise; + uninstall(deleteData?: boolean): Promise; getVersion(): string; checkForUpdate(): Promise; openInBrowser(): void; diff --git a/src/main/targets/windowsHost.ts b/src/main/targets/windowsHost.ts index c34683d..948bcef 100644 --- a/src/main/targets/windowsHost.ts +++ b/src/main/targets/windowsHost.ts @@ -49,7 +49,7 @@ export function hostPrompt(facts: WindowsFacts): HostPrompt { return { kind: 'enable-wsl', title: 'Windows needs Linux support', - body: 'ElastOS on Windows runs in its own Linux environment. Click Enable. Windows will ask for permission once, and it may ask you to restart. After that restart, open ElastOS and Install continues. You do not type any commands.', + body: 'Windows needs permission to enable Linux support.', actionLabel: 'Enable', }; } @@ -57,14 +57,14 @@ export function hostPrompt(facts: WindowsFacts): HostPrompt { return { kind: 'setup-distro', title: 'Set up ElastOS on Windows', - body: 'Linux support is on. Click Set up and ElastOS will add its own Linux environment. Windows may ask for permission. You do not type any commands.', + body: 'ElastOS needs to finish setup on this computer.', actionLabel: 'Set up', }; } return { kind: 'ready', title: 'Windows is ready', - body: 'Linux support is on. Click Install. ElastOS sets itself up in its own Linux environment and opens in the browser. You do not type any commands.', + body: '', actionLabel: null, }; } @@ -83,7 +83,7 @@ export function importDistroArgs(installDir: string, rootfs: string): readonly s return ['--import', 'ElastOS', installDir, rootfs, '--version', '2']; } -export const WINDOWS_REBOOT_MESSAGE = 'Restart Windows. When you open ElastOS again, Install continues.'; +export const WINDOWS_REBOOT_MESSAGE = 'Windows needs to restart before setup can continue.'; export type ResumeInstallPlan = 'install' | 'wait' | 'none'; diff --git a/src/main/targets/windowsReset.ts b/src/main/targets/windowsReset.ts index 4865232..f67e4b6 100644 --- a/src/main/targets/windowsReset.ts +++ b/src/main/targets/windowsReset.ts @@ -369,8 +369,9 @@ export async function removeInDistro( run: DistroHelperRun, paths: DistroResetPaths, plan: DistroRemovalPlan, + keepData = false, ): Promise { - const result = await run('remove', { ...helperInput(paths), ...plan }, { timeoutMs: 30 * 60 * 1000 }); + const result = await run('remove', { ...helperInput(paths), ...plan, keepData }, { timeoutMs: 30 * 60 * 1000 }); if (result.code === 3) { if (/ELASTOS-REFUSED mount/.test(result.stderr)) throw new Error(mountedMessage(`${paths.dataDir} ${DATA_IN_LINUX}`, ['.'])); throw new Error(`ElastOS was not reset, because its files ${DATA_IN_LINUX} changed. Nothing was deleted there. Click Reset to try again.`); diff --git a/src/main/targets/windowsRuntime.ts b/src/main/targets/windowsRuntime.ts index 57fb50f..dce4234 100644 --- a/src/main/targets/windowsRuntime.ts +++ b/src/main/targets/windowsRuntime.ts @@ -1,4 +1,4 @@ -import { spawn, spawnSync } from 'child_process'; +import { ChildProcess, spawn, spawnSync } from 'child_process'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -13,8 +13,9 @@ import { WINDOWS_NATIVE_MESSAGE } from './runtimeSupport'; import { createGatewaySupervisor, emitRuntimeLog, - GATEWAY_ARGS, GatewayProcess, + GatewayLifetime, + homeGatewayLifetime, InstalledGatewayKind, installedGatewayKind, listenerOwnership, @@ -38,9 +39,10 @@ export const DISTRO_INSTALL_DIR = 'C:\\ElastOS\\distro'; export const DISTRO_IMPORT_FAILED = 'ElastOS could not add its Linux environment. Click Install to try again.'; export const DISTRO_SETUP_FAILED = 'ElastOS could not finish setting up its Linux environment. Click Install to try again.'; export const DISTRO_INSTALL_FAILED = 'ElastOS could not be installed. Click Install to try again.'; +export const HOME_UNCONFIRMED_MESSAGE = 'Home could not be confirmed'; const FILE_HELPER = ` -import base64, sys, pathlib +import base64, os, stat, sys, pathlib op, raw = sys.argv[1], sys.argv[2] root = pathlib.PurePosixPath('/root') target = pathlib.PurePosixPath(raw) @@ -54,23 +56,322 @@ elif op == 'write': path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) elif op == 'read': - sys.stdout.write(base64.b64encode(path.read_bytes()).decode('ascii')) + limit = int(sys.argv[3]) if len(sys.argv) > 3 else None + if limit is not None: + info = path.lstat() + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_size > limit: + raise SystemExit(2) + fd = os.open(raw, os.O_RDONLY | os.O_NOFOLLOW) + try: + data = os.read(fd, limit + 1) + finally: + os.close(fd) + if len(data) > limit: + raise SystemExit(2) + else: + data = path.read_bytes() + sys.stdout.write(base64.b64encode(data).decode('ascii')) elif op == 'exists': raise SystemExit(0 if path.is_file() else 1) else: raise SystemExit(2) `.trim(); -const STOP_HELPER = ` -import os, signal, sys -name = sys.argv[1] -raw = sys.argv[2] -if type(raw) is not str or not raw.isdigit(): - raise SystemExit(1) -pid = int(raw) -if type(pid) is not int or pid <= 1: +export const STOP_HELPER = ` +import errno, json, os, signal, stat, sys, time +MESSAGE = 'Home could not be confirmed' +RECORD_MAX = 16384 +STAT_MAX = 4096 +LINK_MAX = 4096 +BOOT_MAX = 128 +CMD_MAX = 64 +DATA = '/root/.local/share/elastos' +LOCK = DATA + '/host-process.lock' +STATUS = DATA + '/update-controller/status.json' +RUNTIME = DATA + '/update-controller/runtime' +BINARY = '/root/.local/bin/elastos' + +def located(root, suffix): + if root == '/': + return suffix + return root.rstrip('/') + suffix + +def publish(channel, seq, text): + final = os.path.join(channel, 'reply-%d' % seq) + tmp = final + '.tmp' + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + try: + os.write(fd, (text + '\\n').encode('utf-8')) + finally: + os.close(fd) + os.replace(tmp, final) + +def refuse(channel): + try: + publish(channel, 0, MESSAGE) + except Exception: + pass raise SystemExit(1) -os.kill(-pid, signal.SIGKILL if name == 'KILL' else signal.SIGTERM) + +def walk(path): + current = '' + parts = path.strip('/').split('/') + if not parts or parts == ['']: + return None + for index, part in enumerate(parts): + current = current + '/' + part + try: + info = os.lstat(current) + except OSError: + return None + if stat.S_ISLNK(info.st_mode): + return False + if index == len(parts) - 1: + return info + return None + +def read_file(path, limit): + info = walk(path) + if info is None or info is False: + return info + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + return False + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return False + try: + data = os.read(fd, limit + 1) + finally: + os.close(fd) + if len(data) > limit: + return False + return data + +def load_json(data): + if data is None or data is False: + return data + try: + parsed = json.loads(data.decode('utf-8')) + except Exception: + return False + if type(parsed) is not dict: + return False + return parsed + +def positive(value): + if type(value) is not int or value <= 1: + return None + return value + +def token(value, limit): + if type(value) is not str or value == '' or len(value) > limit: + return None + if '\\r' in value or '\\n' in value: + return None + return value + +def prove(root): + lock = load_json(read_file(located(root, LOCK), RECORD_MAX)) + status = load_json(read_file(located(root, STATUS), RECORD_MAX)) + if lock is None or lock is False or status is None or status is False: + return None + if lock.get('role') != 'gateway' or lock.get('addr') != 'localhost:8090': + return None + generation = token(lock.get('generation'), 128) + if generation is None or generation != token(status.get('generation'), 128): + return None + start = token(status.get('controller_start'), 200) + host = positive(lock.get('pid')) + if start is None or host is None or positive(status.get('host_pid')) != host: + return None + controller = positive(status.get('controller_pid')) + if controller is None or controller == host: + return None + return controller, start + +def start_ticks(text, pid): + space = text.find(' ') + if space <= 0 or text[:space] != str(pid): + return None + end = text.rfind(')') + if end < 0: + return None + parts = text[end + 1:].split() + if len(parts) <= 19 or not parts[19].isdigit(): + return None + return parts[19] + +def load_boot(root): + data = read_file(located(root, '/proc/sys/kernel/random/boot_id'), BOOT_MAX) + if data is None: + return True, None + if data is False: + return False, None + boot = data.decode('utf-8', 'replace').strip() + if boot == '' or any(ch.isspace() for ch in boot): + return False, None + return True, boot + +def process_identity(text, boot, pid): + ticks = start_ticks(text, pid) + if ticks is None: + return None + if boot is None: + return 'linux:' + ticks + return 'linux:' + boot + ':' + ticks + +def allowed_exes(root): + found = [] + for suffix in (RUNTIME, BINARY): + path = located(root, suffix) + info = walk(path) + if info is None or info is False or not stat.S_ISREG(info.st_mode): + continue + real = os.path.realpath(path) + if real not in found: + found.append(real) + return found + +def controller_exe(root, pid): + path = located(root, '/proc/%d/exe' % pid) + parent = path.rsplit('/', 1)[0] + info = walk(parent) + if info is None or info is False or not stat.S_ISDIR(info.st_mode): + return None + try: + leaf = os.lstat(path) + except OSError: + return None + if not stat.S_ISLNK(leaf.st_mode): + return None + try: + link = os.readlink(path) + except OSError: + return None + if len(link) > LINK_MAX or not link.startswith('/') or link.endswith(' (deleted)'): + return None + if '\\n' in link or '\\r' in link or '\\x00' in link: + return None + return os.path.realpath(link) + +def identity_matches(root, pid, start): + data = read_file(located(root, '/proc/%d/stat' % pid), STAT_MAX) + if data is None or data is False: + return False + ok, boot = load_boot(root) + if not ok: + return False + if process_identity(data.decode('utf-8', 'replace'), boot, pid) != start: + return False + exe = controller_exe(root, pid) + if exe is None: + return False + return exe in allowed_exes(root) + +def channel_open(channel): + try: + info = os.lstat(channel) + except OSError: + return False + return (not stat.S_ISLNK(info.st_mode)) and stat.S_ISDIR(info.st_mode) + +def read_cmd(channel, seq): + path = os.path.join(channel, 'cmd-%d' % seq) + while channel_open(channel): + try: + info = os.lstat(path) + except OSError: + time.sleep(0.02) + continue + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_size > CMD_MAX: + return None + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + data = os.read(fd, CMD_MAX + 1) + finally: + os.close(fd) + if len(data) > CMD_MAX: + return None + if not data.endswith(b'\\n'): + time.sleep(0.02) + continue + return data.decode('utf-8', 'replace').strip() + return None + +def serve(root, channel): + proved = prove(root) + if proved is None: + refuse(channel) + pid, start = proved + opener = getattr(os, 'pidfd_open', None) + sender = getattr(signal, 'pidfd_send_signal', None) + if opener is None or sender is None: + refuse(channel) + try: + pidfd = opener(pid, 0) + except OSError: + refuse(channel) + try: + if not identity_matches(root, pid, start): + refuse(channel) + publish(channel, 0, 'ready') + seq = 1 + while True: + command = read_cmd(channel, seq) + if command is None: + return + if command == 'close': + publish(channel, seq, 'closed') + return + if command == 'TERM': + sig = signal.SIGTERM + elif command == 'KILL': + sig = signal.SIGKILL + else: + publish(channel, seq, MESSAGE) + seq += 1 + continue + try: + sender(pidfd, sig, None, 0) + except OSError as err: + code = errno.errorcode.get(err.errno, '') + if code == 'ESRCH': + publish(channel, seq, 'errno ESRCH') + else: + publish(channel, seq, MESSAGE) + seq += 1 + continue + publish(channel, seq, 'sent') + seq += 1 + finally: + try: + os.close(pidfd) + except OSError: + pass + +def main(): + root = sys.argv[1] if len(sys.argv) > 1 else '/' + channel = sys.argv[2] if len(sys.argv) > 2 else '' + if not root.startswith('/') or not channel.startswith('/'): + raise SystemExit(1) + try: + info = os.lstat(channel) + except OSError: + raise SystemExit(1) + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + raise SystemExit(1) + try: + serve(root, channel) + except SystemExit: + raise + except Exception: + refuse(channel) + +main() `.trim(); const LOCK_PID_HELPER = ` @@ -98,43 +399,95 @@ except OSError: raise SystemExit(0) `.trim(); -const FACTS_HELPER = ` -import json, os -lock_path = '/root/.local/share/elastos/host-process.lock' +export const FACTS_HELPER = ` +import json, os, stat, sys +RECORD_MAX = 16384 +PROC_MAX = 8 * 1024 * 1024 +FD_MAX = 1024 +LINK_MAX = 4096 +root = sys.argv[1] if len(sys.argv) > 1 else '' +if root and not root.startswith('/'): + raise SystemExit(1) + +def under(suffix): + if root == '' or root == '/': + return suffix + return root.rstrip('/') + suffix + +def walk(path): + current = '' + parts = path.strip('/').split('/') + if not parts or parts == ['']: + return None + for index, part in enumerate(parts): + current = current + '/' + part + try: + info = os.lstat(current) + except OSError: + return None + if stat.S_ISLNK(info.st_mode): + return False + if index == len(parts) - 1: + return info + return None + +def read_capped(path, limit): + info = walk(path) + if info is None or info is False: + return None + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + return None + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + data = os.read(fd, limit + 1) + finally: + os.close(fd) + if len(data) > limit: + return None + return data + +lock_path = under('/root/.local/share/elastos/host-process.lock') out = {'lock': None, 'command': None, 'tcp': '', 'tcp6': '', 'links': [], 'alive': False} -try: - out['lock'] = open(lock_path).read() -except Exception: - pass +lock_data = read_capped(lock_path, RECORD_MAX) +if lock_data is not None: + out['lock'] = lock_data.decode('utf-8', 'replace') pid = 0 try: pid = json.loads(out['lock'] or '{}').get('pid') or 0 except Exception: pid = 0 if type(pid) is int and pid > 1: - out['alive'] = os.path.exists(f'/proc/{pid}') - try: - out['command'] = open(f'/proc/{pid}/cmdline', 'rb').read().replace(bytes([0]), b' ').decode() - except Exception: - out['command'] = None - try: - out['tcp'] = open('/proc/net/tcp').read() - except Exception: - out['tcp'] = '' + proc = under('/proc/%d' % pid) try: - out['tcp6'] = open('/proc/net/tcp6').read() - except Exception: - out['tcp6'] = '' + info = os.lstat(proc) + out['alive'] = (not stat.S_ISLNK(info.st_mode)) and stat.S_ISDIR(info.st_mode) + except OSError: + out['alive'] = False + command = read_capped(proc + '/cmdline', RECORD_MAX) + if command is not None: + out['command'] = command.replace(bytes([0]), b' ').decode('utf-8', 'replace') + tcp = read_capped(proc + '/net/tcp', PROC_MAX) + out['tcp'] = '' if tcp is None else tcp.decode('utf-8', 'replace') + tcp6 = read_capped(proc + '/net/tcp6', PROC_MAX) + out['tcp6'] = '' if tcp6 is None else tcp6.decode('utf-8', 'replace') links = [] - fd = f'/proc/{pid}/fd' + fd_dir = proc + '/fd' try: - for name in os.listdir(fd): + info = os.lstat(fd_dir) + names = [] if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode) else os.listdir(fd_dir) + except OSError: + names = [] + if len(names) <= FD_MAX: + for name in names: try: - links.append(os.readlink(f'{fd}/{name}')) - except Exception: - pass - except Exception: - links = [] + link = os.readlink(fd_dir + '/' + name) + except OSError: + continue + if len(link) <= LINK_MAX: + links.append(link) out['links'] = links print(json.dumps(out)) `.trim(); @@ -185,10 +538,220 @@ export function distroInstallerArgs( ]; } +/** Runtime 2.0.0 enters the update controller only through this command. */ export function distroGatewayArgs(): string[] { - return [...wslCommandPrefix(), '/root/.local/bin/elastos', ...GATEWAY_ARGS]; + return [...wslCommandPrefix(), '/root/.local/bin/elastos', 'home', '--browser']; } +/** + * The controller binary the host lock's parent must be running. + * `queue_update` accepts a request only while that process is the live controller. + */ +export const DISTRO_CONTROLLER_COMMAND = + `${runtimeDataDir('linux', DISTRO_HOME, {})}/update-controller/runtime __update-controller`; + +/** Home's controller can take the runtime's full ready budget (120s) plus margin. Mac uses the same budget. */ +export const DISTRO_HOME_READY_MS = 150_000; + +export function distroHomeSpawnOptions(env: NodeJS.ProcessEnv = wslSpawnEnv()): { + detached: true; + windowsHide: true; + stdio: ['ignore', 'pipe', 'pipe']; + env: NodeJS.ProcessEnv; +} { + return { + detached: true, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + env, + }; +} + +export interface DistroProcFact { + ppid: number | null; + command: string | null; +} + +/** Stop does not signal a pid from this report. */ +export interface DistroStopReport { + lockText: string; + statusText: string | null; + procs: Readonly>; +} + +/** Stop does not signal this value. */ +export function distroStopPid(report: DistroStopReport): number | null { + let lock: { pid?: unknown; generation?: unknown }; + try { + lock = JSON.parse(report.lockText) as { pid?: unknown; generation?: unknown }; + } catch { + return null; + } + const host = lock.pid; + if (typeof host !== 'number' || !Number.isInteger(host) || host <= 1) return null; + if (!report.statusText) return null; + let status: { host_pid?: unknown; generation?: unknown; controller_pid?: unknown }; + try { + status = JSON.parse(report.statusText) as { host_pid?: unknown; generation?: unknown; controller_pid?: unknown }; + } catch { + return null; + } + const controller = status.controller_pid; + const proved = status.host_pid === host + && typeof status.generation === 'string' + && status.generation.length > 0 + && status.generation === lock.generation + && typeof controller === 'number' + && Number.isInteger(controller) + && controller > 1 + && controller !== host; + if (!proved) return null; + const controllerFact = report.procs[String(controller)]; + const hostFact = report.procs[String(host)]; + if (!controllerFact || !hostFact) return null; + if (hostFact.ppid !== controller) return null; + if (!controllerFact.command || !controllerFact.command.includes(DISTRO_CONTROLLER_COMMAND)) return null; + return controller; +} + +export function parseDistroStopReport(raw: string): DistroStopReport | null { + let parsed: { lock?: unknown; status?: unknown; procs?: unknown }; + try { + parsed = JSON.parse(raw) as { lock?: unknown; status?: unknown; procs?: unknown }; + } catch { + return null; + } + if (typeof parsed.lock !== 'string') return null; + if (parsed.status !== null && typeof parsed.status !== 'string') return null; + if (!parsed.procs || typeof parsed.procs !== 'object') return null; + const procs: Record = {}; + for (const [key, value] of Object.entries(parsed.procs as Record)) { + if (!/^[1-9]\d*$/.test(key) || !value || typeof value !== 'object') return null; + const fact = value as { ppid?: unknown; command?: unknown }; + if (fact.ppid !== null && (typeof fact.ppid !== 'number' || !Number.isInteger(fact.ppid) || fact.ppid <= 0)) return null; + if (fact.command !== null && typeof fact.command !== 'string') return null; + procs[key] = { + ppid: typeof fact.ppid === 'number' ? fact.ppid : null, + command: typeof fact.command === 'string' ? fact.command : null, + }; + } + return { + lockText: parsed.lock, + statusText: parsed.status, + procs, + }; +} + +export const DISTRO_STOP_READER = ` +import json, os, stat +LIMIT = 16384 +ROOT = '/root/.local/share/elastos' +LOCK = ROOT + '/host-process.lock' +STATUS = ROOT + '/update-controller/status.json' + +def read_text(path, required): + current = '' + parts = path.strip('/').split('/') + info = None + for index, part in enumerate(parts): + current = current + '/' + part + try: + info = os.lstat(current) + except FileNotFoundError: + if required: + raise SystemExit(1) + return None + if stat.S_ISLNK(info.st_mode): + raise SystemExit(2) + if index == len(parts) - 1: + if not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT: + raise SystemExit(2) + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + try: + data = os.read(fd, LIMIT + 1) + finally: + os.close(fd) + if len(data) > LIMIT: + raise SystemExit(2) + return data.decode('utf-8', 'replace') + +def read_proc(path): + try: + info = os.lstat(path) + except OSError: + return None + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode) or info.st_size > LIMIT: + return None + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + data = os.read(fd, LIMIT + 1) + finally: + os.close(fd) + if len(data) > LIMIT: + return None + return data + +def pid_of(text, key): + try: + value = json.loads(text).get(key) + except Exception: + return None + if type(value) is int and value > 1: + return value + return None + +def proc_fact(pid): + base = '/proc/' + str(pid) + try: + info = os.lstat(base) + except OSError: + return None + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + return None + status = read_proc(base + '/status') + cmd = read_proc(base + '/cmdline') + ppid = None + if status: + for line in status.decode('utf-8', 'replace').split('\\n'): + if line.startswith('PPid:'): + raw = line[5:].strip() + if raw.isdigit(): + ppid = int(raw) + command = None + if cmd is not None: + command = cmd.replace(b'\\x00', b' ').decode('utf-8', 'replace').strip() + return {'ppid': ppid, 'command': command} + +lock = read_text(LOCK, True) +status = read_text(STATUS, False) +procs = {} +for key, text in (('pid', lock), ('host_pid', status), ('controller_pid', status)): + if not text: + continue + pid = pid_of(text, key) + if pid and str(pid) not in procs: + fact = proc_fact(pid) + if fact: + procs[str(pid)] = fact +print(json.dumps({'lock': lock, 'status': status, 'procs': procs})) +`.trim(); + +export function readDistroStopReport( + run: (args: readonly string[]) => { code: number; stdout: string } = (args) => runWslSync(args, undefined, 8000), +): DistroStopReport | null { + try { + const result = run(['python3', '-c', DISTRO_STOP_READER]); + if (result.code !== 0) return null; + return parseDistroStopReport(result.stdout); + } catch { + return null; + } +} + + export function distroToolCheckArgs(): readonly string[] { return ['bash', '-lc', 'command -v python3 >/dev/null && command -v curl >/dev/null']; } @@ -201,20 +764,262 @@ export function runDistroRuntimeCommand(args: readonly string[]): Promise /etc/resolv.conf; apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 curl ca-certificates']; } -/** Signal this pid's group. The helper does not read the lock again. Pid 1 is refused. */ -export function distroStopArgs(signal: 'TERM' | 'KILL', pid: number): string[] { - if (!Number.isInteger(pid) || pid <= 1) { - throw new Error('Refusing to signal that process.'); +export function distroStopArgs(root = '/', channel?: string): string[] { + const args = ['python3', '-c', STOP_HELPER, root]; + if (channel) args.push(channel); + return args; +} + +export const WSL_OUTPUT_MAX = 20 * 1024 * 1024; + +export function appendCappedOutput( + chunks: Buffer[], + total: number, + chunk: Buffer, + max = WSL_OUTPUT_MAX, +): number { + if (total >= max || chunk.length === 0) return total; + const room = max - total; + const slice = chunk.length > room ? chunk.subarray(0, room) : chunk; + chunks.push(Buffer.from(slice)); + return total + slice.length; +} + +const STOP_REPLY_MS = 8000; + +export interface DistroStopSession { + signal(name: 'TERM' | 'KILL'): void; + close(): void; + dispose(): void; +} + +function helperGone(pid: number): boolean { + try { + process.kill(pid, 0); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err + ? String((err as { code?: string }).code) + : ''; + return code === 'ESRCH'; + } + if (process.platform === 'win32') return false; + const result = spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8', timeout: 1000 }); + const state = (result.stdout || '').trim(); + return state === '' || state.startsWith('Z'); +} + +function distroVisiblePath(file: string): string { + const normalized = file.replace(/\\/g, '/'); + const drive = /^([A-Za-z]):\/(.*)$/.exec(normalized); + if (!drive) return normalized; + return `/mnt/${drive[1].toLowerCase()}/${drive[2]}`; +} + +interface CreatedDir { + path: string; + dev: number; + ino: number; +} + +function stopChannelRoot(): string { + return path.resolve(os.tmpdir()); +} + +function createStopChannel(): CreatedDir { + const dir = fs.mkdtempSync(path.join(stopChannelRoot(), 'elastos-stop-')); + fs.chmodSync(dir, 0o700); + const info = fs.lstatSync(dir); + if (info.isSymbolicLink() || !info.isDirectory()) throw new Error(HOME_UNCONFIRMED_MESSAGE); + return { path: dir, dev: info.dev, ino: info.ino }; +} + +function parentsStayReal(dir: string, root: string): boolean { + let current = path.resolve(dir); + const stop = path.resolve(root); + if (current !== stop && !current.startsWith(`${stop}${path.sep}`)) return false; + while (current !== stop) { + let info: fs.Stats; + try { + info = fs.lstatSync(current); + } catch { + return false; + } + if (info.isSymbolicLink() || !info.isDirectory()) return false; + const parent = path.dirname(current); + if (parent === current) return false; + current = parent; + } + try { + const rootInfo = fs.lstatSync(stop); + return !rootInfo.isSymbolicLink() && rootInfo.isDirectory(); + } catch { + return false; + } +} + +function removeStopChannel(dir: CreatedDir): void { + let info: fs.Stats; + try { + info = fs.lstatSync(dir.path); + } catch { + return; + } + if (info.isSymbolicLink() || !info.isDirectory()) return; + if (info.dev !== dir.dev || info.ino !== dir.ino) return; + if (!parentsStayReal(dir.path, stopChannelRoot())) return; + fs.rmSync(dir.path, { recursive: true, force: true }); +} + +function assertStopChannel(dir: CreatedDir): void { + const info = fs.lstatSync(dir.path); + if (info.isSymbolicLink() || !info.isDirectory() || info.dev !== dir.dev || info.ino !== dir.ino) { + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } +} + +function readStopReply(dir: CreatedDir, seq: number, childPid: number, timeoutMs: number): string { + assertStopChannel(dir); + const file = path.join(dir.path, `reply-${seq}`); + const deadline = Date.now() + timeoutMs; + const pause = new Int32Array(new SharedArrayBuffer(4)); + while (Date.now() < deadline) { + try { + const text = fs.readFileSync(file, 'utf8'); + if (text.includes('\n') || text.includes('\r')) return text.split(/\r?\n/, 1)[0].trim(); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err + ? String((err as { code?: string }).code) + : ''; + if (code !== 'ENOENT') throw err; + } + if (helperGone(childPid)) throw new Error(HOME_UNCONFIRMED_MESSAGE); + Atomics.wait(pause, 0, 0, 20); + } + throw new Error(HOME_UNCONFIRMED_MESSAGE); +} + +function writeStopCommand(dir: CreatedDir, seq: number, command: string): void { + assertStopChannel(dir); + const finalPath = path.join(dir.path, `cmd-${seq}`); + const tmp = `${finalPath}.tmp`; + fs.writeFileSync(tmp, `${command}\n`, { mode: 0o600 }); + fs.renameSync(tmp, finalPath); +} + +function defaultStopSpawn(args: readonly string[]): ChildProcess { + return spawn('wsl.exe', [...wslCommandPrefix(), ...args], { + windowsHide: true, + env: wslSpawnEnv(), + stdio: 'ignore', + }); +} + +export function createDistroStopSession(deps: { + root?: string; + spawn?: (args: readonly string[]) => ChildProcess; +} = {}): DistroStopSession { + const root = deps.root ?? '/'; + const launch = deps.spawn ?? defaultStopSpawn; + let dir: CreatedDir | null = null; + let child: ChildProcess | null = null; + let ready = false; + let seq = 0; + let closed = false; + let holding = false; + + function stopChild(): void { + if (!child?.pid || helperGone(child.pid)) return; + try { + child.kill('SIGKILL'); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err + ? String((err as { code?: string }).code) + : ''; + if (code !== 'ESRCH') throw err; + } } - return ['python3', '-c', STOP_HELPER, signal, String(pid)]; + + function finish(): void { + if (closed) return; + holding = true; + closed = true; + let closeError: unknown = null; + if (ready && dir && child?.pid && !helperGone(child.pid)) { + try { + seq += 1; + writeStopCommand(dir, seq, 'close'); + readStopReply(dir, seq, child.pid, STOP_REPLY_MS); + } catch (err) { + closeError = err; + } + } + const helperExited = child?.pid != null && helperGone(child.pid); + stopChild(); + if (dir) removeStopChannel(dir); + holding = false; + if (closeError && !helperExited) throw closeError; + } + + return { + signal(name) { + if (closed || (name !== 'TERM' && name !== 'KILL')) throw new Error(HOME_UNCONFIRMED_MESSAGE); + holding = true; + try { + if (!ready) { + dir = createStopChannel(); + const channel = dir.path; + child = launch(distroStopArgs(root, distroVisiblePath(channel))); + child.on('error', () => {}); + child.on('exit', () => { + if (holding) return; + closed = true; + if (dir) removeStopChannel(dir); + }); + child.unref(); + if (!child.pid) { + finish(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + const opened = readStopReply(dir, 0, child.pid, STOP_REPLY_MS); + if (opened !== 'ready') { + finish(); + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } + ready = true; + } + if (!dir || !child?.pid) throw new Error(HOME_UNCONFIRMED_MESSAGE); + seq += 1; + writeStopCommand(dir, seq, name); + const reply = readStopReply(dir, seq, child.pid, STOP_REPLY_MS); + if (reply === 'sent' || reply === 'errno ESRCH') return; + throw new Error(HOME_UNCONFIRMED_MESSAGE); + } finally { + if (!closed) holding = false; + } + }, + close() { finish(); }, + dispose() { + try { + finish(); + } catch { + // finish() already dropped the helper. Stop still reports its own error. + } + }, + }; } function plainSpawnError(err: unknown, fallback: string): Error { @@ -250,6 +1055,8 @@ function runWsl(args: readonly string[], timeoutMs: number, input?: Buffer): Pro }); const stdout: Buffer[] = []; const stderr: Buffer[] = []; + let stdoutTotal = 0; + let stderrTotal = 0; const timer = setTimeout(() => { child.kill(); reject(new Error(DISTRO_SETUP_FAILED)); @@ -258,8 +1065,12 @@ function runWsl(args: readonly string[], timeoutMs: number, input?: Buffer): Pro clearTimeout(timer); reject(plainSpawnError(err, DISTRO_SETUP_FAILED)); }); - child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk)); - child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk)); + child.stdout.on('data', (chunk: Buffer) => { + stdoutTotal = appendCappedOutput(stdout, stdoutTotal, chunk); + }); + child.stderr.on('data', (chunk: Buffer) => { + stderrTotal = appendCappedOutput(stderr, stderrTotal, chunk); + }); child.on('exit', (code) => { clearTimeout(timer); resolve({ @@ -273,12 +1084,14 @@ function runWsl(args: readonly string[], timeoutMs: number, input?: Buffer): Pro }); } -function fileArgs(op: string, file: string): string[] { - return ['python3', '-c', FILE_HELPER, op, assertDistroPath(file)]; +function fileArgs(op: string, file: string, limit?: number): string[] { + const args = ['python3', '-c', FILE_HELPER, op, assertDistroPath(file)]; + if (limit !== undefined) args.push(String(limit)); + return args; } -function readDistroFile(file: string): string { - const result = runWslSync(fileArgs('read', file)); +function readDistroFile(file: string, limit?: number): string { + const result = runWslSync(fileArgs('read', file, limit)); if (result.code !== 0) { throw new Error('ElastOS could not read a file in its Linux environment. Click Install to try again.'); } @@ -315,24 +1128,22 @@ export async function ensureElastosDistro(deps: { lookup: async () => true, listDistros: deps.listDistros, }); + const run = deps.runInDistro ?? ((args, timeoutMs) => runWsl(args, timeoutMs)); if (!facts.distroReady) { const rootfs = await deps.ensureRootfs(); deps.onProgress('Rootfs SHA-256 matches the pin'); (deps.prepareImportDir ?? prepareImportDir)(DISTRO_INSTALL_DIR); const code = await deps.importDistro(DISTRO_INSTALL_DIR, rootfs); if (code !== 0) throw new Error(DISTRO_IMPORT_FAILED); - // The first command can block while the rootfs finishes its first boot. - // The tool check's 20 seconds is too short for that. deps.onProgress('Starting the Linux environment for the first time'); - const run = deps.runInDistro ?? ((args, timeoutMs) => runWsl(args, timeoutMs)); - let booted: WslResult; - try { - booted = await run(['true'], DISTRO_FIRST_BOOT_MS); - } catch { - throw new Error(DISTRO_SETUP_FAILED); - } - if (booted.code !== 0) throw new Error(DISTRO_SETUP_FAILED); } + let booted: WslResult; + try { + booted = await run(['true'], DISTRO_FIRST_BOOT_MS); + } catch { + throw new Error(DISTRO_SETUP_FAILED); + } + if (booted.code !== 0) throw new Error(DISTRO_SETUP_FAILED); if (!(await deps.hasTools())) { const code = await deps.installTools(); if (code !== 0) throw new Error(DISTRO_SETUP_FAILED); @@ -416,11 +1227,21 @@ function distroInstallDeps(): RuntimeInstallDeps { export async function installRuntimeInsideDistro( onProgress: (message: string) => void = () => {}, + host: { + lookupWsl?: () => Promise; + listDistros?: () => Promise; + ensureRootfs?: () => Promise; + importDistro?: (installDir: string, rootfs: string) => Promise; + prepareImportDir?: (dir: string) => void; + runInDistro?: (args: readonly string[], timeoutMs: number) => Promise; + continueInstall?: (onProgress: (message: string) => void) => Promise; + } = {}, ): Promise { + const run = host.runInDistro ?? ((args: readonly string[], timeoutMs: number) => runWsl(args, timeoutMs)); await ensureElastosDistro({ - lookupWsl: () => lookupCommand('wsl.exe'), - listDistros, - ensureRootfs: () => ensureElastosRootfs({ + lookupWsl: host.lookupWsl ?? (() => lookupCommand('wsl.exe')), + listDistros: host.listDistros ?? listDistros, + ensureRootfs: host.ensureRootfs ?? (() => ensureElastosRootfs({ dest: path.join(os.homedir(), '.elastos-launcher', 'ubuntu-noble-wsl.rootfs.tar.gz'), exists: (file) => { try { return fs.statSync(file).isFile(); } catch { return false; } @@ -428,12 +1249,18 @@ export async function installRuntimeInsideDistro( download: downloadPinnedRootfs, read: (file) => fs.readFileSync(file), accept: assertPinnedRootfs, - }), - importDistro: (installDir, rootfs) => runHost(importDistroArgs(installDir, rootfs), 10 * 60 * 1000), - hasTools: async () => (await runWsl(distroToolCheckArgs(), 20000)).code === 0, - installTools: async () => (await runWsl(distroPackageArgs(), 10 * 60 * 1000)).code, + })), + importDistro: host.importDistro ?? ((installDir, rootfs) => runHost(importDistroArgs(installDir, rootfs), 10 * 60 * 1000)), + prepareImportDir: host.prepareImportDir, + runInDistro: run, + hasTools: async () => (await run(distroToolCheckArgs(), 20000)).code === 0, + installTools: async () => (await run(distroPackageArgs(), 10 * 60 * 1000)).code, onProgress, }); + if (host.continueInstall) { + await host.continueInstall(onProgress); + return; + } await installRuntime(distroInstallDeps(), onProgress); } @@ -459,53 +1286,47 @@ function runHost(args: readonly string[], timeoutMs: number): Promise { }); } -/** Signal the gateway recorded in the distro host lock. Never uses pid 0 or 1. */ export function signalDistroLock( signal: NodeJS.Signals, - stopInside: (name: 'TERM' | 'KILL') => void = (name) => { - const pid = readDistroLockPid(); - if (pid == null || pid <= 1) return; - runWslSync(distroStopArgs(name, pid), undefined, 5000); - }, + stopInside: (name: 'TERM' | 'KILL') => void, ): void { - const name = signal === 'SIGKILL' ? 'KILL' : 'TERM'; - stopInside(name); + stopInside(signal === 'SIGKILL' ? 'KILL' : 'TERM'); } export function signalDistroGateway( wslPid: number, signal: NodeJS.Signals, kill: (pid: number, signal: NodeJS.Signals) => void = process.kill, - stopInside: (name: 'TERM' | 'KILL') => void = (name) => { - const pid = readDistroLockPid(); - if (pid == null || pid <= 1) return; - runWslSync(distroStopArgs(name, pid), undefined, 5000); - }, + stopInside: (name: 'TERM' | 'KILL') => void = () => { throw new Error(HOME_UNCONFIRMED_MESSAGE); }, ): void { + let stopError: unknown = null; try { signalDistroLock(signal, stopInside); - } catch { - // The lock may already be gone. - } - if (!Number.isInteger(wslPid) || wslPid <= 0) return; - try { - kill(wslPid, signal); } catch (err) { - const code = err && typeof err === 'object' && 'code' in err - ? String((err as { code?: string }).code) - : ''; - if (code === 'ESRCH') return; - const message = err instanceof Error ? err.message : String(err); - throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + stopError = err; + } + if (signal === 'SIGKILL' && Number.isInteger(wslPid) && wslPid > 0) { + try { + kill(wslPid, signal); + } catch (err) { + const code = err && typeof err === 'object' && 'code' in err + ? String((err as { code?: string }).code) + : ''; + if (code !== 'ESRCH' && !stopError) { + const message = err instanceof Error ? err.message : String(err); + throw new Error(`Could not signal ElastOS (${signal}): ${message}`); + } + } + } + if (stopError) { + if (stopError instanceof Error) throw stopError; + throw new Error(HOME_UNCONFIRMED_MESSAGE); } } export function spawnDistroGatewayProcess(): GatewayProcess { - const child = spawn('wsl.exe', distroGatewayArgs(), { - windowsHide: true, - env: wslSpawnEnv(), - stdio: ['ignore', 'pipe', 'pipe'], - }); + const child = spawn('wsl.exe', distroGatewayArgs(), distroHomeSpawnOptions()); + const session = createDistroStopSession(); const outputListeners: Array<(chunk: string) => void> = []; const exitListeners: Array<(code: number | null) => void> = []; let exited = false; @@ -524,13 +1345,25 @@ export function spawnDistroGatewayProcess(): GatewayProcess { onOutput(listener) { outputListeners.push(listener); }, onExit(listener) { exitListeners.push(listener); }, hasExited() { return exited; }, - signal(signal) { signalDistroGateway(child.pid ?? -1, signal); }, + signal(signal) { + try { + signalDistroGateway(child.pid ?? -1, signal, process.kill, (name) => session.signal(name)); + } finally { + if (signal === 'SIGKILL') session.close(); + } + }, + dispose() { + session.dispose(); + }, }; } -export function createDistroGatewaySupervisor() { +export function createDistroGatewaySupervisor(lifetime: GatewayLifetime = homeGatewayLifetime) { return createGatewaySupervisor({ + lifetime, binary: '/root/.local/bin/elastos', + platform: 'win32', + args: ['home', '--browser'], spawn: () => spawnDistroGatewayProcess(), // Windows forwards localhost to the distro. Probe each address Windows // resolves localhost to, the same way the Windows browser can connect. @@ -539,6 +1372,8 @@ export function createDistroGatewaySupervisor() { now: () => Date.now(), openUrl: openRuntimeHome, log: emitRuntimeLog, + adoptForControls: true, + healthTimeoutMs: DISTRO_HOME_READY_MS, confirmForeign: confirmDistroGateway, foreignIsLegacy: async () => (await distroListenerKind()) === 'legacy', // The Windows side of the forward has no pid this launcher can check. @@ -634,45 +1469,55 @@ export async function distroListenerKind( } /** - * Adopt the installed distro gateway. The signal goes to the pid read from - * the lock, not to whatever the lock says later. hasExited asks the distro - * whether that pid is still there and treats an error as still running. - * A missing pid is not adopted, and pid 0 is never signaled. + * Adopt the installed distro Home. Stop signals only the confirmed controller. + * hasExited asks whether the lock pid is still there and treats an error as + * still running. A missing pid is not adopted. */ export function adoptDistroGatewayProcess(deps: { readPid?: () => number | null; alive?: (pid: number) => boolean | Promise; - signal?: (pid: number, signal: NodeJS.Signals) => void; - runStop?: (args: readonly string[]) => void; + stop?: (name: 'TERM' | 'KILL') => void; + root?: string; + spawn?: (args: readonly string[]) => ChildProcess; } = {}): GatewayProcess | null { const readPid = deps.readPid ?? (() => readDistroLockPid()); const alive = deps.alive ?? ((pid: number) => distroPidAlive(pid)); - const signalInside = deps.signal ?? ((pid: number, signal: NodeJS.Signals) => { - if (!Number.isInteger(pid) || pid <= 1) return; - const name = signal === 'SIGKILL' ? 'KILL' : 'TERM'; - const run = deps.runStop ?? ((args: readonly string[]) => { - runWslSync(args, undefined, 5000); - }); - run(distroStopArgs(name, pid)); + let session: DistroStopSession | null = null; + const stop = deps.stop ?? ((name: 'TERM' | 'KILL') => { + if (!session) session = createDistroStopSession({ root: deps.root, spawn: deps.spawn }); + session.signal(name); }); const pid = readPid(); if (pid == null || pid <= 1) return null; + const gone = (): boolean | Promise => { + try { + const result = alive(pid); + if (result && typeof (result as Promise).then === 'function') { + return (result as Promise).then((still) => still === false).catch(() => false); + } + return result === false; + } catch { + return false; + } + }; return { pid, onOutput() {}, onExit() {}, hasExited() { + return gone(); + }, + signal(signal) { + const name = signal === 'SIGKILL' ? 'KILL' : 'TERM'; try { - const result = alive(pid); - if (result && typeof (result as Promise).then === 'function') { - return (result as Promise).then((still) => still === false).catch(() => false); - } - return result === false; - } catch { - return false; + stop(name); + } finally { + if (name === 'KILL') session?.close(); } }, - signal(signal) { signalInside(pid, signal); }, + dispose() { + session?.dispose(); + }, }; } @@ -689,7 +1534,9 @@ export async function adoptInstalledDistroGateway(deps: { adopt?: (pid: number) => GatewayProcess | null; } = {}): Promise { const identify = deps.identify ?? (() => distroListenerIdentity()); - const adopt = deps.adopt ?? ((pid: number) => adoptDistroGatewayProcess({ readPid: () => pid })); + const adopt = deps.adopt ?? ((pid: number) => adoptDistroGatewayProcess({ + readPid: () => pid, + })); let seen: DistroListenerIdentity; try { seen = await identify(); diff --git a/src/main/targets/windowsUninstall.ts b/src/main/targets/windowsUninstall.ts index 3cd7a97..e8ceb52 100644 --- a/src/main/targets/windowsUninstall.ts +++ b/src/main/targets/windowsUninstall.ts @@ -27,6 +27,7 @@ import { inspectDistro, launcherHostFiles, removeLauncherHostFiles, + removeInDistro, RestrictToOwner, windowsRestrictToOwner, wslHelperRun, @@ -552,3 +553,32 @@ export async function uninstallRuntimeInDistroOnThisComputer( removeHost: (target) => removeVerifiedTarget(target), }); } + +/** Program-only uninstall keeps the existing Home and the Linux environment in place. */ +export async function uninstallDistroProgram(deps: { + stop: () => Promise; + inspect: () => Promise; + paths: DistroResetPaths; + maintainerDid: string | null; + removeProgram: (plan: ReturnType) => Promise; +}): Promise { + const before = await deps.inspect(); + const plan = distroRemovalPlan(before, deps.paths, deps.maintainerDid, 'uninstall'); + if (before.data === 'dir') assertDistroIsElastos(before, deps.paths, deps.maintainerDid); + await deps.stop(); + const after = await deps.inspect(); + const fresh = distroRemovalPlan(after, deps.paths, deps.maintainerDid, 'uninstall'); + if (JSON.stringify(fresh) !== JSON.stringify(plan)) throw new Error('ElastOS changed before uninstall. Nothing was removed.'); + await deps.removeProgram(fresh); +} + +export async function uninstallDistroProgramOnThisComputer(stop: () => Promise): Promise { + const paths = distroResetPaths(); + const run = wslHelperRun(); + await uninstallDistroProgram({ stop, paths, maintainerDid: pinnedMaintainerDid(), + inspect: () => inspectDistro(run, paths, 'uninstall'), + removeProgram: plan => removeInDistro(run, paths, plan, true), + }); + const hostFiles = launcherHostFiles(os.homedir(), process.platform, process.env); + removeLauncherHostFiles(hostFiles, { removeHost: target => removeVerifiedTarget(target) }); +} diff --git a/src/native/linux-pidfd.c b/src/native/linux-pidfd.c new file mode 100644 index 0000000..f77180e --- /dev/null +++ b/src/native/linux-pidfd.c @@ -0,0 +1,125 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __NR_pidfd_open +#define __NR_pidfd_open 434 +#endif +#ifndef __NR_pidfd_send_signal +#define __NR_pidfd_send_signal 424 +#endif + +static int write_text(int fd, const char *text) { + size_t len = strlen(text); + size_t off = 0; + while (off < len) { + ssize_t n = write(fd, text + off, len - off); + if (n < 0) { + if (errno == EINTR) continue; + return -1; + } + off += (size_t)n; + } + return 0; +} + +static const char *errno_name(int err) { + switch (err) { + case ESRCH: return "ESRCH"; + case ENOSYS: return "ENOSYS"; + case EPERM: return "EPERM"; + case EINVAL: return "EINVAL"; + case EBADF: return "EBADF"; + default: return "EIO"; + } +} + +static void report(int reply, int err) { + char line[32]; + int n = snprintf(line, sizeof line, "errno %s\n", errno_name(err)); + if (n > 0 && (size_t)n < sizeof line) write_text(reply, line); +} + +static int read_line(int fd, char *buf, size_t cap) { + size_t n = 0; + while (n + 1 < cap) { + char c = 0; + ssize_t r = read(fd, &c, 1); + if (r < 0) { + if (errno == EINTR) continue; + return -1; + } + if (r == 0) return -1; + buf[n++] = c; + if (c == '\n') { + buf[n] = '\0'; + return 0; + } + } + return -1; +} + +int main(int argc, char **argv) { + char *end = NULL; + long pid; + int reply; + int fd; + int cmd; + char line[32]; + if (argc != 4) return 2; + prctl(PR_SET_PDEATHSIG, SIGKILL); + if (getppid() == 1) return 2; + alarm(2); + errno = 0; + pid = strtol(argv[1], &end, 10); + if (errno || !argv[1][0] || (end && *end) || pid <= 0 || pid > 0x7fffffff) return 2; + reply = open(argv[2], O_WRONLY | O_CLOEXEC | O_NOFOLLOW); + if (reply < 0) return 2; + fd = (int)syscall(__NR_pidfd_open, (int)pid, 0); + if (fd < 0) { + report(reply, errno); + close(reply); + return 1; + } + if (write_text(reply, "ready\n") != 0) { + close(fd); + close(reply); + return 1; + } + cmd = open(argv[3], O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + alarm(0); + if (cmd < 0) { + report(reply, errno); + close(fd); + close(reply); + return 1; + } + while (read_line(cmd, line, sizeof line) == 0) { + int sig = 0; + if (strcmp(line, "close\n") == 0) { + close(fd); + close(cmd); + close(reply); + return 0; + } + if (strcmp(line, "SIGTERM\n") == 0) sig = SIGTERM; + else if (strcmp(line, "SIGKILL\n") == 0) sig = SIGKILL; + else { + report(reply, EINVAL); + continue; + } + if (syscall(__NR_pidfd_send_signal, fd, sig, NULL, 0) != 0) report(reply, errno); + else write_text(reply, "sent\n"); + } + close(fd); + close(cmd); + close(reply); + return 0; +} diff --git a/src/native/mac-process-info.c b/src/native/mac-process-info.c new file mode 100644 index 0000000..0bb4863 --- /dev/null +++ b/src/native/mac-process-info.c @@ -0,0 +1,24 @@ +#include +#include +#include +#include +#include + +/* Read the kernel executable path between two birth-time observations. */ +int main(int argc, char **argv) { + if (argc != 2) return 1; + char *end; + errno = 0; + long pid = strtol(argv[1], &end, 10); + if (errno || !*argv[1] || *end || pid <= 0 || pid > INT_MAX) return 1; + struct proc_bsdinfo before, after; + char executable[PROC_PIDPATHINFO_MAXSIZE]; + if (proc_pidinfo((int)pid, PROC_PIDTBSDINFO, 0, &before, sizeof(before)) != sizeof(before) + || proc_pidpath((int)pid, executable, sizeof(executable)) <= 0 + || proc_pidinfo((int)pid, PROC_PIDTBSDINFO, 0, &after, sizeof(after)) != sizeof(after) + || before.pbi_start_tvsec != after.pbi_start_tvsec + || before.pbi_start_tvusec != after.pbi_start_tvusec) return 1; + printf("%llu.%06llu\n%s", (unsigned long long)after.pbi_start_tvsec, + (unsigned long long)after.pbi_start_tvusec, executable); + return 0; +} diff --git a/src/preload/index.ts b/src/preload/index.ts index 15cc82a..373da87 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,127 +1,20 @@ import { contextBridge, ipcRenderer } from 'electron'; -export type RuntimeStatus = 'running' | 'stopped' | 'starting' | 'stopping' | 'error' | 'not-installed'; - +// Maintenance stays in the native menu. The renderer can only act on its current dialog. contextBridge.exposeInMainWorld('elastos', { - start: () => ipcRenderer.invoke('elastos:start'), - stop: () => ipcRenderer.invoke('elastos:stop'), - restart: () => ipcRenderer.invoke('elastos:restart'), - openBrowser: () => ipcRenderer.invoke('elastos:openBrowser'), - install: () => ipcRenderer.invoke('elastos:install'), - uninstall: () => ipcRenderer.invoke('elastos:uninstall'), - resetRuntime: (choice: { backup?: unknown }) => ipcRenderer.invoke('elastos:resetRuntime', { - backup: choice && (choice.backup === true || choice.backup === false) ? choice.backup : undefined, - }), - describeResetBackup: () => ipcRenderer.invoke('elastos:describeResetBackup'), - - getStatus: () => ipcRenderer.invoke('elastos:getStatus'), - getLogs: (lines: number) => ipcRenderer.invoke('elastos:getLogs', lines), - isInstalled: () => ipcRenderer.invoke('elastos:isInstalled'), - - getVersion: () => ipcRenderer.invoke('elastos:getVersion'), - checkForUpdate: () => ipcRenderer.invoke('elastos:checkForUpdate'), + platform: process.platform, + contentSize: (height: number) => ipcRenderer.send('elastos:contentSize', height), + getWindowState: () => ipcRenderer.invoke('elastos:getWindowState'), + install: (login: boolean) => ipcRenderer.invoke('elastos:install', login === true), update: () => ipcRenderer.invoke('elastos:update'), - rollback: () => ipcRenderer.invoke('elastos:rollback'), - getLaunchInfo: () => ipcRenderer.invoke('elastos:getLaunchInfo'), - getPreflight: () => ipcRenderer.invoke('elastos:getPreflight'), - getDiagnostics: () => ipcRenderer.invoke('elastos:getDiagnostics'), - saveSupportBundle: () => ipcRenderer.invoke('elastos:saveSupportBundle'), - describeLegacyPc2: () => ipcRenderer.invoke('elastos:describeLegacyPc2'), - removeLegacyPc2: (backup: boolean, paths: readonly string[]) => ipcRenderer.invoke( - 'elastos:removeLegacyPc2', - backup === true, - Array.isArray(paths) ? paths.filter((entry) => typeof entry === 'string') : [], - ), - describeFailure: () => ipcRenderer.invoke('elastos:describeFailure'), - fixFailure: () => ipcRenderer.invoke('elastos:fixFailure'), - resumeInstallPlan: () => ipcRenderer.invoke('elastos:resumeInstallPlan'), - finishResumeInstall: (ok: boolean) => ipcRenderer.invoke('elastos:finishResumeInstall', ok === true), - setOpenAtLogin: (enabled: boolean) => ipcRenderer.invoke('elastos:setOpenAtLogin', enabled), - - onStatus: (callback: (status: RuntimeStatus) => void) => { - const listener = (_event: Electron.IpcRendererEvent, status: RuntimeStatus) => callback(status); - ipcRenderer.on('elastos:status', listener); - return () => ipcRenderer.removeListener('elastos:status', listener); - }, - - onLog: (callback: (log: string) => void) => { - const listener = (_event: Electron.IpcRendererEvent, log: string) => callback(log); - ipcRenderer.on('elastos:log', listener); - return () => ipcRenderer.removeListener('elastos:log', listener); - }, - - onInstallProgress: (callback: (message: string) => void) => { - const listener = (_event: Electron.IpcRendererEvent, message: string) => callback(message); - ipcRenderer.on('elastos:installProgress', listener); - return () => ipcRenderer.removeListener('elastos:installProgress', listener); + retry: () => ipcRenderer.invoke('elastos:retry'), + openHome: () => ipcRenderer.invoke('elastos:openHome'), + copyDiagnostics: () => ipcRenderer.invoke('elastos:copyDiagnostics'), + releaseNotes: () => ipcRenderer.invoke('elastos:releaseNotes'), + closeWindow: () => ipcRenderer.invoke('elastos:closeWindow'), + onWindowState: (callback: (state: unknown) => void) => { + const listener = (_event: Electron.IpcRendererEvent, state: unknown) => callback(state); + ipcRenderer.on('elastos:windowState', listener); + return () => ipcRenderer.removeListener('elastos:windowState', listener); }, - - onUpdateProgress: (callback: (message: string) => void) => { - const listener = (_event: Electron.IpcRendererEvent, message: string) => callback(message); - ipcRenderer.on('elastos:updateProgress', listener); - return () => ipcRenderer.removeListener('elastos:updateProgress', listener); - } }); - -declare global { - interface Window { - elastos: { - start: () => Promise; - stop: () => Promise; - restart: () => Promise; - openBrowser: () => void; - install: () => Promise; - uninstall: () => Promise<{ linuxCopyPath: string | null; linuxCopyMessage: string | null; restoreHint: string | null; removedLinux: boolean } | void>; - resetRuntime: (choice: { backup: boolean }) => Promise<{ backupPath: string | null }>; - describeResetBackup: () => Promise<{ - present: boolean; - bytes: number; - neededBytes: number; - freeBytes: number | null; - enough: boolean; - folder: string; - }>; - getStatus: () => Promise; - getLogs: (lines: number) => Promise; - isInstalled: () => Promise; - getVersion: () => Promise; - checkForUpdate: () => Promise<{ current: string; latest: string; updateAvailable: boolean; releaseUrl: string }>; - update: () => Promise; - rollback: () => Promise; - getLaunchInfo: () => Promise<{ - id: string; - displayName: string; - openUrl: string; - status: RuntimeStatus; - platformNote: string | null; - browserNote: string | null; - uninstallRemovesLinux: boolean; - preflight: { ok: boolean; checks: Array<{ id: string; level: string; message: string }> }; - openAtLogin: boolean; - canRollback: boolean; - }>; - getPreflight: () => Promise<{ ok: boolean; checks: Array<{ id: string; level: string; message: string }> }>; - getDiagnostics: () => Promise; - saveSupportBundle: () => Promise; - describeLegacyPc2: () => Promise<{ - items: Array<{ scope: string; path: string; label: string; bytes: number | null }>; - }>; - removeLegacyPc2: (backup: boolean, paths: string[]) => Promise<{ ok: boolean; message: string }>; - describeFailure: () => Promise<{ - kind: string; - title: string; - message: string; - retryLabel: string; - fixLabel: string | null; - }>; - fixFailure: () => Promise<'ready' | 'still-blocked'>; - resumeInstallPlan: () => Promise<'install' | 'wait' | 'none'>; - finishResumeInstall: (ok: boolean) => Promise; - setOpenAtLogin: (enabled: boolean) => Promise; - onStatus: (callback: (status: RuntimeStatus) => void) => () => void; - onLog: (callback: (log: string) => void) => () => void; - onInstallProgress: (callback: (message: string) => void) => () => void; - onUpdateProgress: (callback: (message: string) => void) => () => void; - }; - } -} diff --git a/src/renderer/app.js b/src/renderer/app.js index 2e7bd2f..80eea32 100644 --- a/src/renderer/app.js +++ b/src/renderer/app.js @@ -1,572 +1,46 @@ -const statusLed = document.getElementById('status-led'); -const statusText = document.getElementById('status-text'); -const powerBtn = document.getElementById('power-btn'); -const openBtn = document.getElementById('open-btn'); -const openLabel = document.getElementById('open-label'); -const logsBtn = document.getElementById('logs-btn'); -const uninstallBtn = document.getElementById('uninstall-btn'); -const resetBtn = document.getElementById('reset-btn'); -const logsPanel = document.getElementById('logs-panel'); -const logsContent = document.getElementById('logs-content'); -const closeLogsBtn = document.getElementById('close-logs'); -const confirmModal = document.getElementById('confirm-modal'); -const confirmTitle = document.getElementById('confirm-title'); -const confirmBody = document.getElementById('confirm-body'); -const confirmPath = document.getElementById('confirm-path'); -const confirmCancel = document.getElementById('confirm-cancel'); -const confirmDelete = document.getElementById('confirm-delete'); -const copyLogsBtn = document.getElementById('copy-logs'); -const versionEl = document.getElementById('version'); -const updateBtn = document.getElementById('update-btn'); -const updateBtnLabel = document.getElementById('update-btn-label'); -const rollbackBtn = document.getElementById('rollback-btn'); -const firstRun = document.getElementById('first-run'); -const platformNote = document.getElementById('platform-note'); -const stepsEl = document.getElementById('steps'); -const errorBox = document.getElementById('error-box'); -const errorTitle = document.getElementById('error-title'); -const errorText = document.getElementById('error-text'); -const retryBtn = document.getElementById('retry-btn'); -const fixBtn = document.getElementById('fix-btn'); -const diagnosticsBtn = document.getElementById('diagnostics-btn'); -const supportBtn = document.getElementById('support-btn'); -const loginCheckbox = document.getElementById('login-checkbox'); -const urlValue = document.getElementById('url-value'); -const removePc2Btn = document.getElementById('remove-pc2-btn'); -const confirmBackupRow = document.getElementById('confirm-backup-row'); -const confirmBackup = document.getElementById('confirm-backup'); -const resetBackup = document.getElementById('reset-backup'); -const resetBackupText = document.getElementById('reset-backup-text'); -const resetBackupWarning = document.getElementById('reset-backup-warning'); -const resetBackupYes = document.getElementById('reset-backup-yes'); -const resetBackupNo = document.getElementById('reset-backup-no'); -const resetBackupYesLabel = document.getElementById('reset-backup-yes-label'); -const resetBackupNoLabel = document.getElementById('reset-backup-no-label'); -const resetBackupSpace = document.getElementById('reset-backup-space'); -const browserRow = document.getElementById('browser-row'); -const browserNote = document.getElementById('browser-note'); - -let currentStatus = 'stopped'; -let confirmMode = 'uninstall'; -let legacyItems = []; -let legacyConfirmPaths = []; -let pc2Busy = false; -let resetOffer = null; -/** Windows: Uninstall removes the ElastOS Linux environment after it saves it (launch info). */ -let uninstallRemovesLinux = false; -let targetId = 'runtime'; -// The main process sends the Home address (src/main/targets/gatewayAddress.ts). -let openUrl = ''; -let busy = false; -let isUpdating = false; -let logs = []; -const MAX_LOGS = 200; -const flow = window.elastosFlow; - -const statusLabels = { - running: 'Running', - stopped: 'Stopped', - starting: 'Starting...', - stopping: 'Stopping...', - error: 'Needs attention', - 'not-installed': 'Not installed' -}; - -async function showError(message) { - errorTitle.textContent = 'ElastOS needs attention'; - errorText.textContent = message; - errorBox.classList.remove('hidden'); - fixBtn.classList.add('hidden'); - addLog(message); - try { - const screen = await window.elastos.describeFailure(); - if (!screen || !screen.title) return; - errorTitle.textContent = screen.title; - errorText.textContent = screen.message; - fixBtn.classList.toggle('hidden', !screen.fixLabel); - if (screen.fixLabel) fixBtn.textContent = screen.fixLabel; - } catch { - fixBtn.classList.add('hidden'); - } -} - -function hidePc2Backup() { - confirmBackupRow.classList.add('hidden'); - confirmBackup.checked = false; -} - -function hideResetBackup() { - resetOffer = null; - resetBackup.classList.add('hidden'); - resetBackupYes.checked = false; - resetBackupNo.checked = false; - confirmDelete.disabled = false; -} - -/** Reset stays off until the person answers the backup offer. Only Reset offers it. */ -function syncResetButton() { - if (confirmMode !== 'reset') return; - if (!resetOffer) { - confirmDelete.disabled = true; - return; - } - confirmDelete.disabled = Boolean(resetOffer.blocked) - || (resetOffer.needsChoice && !resetBackupYes.checked && !resetBackupNo.checked); -} - -function showResetBackup(description) { - const copy = flow.resetBackupCopy(description); - resetOffer = copy; - resetBackupText.textContent = copy.text; - resetBackupWarning.textContent = copy.canSave ? copy.warning : ''; - resetBackupYesLabel.textContent = copy.yes; - resetBackupNoLabel.textContent = copy.no; - resetBackupYes.checked = false; - resetBackupNo.checked = false; - resetBackupYes.disabled = !copy.canSave; - resetBackupYes.parentElement.classList.toggle('hidden', !copy.needsChoice); - resetBackupNo.parentElement.classList.toggle('hidden', !copy.needsChoice); - resetBackupSpace.textContent = copy.space; - resetBackupSpace.classList.toggle('hidden', !copy.space); - resetBackup.classList.remove('hidden'); - syncResetButton(); -} - -function showLegacyPc2(items) { - legacyItems = Array.isArray(items) ? items : []; - removePc2Btn.classList.toggle('hidden', legacyItems.length === 0); -} - -async function refreshLegacyPc2() { - try { - const found = await window.elastos.describeLegacyPc2(); - showLegacyPc2(found && found.items); - } catch { - showLegacyPc2([]); - } -} - -function clearError() { - errorBox.classList.add('hidden'); - errorText.textContent = ''; - fixBtn.classList.add('hidden'); -} - -function renderSteps(message) { - const states = flow.stepStates(message || ''); - stepsEl.classList.remove('hidden'); - stepsEl.innerHTML = ''; - for (const step of states) { - const item = document.createElement('li'); - item.className = step.state; - const mark = step.state === 'done' ? 'Done' : step.state === 'active' ? 'Now' : 'Next'; - item.textContent = `${mark} — ${step.label} (${step.estimate})`; - stepsEl.appendChild(item); - } -} - -function updateStatus(status) { - currentStatus = status; - statusLed.className = 'led ' + status; - statusText.textContent = statusLabels[status] || status; - - const action = flow.primaryAction({ targetId, status, busy }); - openLabel.textContent = action.label; - openBtn.disabled = !action.enabled; - openBtn.dataset.action = action.id; - - powerBtn.className = 'power-button' + (status === 'running' ? ' running' : ''); - powerBtn.disabled = busy || status === 'starting' || status === 'stopping' || status === 'not-installed'; - - const isInstalled = status !== 'not-installed'; - uninstallBtn.disabled = !isInstalled || status === 'running' || busy; - - firstRun.textContent = flow.firstRunCopy(targetId, status); - urlValue.textContent = flow.urlLabel(openUrl) || '...'; - if (status !== 'error') { - // Keep a visible error until the next successful action. - } -} - -function addLog(message) { - logs.push(message); - if (logs.length > MAX_LOGS) logs.shift(); - logsContent.textContent = logs.join('\n'); - logsContent.scrollTop = logsContent.scrollHeight; -} - -async function runInstall() { - clearError(); - busy = true; - updateStatus(currentStatus); - try { - const preflight = await window.elastos.getPreflight(); - const blocked = (preflight.checks || []).filter((check) => check.level === 'block'); - const warnings = (preflight.checks || []).filter((check) => check.level === 'warn'); - if (warnings.length) { - platformNote.textContent = warnings.map((check) => check.message).join(' '); - platformNote.classList.remove('hidden'); - } - if (!preflight.ok) { - showError(blocked.map((check) => check.message).join(' ')); - return; - } - renderSteps('Checking this computer'); - await window.elastos.install(); - renderSteps('Starting'); - await window.elastos.start(); - renderSteps('Your computer is ready'); - await window.elastos.openBrowser(); - } catch (err) { - showError(err && err.message ? err.message : 'Something went wrong. Try again.'); - updateStatus('error'); - } finally { - busy = false; - const status = await window.elastos.getStatus().catch(() => currentStatus); - updateStatus(status); - } -} - -openBtn.addEventListener('click', async () => { - const action = openBtn.dataset.action; - if (action === 'install' || action === 'retry') { - await runInstall(); - return; - } - if (action === 'open') { - window.elastos.openBrowser(); - return; - } - if (action === 'start') { - try { - await window.elastos.start(); - } catch (err) { - showError(err.message); - } - } -}); - -retryBtn.addEventListener('click', () => runInstall()); - -fixBtn.addEventListener('click', async () => { - fixBtn.disabled = true; - try { - const result = await window.elastos.fixFailure(); - if (result === 'ready') { - clearError(); - await runInstall(); - return; - } - await showError('That still needs attention.'); - } catch (err) { - await showError(err && err.message ? err.message : 'Fix it did not finish.'); - } finally { - fixBtn.disabled = false; - } -}); - -diagnosticsBtn.addEventListener('click', async () => { - const text = await window.elastos.getDiagnostics(); - try { - await navigator.clipboard.writeText(text); - diagnosticsBtn.textContent = 'Copied'; - setTimeout(() => { diagnosticsBtn.textContent = 'Copy diagnostics'; }, 2000); - } catch (err) { - addLog('Could not copy diagnostics.'); - } -}); - -supportBtn.addEventListener('click', async () => { - try { - await window.elastos.saveSupportBundle(); - supportBtn.textContent = 'Saved'; - addLog('Saved ElastOS-support.txt on the Desktop, or in the home folder if there is no Desktop.'); - setTimeout(() => { supportBtn.textContent = 'Save support bundle'; }, 2000); - } catch (err) { - showError(err && err.message ? err.message : 'Could not save the support bundle.'); - } -}); - -powerBtn.addEventListener('click', async () => { - try { - if (currentStatus === 'running') await window.elastos.stop(); - else if (currentStatus === 'stopped' || currentStatus === 'error') await window.elastos.start(); - } catch (err) { - showError(err.message); - } -}); - -logsBtn.addEventListener('click', async () => { - if (logsPanel.classList.contains('hidden')) { - const logText = await window.elastos.getLogs(100); - logs = logText.split('\n').filter((line) => line.trim()); - logsContent.textContent = logs.join('\n'); - logsContent.scrollTop = logsContent.scrollHeight; - logsPanel.classList.remove('hidden'); - } else { - logsPanel.classList.add('hidden'); - } -}); - -closeLogsBtn.addEventListener('click', () => logsPanel.classList.add('hidden')); - -copyLogsBtn.addEventListener('click', async () => { - try { - await navigator.clipboard.writeText(logsContent.textContent); - copyLogsBtn.classList.add('copied'); - setTimeout(() => copyLogsBtn.classList.remove('copied'), 2000); - } catch (err) { - console.error('Failed to copy:', err); - } -}); - -resetBtn.addEventListener('click', async () => { - const copy = flow.resetCopy(); - confirmMode = 'reset'; - hidePc2Backup(); - hideResetBackup(); - confirmTitle.textContent = copy.title; - confirmBody.textContent = copy.body; - confirmPath.textContent = 'The ElastOS program and its data folder'; - confirmDelete.textContent = 'Reset'; - confirmModal.classList.remove('hidden'); - await loadBackupOffer('reset'); -}); - -/** Show "Checking the size", then the offer. Nothing can be confirmed until it is answered. */ -async function loadBackupOffer(mode) { - resetBackupText.textContent = 'Checking the size of your ElastOS data...'; - resetBackupWarning.textContent = ''; - resetBackupSpace.classList.add('hidden'); - resetBackupYes.parentElement.classList.add('hidden'); - resetBackupNo.parentElement.classList.add('hidden'); - resetBackup.classList.remove('hidden'); - confirmDelete.disabled = true; - let description = null; - try { - description = await window.elastos.describeResetBackup(); - } catch { - description = null; - } - if (confirmMode !== mode || confirmModal.classList.contains('hidden')) return; - showResetBackup(description); -} - -resetBackupYes.addEventListener('change', syncResetButton); -resetBackupNo.addEventListener('change', syncResetButton); - -uninstallBtn.addEventListener('click', async () => { - confirmMode = 'uninstall'; - hidePc2Backup(); - hideResetBackup(); - confirmDelete.textContent = uninstallRemovesLinux ? 'Uninstall' : 'Delete'; - const copy = flow.confirmCopy(targetId, [], uninstallRemovesLinux); - confirmTitle.textContent = copy.title; - confirmBody.textContent = copy.body; - confirmPath.textContent = uninstallRemovesLinux - ? 'The Linux environment named ElastOS, with everything in it' - : 'The ElastOS program and its data folder'; - confirmModal.classList.remove('hidden'); -}); - -removePc2Btn.addEventListener('click', () => { - if (!legacyItems.length || pc2Busy) return; - legacyConfirmPaths = legacyItems.map((entry) => String(entry.path)); - const copy = flow.legacyPc2Copy(legacyItems); - confirmMode = 'pc2'; - hideResetBackup(); - confirmTitle.textContent = copy.title; - confirmBody.textContent = copy.body; - confirmPath.textContent = copy.list; - confirmDelete.textContent = copy.confirm; - const canBackup = legacyItems.some((entry) => entry.scope === 'distro' || String(entry.path).endsWith('/.pc2') || String(entry.path).endsWith('\\.pc2')); - confirmBackupRow.classList.toggle('hidden', !canBackup); - confirmBackup.checked = false; - confirmModal.classList.remove('hidden'); -}); - -confirmCancel.addEventListener('click', () => { - confirmModal.classList.add('hidden'); - hideResetBackup(); -}); - -confirmDelete.addEventListener('click', async () => { - let resetChoice = null; - if (confirmMode === 'reset') { - // No answer to the backup offer means no Reset. - if (!resetOffer || resetOffer.blocked) return; - if (resetOffer.needsChoice && !resetBackupYes.checked && !resetBackupNo.checked) return; - resetChoice = { backup: Boolean(resetOffer.canSave && resetBackupYes.checked) }; - } - confirmModal.classList.add('hidden'); - if (confirmMode === 'pc2') { - if (pc2Busy) return; - const backup = confirmBackup.checked; - const paths = legacyConfirmPaths.slice(); - hidePc2Backup(); - pc2Busy = true; - statusText.textContent = 'Removing PC2...'; - try { - const result = await window.elastos.removeLegacyPc2(backup, paths); - addLog(result && result.message ? result.message : 'PC2 removed'); - clearError(); - } catch (err) { - showError(err && err.message ? err.message : 'PC2 could not be removed.'); - } finally { - pc2Busy = false; - } - await refreshLegacyPc2(); - updateStatus(currentStatus); - return; - } - const resetting = confirmMode === 'reset'; - const saving = Boolean(resetChoice && resetChoice.backup); - statusText.textContent = resetting - ? (saving ? 'Saving a copy of your data, then resetting...' : 'Resetting...') - : (uninstallRemovesLinux ? 'Saving the whole Linux environment, then removing it...' : 'Removing...'); - hideResetBackup(); - try { - if (resetting) { - const result = await window.elastos.resetRuntime(resetChoice); - if (result && result.backupPath) addLog(`A copy of your ElastOS data is in ${result.backupPath}. Keep it private.`); - addLog('ElastOS was reset. Click Install to set it up again.'); - } else { - const result = await window.elastos.uninstall(); - if (result && result.linuxCopyMessage) addLog(result.linuxCopyMessage); - addLog(result && result.removedLinux ? 'ElastOS was removed, with its Linux environment.' : 'ElastOS was removed.'); - } - stepsEl.classList.add('hidden'); - clearError(); - } catch (err) { - showError(err.message); - } -}); - -confirmModal.addEventListener('click', (event) => { - if (event.target === confirmModal) confirmModal.classList.add('hidden'); -}); - -loginCheckbox.addEventListener('change', async () => { - await window.elastos.setOpenAtLogin(loginCheckbox.checked); -}); - -window.elastos.onStatus((status) => updateStatus(status)); -window.elastos.onLog((log) => addLog(log)); -window.elastos.onInstallProgress((message) => { - statusText.textContent = message; - renderSteps(message); - addLog(message); -}); -window.elastos.onUpdateProgress((message) => { - statusText.textContent = message; - addLog(message); -}); - -async function refreshVersion() { - try { - const version = await window.elastos.getVersion(); - versionEl.textContent = !version || version === 'not installed' || /not supported/i.test(version) - ? '—' - : (version.startsWith('v') || version.startsWith('ElastOS') ? version : `v${version}`); - } catch { - versionEl.textContent = '—'; - } -} - -async function checkForUpdate() { - try { - const result = await window.elastos.checkForUpdate(); - if (result.updateAvailable) { - updateBtn.classList.remove('hidden'); - updateBtnLabel.textContent = result.latest && result.latest !== 'a newer release' - ? `Update to ${result.latest}` - : 'Update'; - } else { - updateBtn.classList.add('hidden'); - } - } catch { - updateBtn.classList.add('hidden'); - } -} - -rollbackBtn.addEventListener('click', async () => { - try { - await window.elastos.rollback(); - addLog('Restored the previous ElastOS release. Start it again to open your computer.'); - } catch (err) { - showError(err.message); - } -}); - -updateBtn.addEventListener('click', async () => { - if (isUpdating) return; - isUpdating = true; - updateBtn.disabled = true; - updateBtnLabel.textContent = 'Updating...'; - try { - await window.elastos.update(); - await refreshVersion(); - updateBtn.classList.add('hidden'); - } catch (err) { - showError(err.message); - updateBtnLabel.textContent = 'Retry'; - updateBtn.disabled = false; - } finally { - isUpdating = false; - } -}); - -async function refreshLaunch() { - const info = await window.elastos.getLaunchInfo(); - targetId = 'runtime'; - openUrl = info.openUrl; - uninstallRemovesLinux = Boolean(info.uninstallRemovesLinux); - if (rollbackBtn) rollbackBtn.classList.toggle('hidden', !info.canRollback); - loginCheckbox.checked = Boolean(info.openAtLogin); - const browserText = flow.browserNoteText(info); - browserNote.textContent = browserText; - browserRow.classList.toggle('hidden', !browserText); - const blocks = (info.preflight.checks || []).filter((check) => check.level === 'block' || check.level === 'warn'); - if (info.platformNote || blocks.length) { - platformNote.textContent = info.platformNote || blocks.map((check) => check.message).join(' '); - platformNote.classList.remove('hidden'); - } else { - platformNote.classList.add('hidden'); - } - updateStatus(info.status || await window.elastos.getStatus()); - await refreshVersion(); - checkForUpdate(); - await refreshLegacyPc2(); -} - -async function maybeResumeInstall() { - if (busy) return; - try { - const plan = await window.elastos.resumeInstallPlan(); - if (plan !== 'install' || busy) return; - await runInstall(); - const status = await window.elastos.getStatus().catch(() => 'error'); - if (typeof window.elastos.finishResumeInstall === 'function') { - await window.elastos.finishResumeInstall(status === 'running'); - } - } catch (err) { - console.error('Resume error:', err); - if (typeof window.elastos.finishResumeInstall === 'function') { - await window.elastos.finishResumeInstall(false).catch(() => {}); - } - } -} - -async function init() { - try { - await refreshLaunch(); - } catch (err) { - console.error('Init error:', err); - updateStatus('error'); - showError('Could not read this computer. Quit ElastOS and open it again.'); - return; - } - await maybeResumeInstall(); -} - -init(); +const api = window.elastos; +const $ = id => document.getElementById(id); +let state; +function render(next) { + state = next; + document.body.dataset.state = state.kind; + $('message').hidden = !state.message; + $('message').textContent = state.message || ''; + $('login-row').hidden = state.kind !== 'install' || state.ready; + $('location').hidden = !state.ready; + $('location').textContent = api.platform === 'darwin' ? '↑ ElastOS is in the menu bar.' + : api.platform === 'win32' ? "ElastOS is in the system tray. If you don't see it, click ^ next to the clock." + : 'ElastOS is in the top bar.'; + $('release-notes').hidden = state.kind !== 'update' || !state.releaseNotes; + $('progress').hidden = state.kind !== 'progress'; + $('actions').hidden = state.kind === 'progress'; + $('cancel').hidden = state.kind !== 'update'; + $('diagnostics').hidden = state.kind !== 'error'; + $('primary').textContent = state.kind === 'update' ? 'Update' : state.kind === 'error' ? state.actionLabel + : state.ready ? 'Open Home' : 'Install'; + if (state.kind !== 'progress') $('primary').focus(); +} +$('primary').addEventListener('click', async () => { + $('primary').disabled = true; + try { + if (state.kind === 'install' && !state.ready) await api.install($('login').checked); + else if (state.kind === 'update') await api.update(); + else if (state.kind === 'error') await api.retry(); + else await api.openHome(); + } finally { $('primary').disabled = false; } +}); +$('cancel').addEventListener('click', () => api.closeWindow()); +$('release-notes').addEventListener('click', event => { event.preventDefault(); api.releaseNotes(); }); +$('diagnostics').addEventListener('click', async () => { + await api.copyDiagnostics(); + $('diagnostics').textContent = 'Copied'; + setTimeout(() => { $('diagnostics').textContent = 'Copy Diagnostics'; }, 2000); +}); +document.addEventListener('keydown', event => { + if (event.key === 'Escape') api.closeWindow(); + if (event.key === 'Enter' && !['BUTTON', 'A'].includes(document.activeElement.tagName) && state.kind !== 'progress') $('primary').click(); +}); +api.onWindowState(render); +api.getWindowState().then(render); +new ResizeObserver(() => api.contentSize(Math.ceil($('window-content').getBoundingClientRect().height))) + .observe($('window-content')); diff --git a/src/renderer/elacity-labs-logo.svg b/src/renderer/elacity-labs-logo.svg deleted file mode 100644 index ba6b5e2..0000000 --- a/src/renderer/elacity-labs-logo.svg +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/renderer/elastos-logo.svg b/src/renderer/elastos-logo.svg deleted file mode 100644 index 581d9d3..0000000 --- a/src/renderer/elastos-logo.svg +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/src/renderer/flow.js b/src/renderer/flow.js deleted file mode 100644 index 7b4d83c..0000000 --- a/src/renderer/flow.js +++ /dev/null @@ -1,173 +0,0 @@ -const INSTALL_STEPS = [ - { id: 'check', label: 'Checking this computer', estimate: 'about 10 seconds' }, - { id: 'download', label: 'Downloading ElastOS', estimate: 'about 1 minute' }, - { id: 'install', label: 'Installing', estimate: 'about 30 seconds' }, - { id: 'setup', label: 'Setting up your computer', estimate: 'about 2 minutes' }, - { id: 'start', label: 'Starting', estimate: 'about 20 seconds' }, -]; - -function stepIndexForMessage(message) { - const text = String(message || '').toLowerCase(); - if (text.includes('ready')) return INSTALL_STEPS.length; - if (text.includes('starting')) return 4; - if (text.includes('setting up') || text.includes('resuming')) return 3; - if (text.includes('installing')) return 2; - if (text.includes('download') || text.includes('hosted installer') || text.includes('pinned')) return 1; - if (text.includes('checking')) return 0; - return -1; -} - -function stepStates(message) { - const active = stepIndexForMessage(message); - return INSTALL_STEPS.map((step, index) => ({ - ...step, - state: active >= INSTALL_STEPS.length || index < active ? 'done' : index === active ? 'active' : 'pending', - })); -} - -function primaryAction(state) { - const status = state.status; - if (state.busy) return { id: 'busy', label: 'Working…', enabled: false }; - if (status === 'running') { - return { - id: 'open', - label: 'Open my computer', - enabled: true, - }; - } - if (status === 'not-installed' || status === 'error') { - return { - id: status === 'error' ? 'retry' : 'install', - label: status === 'error' ? 'Try again' : 'Install', - enabled: true, - }; - } - if (status === 'starting' || status === 'stopping') { - return { id: 'busy', label: 'Please wait', enabled: false }; - } - return { id: 'start', label: 'Start', enabled: true }; -} - -function confirmCopy(_targetId, paths, removesLinux) { - if (removesLinux) { - // Windows: Uninstall removes the whole ElastOS Linux environment (windowsUninstall.ts). - return { - title: 'Uninstall ElastOS?', - body: 'This removes ElastOS from this computer: the Linux environment named ElastOS, with the ElastOS program and all your ElastOS data in it. Next, ElastOS asks you one more time, and shows the file where it will save the whole Linux environment before it removes anything.', - paths, - }; - } - return { - title: 'Uninstall ElastOS?', - body: 'This removes the ElastOS program and its data from this computer.', - paths, - }; -} - -function resetCopy() { - return { - title: 'Reset ElastOS?', - body: 'This removes the ElastOS program and its data on this computer so you can install it again.', - }; -} - -/** - * The Reset dialog's backup offer. `description` comes from the main - * process (describeResetBackup). `needsChoice` keeps Reset off until the - * person picks one answer. - */ -function resetBackupCopy(description) { - const base = { - yes: 'Save a copy of your ElastOS data first', - no: 'Do not save a copy', - warning: 'The copy holds your keys and your sign-in identity. Anyone who has the file can use them. Keep it private.', - }; - if (!description || typeof description !== 'object') { - return { - ...base, - needsChoice: true, - canSave: false, - text: 'ElastOS could not measure your data, so it cannot save a copy now. You can still reset without a copy.', - space: '', - }; - } - // The main process found a reason Reset cannot run yet, such as python3 - // missing in the Windows Linux environment. Say it, and keep Reset off. - if (typeof description.blocked === 'string' && description.blocked) { - return { ...base, needsChoice: false, canSave: false, blocked: true, text: description.blocked, space: '' }; - } - if (!description.present) { - return { ...base, needsChoice: false, canSave: false, text: 'There is no ElastOS data on this computer to save.', space: '' }; - } - let space = ''; - if (!description.enough) { - space = description.freeBytes == null - ? 'ElastOS could not check the free space, so it cannot save a copy.' - : `There is not enough free space for a copy. It needs about ${formatBytes(description.neededBytes)}, and ${formatBytes(description.freeBytes)} is free.`; - } - return { - ...base, - needsChoice: true, - canSave: Boolean(description.enough), - text: `Your ElastOS data is about ${formatBytes(description.bytes)}. A copy goes in ${description.folder}. Program files, caches, and downloaded models are left out, because Install gets them again.`, - space, - }; -} - -function firstRunCopy(_targetId, status) { - if (status !== 'not-installed') return ''; - return 'Install ElastOS on this computer. One button downloads it, sets it up, and starts it. Then you open your computer in the browser.'; -} - -/** Decimal units, as plainBytes in runtimeBackup.ts: 1 KB is 1000 bytes, 1 MB is 1000 KB, 1 GB is 1000 MB. */ -function formatBytes(bytes) { - if (bytes === null || bytes === undefined || Number.isNaN(Number(bytes))) return 'size unavailable'; - const size = Number(bytes); - if (size < 1e3) return `${size} bytes`; - if (size < 999.5e3) return `${(size / 1e3).toFixed(size < 9.95e3 ? 1 : 0)} KB`; - if (size < 999.5e6) return `${(size / 1e6).toFixed(size < 9.95e6 ? 1 : 0)} MB`; - return `${(size / 1e9).toFixed(1)} GB`; -} - -function legacyPc2Copy(items) { - const lines = (items || []).map((entry) => `${entry.label} — ${entry.path} (${formatBytes(entry.bytes)})`); - return { - title: 'Remove PC2?', - body: 'This removes the old PC2 install from this computer. ElastOS is left as it is.', - list: lines.join('\n'), - backup: 'Back up my PC2 data first', - confirm: 'Remove PC2', - done: 'PC2 removed', - }; -} - -/** The info-panel Browser line. The main process sends it on Windows only. */ -function browserNoteText(info) { - return info && typeof info.browserNote === 'string' ? info.browserNote : ''; -} - -function urlLabel(openUrl) { - return String(openUrl || '').replace(/^https?:\/\//, '').replace(/\/$/, ''); -} - -const api = { - INSTALL_STEPS, - stepIndexForMessage, - stepStates, - primaryAction, - confirmCopy, - resetCopy, - resetBackupCopy, - firstRunCopy, - formatBytes, - legacyPc2Copy, - browserNoteText, - urlLabel, -}; - -if (typeof module !== 'undefined' && module.exports) { - module.exports = api; -} -if (typeof window !== 'undefined') { - window.elastosFlow = api; -} diff --git a/src/renderer/index.html b/src/renderer/index.html index f1e016f..1670009 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -1,186 +1,27 @@ - + - - + + ElastOS + -
- -
- -
- - -
-

- - - - -
-
-
- Checking... -
- -
- - -
- - -
- - - - -
-
- - -
-
- URL - ... -
-
- Version - ... - - -
- -
- - - - - - - -
- - -
- - -
- Presented by - -
-
+
+ +
+ +

ElastOS

+ + + + + +
+ +
- - - diff --git a/src/renderer/styles.css b/src/renderer/styles.css index 55aadb5..fbf506e 100644 --- a/src/renderer/styles.css +++ b/src/renderer/styles.css @@ -1,795 +1,23 @@ -* { - margin: 0; - padding: 0; - box-sizing: border-box; -} - -:root { - /* ElastOS window colors */ - --bg-body: #121212; - --bg-card: #1e1e1e; - --bg-panel: #252525; - --bg-input: #1a1a1a; - --accent: #9ca3af; - --accent-hover: #d1d5db; - --text-bright: #ffffff; - --text-normal: #b0b0b0; - --text-dim: #666666; - --border: rgba(255, 255, 255, 0.08); - --success: #22c55e; - --warning: #f59e0b; - --error: #ef4444; -} - -body { - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; - background: var(--bg-body); - min-height: 100vh; - display: flex; - align-items: flex-start; - justify-content: center; - padding: 28px 16px 40px; - color: var(--text-normal); - -webkit-app-region: drag; - user-select: none; -} - -.hidden { - display: none; -} - -.hardware-box { - width: 440px; - background: var(--bg-card); - border-radius: 20px; - box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5); - overflow: hidden; - -webkit-app-region: no-drag; -} - -/* Title Bar */ -.title-bar { - padding: 12px 20px; - background: var(--bg-panel); - border-bottom: 1px solid var(--border); - -webkit-app-region: drag; -} - -.title-with-logo { - display: flex; - align-items: center; - gap: 8px; -} - -.title-logo { - height: 16px; - width: auto; -} - -.title { - font-size: 12px; - font-weight: 600; - color: var(--text-dim); - letter-spacing: 0.5px; - text-transform: uppercase; -} - -/* Main Unit */ -.unit { - padding: 16px; - position: relative; -} - -/* Front Panel */ -.front-panel { - display: flex; - align-items: center; - justify-content: space-between; - padding: 16px 20px; - background: var(--bg-panel); - border-radius: 12px; - margin-bottom: 12px; -} - -.status-display { - display: flex; - align-items: center; - gap: 12px; -} - -.led { - width: 14px; - height: 14px; - border-radius: 50%; - background: var(--text-dim); - transition: all 0.3s; -} - -.led.running { - background: var(--success); - box-shadow: 0 0 12px var(--success); -} - -.led.stopped { - background: var(--text-dim); -} - -.led.starting, .led.stopping { - background: var(--warning); - box-shadow: 0 0 12px var(--warning); - animation: pulse 1s infinite; -} - -.led.error, .led.not-installed { - background: var(--error); - box-shadow: 0 0 12px var(--error); -} - -@keyframes pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.4; } -} - -.status-text { - font-size: 14px; - font-weight: 600; - color: var(--text-bright); - text-transform: uppercase; - letter-spacing: 0.5px; -} - -/* Power Button */ -.power-button { - width: 52px; - height: 52px; - border-radius: 50%; - border: 2px solid var(--border); - background: var(--bg-panel); - color: var(--accent); - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - transition: all 0.2s; -} - -.power-button:hover { - background: var(--bg-input); - transform: scale(1.05); -} - -.power-button:active { - transform: scale(0.95); -} - -.power-button:disabled { - opacity: 0.5; - cursor: not-allowed; - transform: none; -} - -.power-button.running { - color: var(--success); - border-color: var(--success); -} - -.power-button.running:hover { - color: var(--error); - border-color: var(--error); -} - -.power-button svg { - width: 24px; - height: 24px; -} - -/* Control Panel */ -.control-panel { - display: flex; - flex-direction: column; - gap: 8px; - margin-bottom: 12px; -} - -.control-btn { - display: flex; - align-items: center; - gap: 10px; - padding: 12px 16px; - background: var(--bg-panel); - border: 1px solid var(--border); - border-radius: 10px; - color: var(--text-normal); - font-size: 13px; - font-weight: 500; - cursor: pointer; - transition: all 0.2s; -} - -.control-btn:hover:not(:disabled) { - background: rgba(74, 158, 255, 0.1); - border-color: var(--accent); - color: var(--text-bright); -} - -.control-btn:disabled { - opacity: 0.4; - cursor: not-allowed; -} - -.control-btn.primary { - background: var(--accent); - color: white; - border: none; -} - -.control-btn.primary:hover:not(:disabled) { - background: var(--accent-hover); -} - -.control-btn.gold { - background: #f0b90b; - color: #1a1a1a; - border: none; -} - -.control-btn.gold:hover:not(:disabled) { - background: #fcd535; - color: #1a1a1a; -} - -.control-btn.gold:disabled { - background: #f0b90b; - color: #1a1a1a; - opacity: 0.5; -} - -.control-btn.danger { - color: var(--error); - border-color: rgba(239, 68, 68, 0.3); -} - -.control-btn.danger:hover:not(:disabled) { - background: rgba(239, 68, 68, 0.1); - border-color: var(--error); -} - -.control-btn .btn-icon { - width: 18px; - height: 18px; - flex-shrink: 0; -} - -.first-run { - font-size: 13px; - line-height: 1.45; - color: var(--text-normal); - margin-bottom: 12px; -} - -.first-run:empty { - display: none; -} - -.note, .error-box { - background: rgba(245, 158, 11, 0.12); - border: 1px solid rgba(245, 158, 11, 0.4); - color: var(--text-bright); - border-radius: 10px; - padding: 10px 12px; - font-size: 12px; - line-height: 1.4; - margin-bottom: 12px; -} - -.error-box { - background: rgba(239, 68, 68, 0.12); - border-color: rgba(239, 68, 68, 0.4); -} - -.error-box h3 { - margin: 0 0 6px; - font-size: 14px; - font-weight: 600; -} - -.steps { - list-style: none; - margin: 0 0 12px; - display: flex; - flex-direction: column; - gap: 6px; -} - -.steps li { - font-size: 12px; - color: var(--text-dim); -} - -.steps li.active { - color: var(--text-bright); -} - -.steps li.done { - color: var(--success); -} - -.target-row, .login-row { - display: flex; - align-items: center; - justify-content: space-between; - gap: 12px; - margin-bottom: 12px; - font-size: 12px; -} - -.login-row input { - margin-right: 8px; -} - -.button-row { - display: flex; - gap: 8px; -} - -.button-row .control-btn { - flex: 1; - flex-direction: row; - justify-content: center; -} - -/* Info Panel */ -.info-panel { - padding: 10px 14px; - background: var(--bg-input); - border-radius: 10px; - border: 1px solid var(--border); -} - -.info-row { - display: flex; - justify-content: space-between; - padding: 6px 0; -} - -.info-row:first-child:not(.single) { - border-bottom: 1px solid var(--border); -} - -.info-row.single { - border-bottom: none; -} - -.info-label { - color: var(--text-dim); - font-size: 12px; - text-transform: uppercase; - letter-spacing: 0.3px; -} - -#browser-row { - border-top: 1px solid var(--border); -} - -.info-note { - color: var(--text-normal); - font-size: 12px; - text-align: right; -} - -.info-value { - color: var(--text-normal); - font-size: 12px; - font-family: 'SF Mono', Monaco, monospace; -} - -/* Logs Panel */ -.logs-panel { - position: absolute; - top: 16px; - left: 16px; - right: 16px; - bottom: 16px; - background: var(--bg-card); - border-radius: 12px; - border: 1px solid var(--border); - display: flex; - flex-direction: column; - z-index: 10; -} - -.logs-panel.hidden { - display: none; -} - -.logs-header, .qr-header { - display: flex; - justify-content: space-between; - align-items: center; - padding: 12px 16px; - border-bottom: 1px solid var(--border); - font-weight: 600; - font-size: 13px; - color: var(--text-bright); -} - -.logs-actions { - display: flex; - align-items: center; - gap: 8px; -} - -.copy-btn { - background: none; - border: none; - color: var(--text-dim); - cursor: pointer; - padding: 4px; - display: flex; - border-radius: 4px; - transition: all 0.2s; -} - -.copy-btn:hover { - color: var(--text-bright); - background: var(--bg-panel); -} - -.copy-btn.copied { - color: var(--success); -} - -.copy-btn svg { - width: 16px; - height: 16px; -} - -.close-btn { - background: none; - border: none; - color: var(--text-dim); - cursor: pointer; - padding: 4px; - display: flex; -} - -.close-btn:hover { - color: var(--text-bright); -} - -.close-btn svg { - width: 16px; - height: 16px; -} - -.logs-content { - flex: 1; - overflow-y: auto; - padding: 12px 16px; - font-family: 'SF Mono', Monaco, monospace; - font-size: 10px; - line-height: 1.5; - color: var(--text-dim); - white-space: pre-wrap; - word-break: break-all; -} - -.logs-content.selectable { - user-select: text; - -webkit-user-select: text; - cursor: text; -} - -/* QR Modal */ -.qr-modal { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - background: rgba(0, 0, 0, 0.8); - display: flex; - align-items: center; - justify-content: center; - z-index: 20; - border-radius: 20px; -} - -.qr-modal.hidden { - display: none; -} - -.qr-content { - background: var(--bg-card); - border-radius: 16px; - padding: 0 20px 20px; - text-align: center; - border: 1px solid var(--border); -} - -#qr-image { - width: 180px; - height: 180px; - border-radius: 10px; - margin: 16px 0; -} - -.qr-url { - color: var(--accent); - font-family: 'SF Mono', Monaco, monospace; - font-size: 13px; - margin-bottom: 6px; -} - -.qr-note { - color: var(--text-dim); - font-size: 11px; -} - -/* Confirm Modal */ -.confirm-modal { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - background: rgba(0, 0, 0, 0.9); - display: flex; - align-items: center; - justify-content: center; - z-index: 30; - border-radius: 20px; -} - -.confirm-modal.hidden { - display: none; -} - -.confirm-content { - background: var(--bg-card); - border-radius: 16px; - padding: 24px; - text-align: center; - border: 1px solid var(--border); - max-width: 360px; - width: calc(100% - 32px); - max-height: calc(100% - 32px); - overflow-y: auto; -} - -.confirm-icon { - width: 48px; - height: 48px; - margin: 0 auto 16px; - color: var(--warning); -} - -.confirm-icon svg { - width: 100%; - height: 100%; -} - -.confirm-content h3 { - color: var(--text-bright); - font-size: 16px; - margin-bottom: 12px; -} - -.confirm-content p { - color: var(--text-dim); - font-size: 13px; - margin-bottom: 8px; -} - -.confirm-path { - color: var(--text-normal) !important; - font-family: 'SF Mono', Monaco, monospace; - background: var(--bg-input); - padding: 8px 12px; - border-radius: 6px; - margin: 12px 0 !important; - white-space: pre-wrap; - text-align: left; - word-break: break-all; - max-height: 140px; - overflow: auto; -} - -.confirm-backup { - display: flex; - gap: 8px; - align-items: flex-start; - text-align: left; - font-size: 13px; - margin: 12px 0; - color: var(--text-normal); -} - -.confirm-backup.hidden { - display: none; -} - -.reset-backup { - text-align: left; - font-size: 13px; - color: var(--text-normal); - margin: 12px 0; -} - -.reset-backup.hidden, -.reset-backup-space.hidden { - display: none; -} - -.reset-backup-warning { - font-weight: 600; -} - -.reset-backup-space { - color: var(--error); - margin: 0 0 8px 26px; -} - -.confirm-warning { - color: var(--error) !important; - font-weight: 600; - margin-top: 12px !important; -} - -.confirm-buttons { - display: flex; - gap: 10px; - margin-top: 20px; -} - -.confirm-btn { - flex: 1; - padding: 10px 16px; - border-radius: 8px; - font-size: 13px; - font-weight: 600; - cursor: pointer; - transition: all 0.2s; -} - -.confirm-btn:disabled { - opacity: 0.45; - cursor: not-allowed; -} - -.confirm-btn.cancel { - background: var(--bg-panel); - border: 1px solid var(--border); - color: var(--text-normal); -} - -.confirm-btn.cancel:hover { - background: var(--bg-input); - color: var(--text-bright); -} - -.confirm-btn.delete { - background: var(--error); - border: none; - color: white; -} - -.confirm-btn.delete:hover { - background: #dc2626; -} - -/* Bottom Panel */ -#remove-pc2-btn { - width: 100%; - margin-bottom: 8px; -} - -.bottom-panel { - display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - padding: 12px 16px; - background: var(--bg-panel); - border-top: 1px solid var(--border); -} - -.env-selector { - display: flex; - align-items: center; - gap: 10px; -} - -.env-label { - font-size: 11px; - color: var(--text-dim); - text-transform: uppercase; - letter-spacing: 0.3px; -} - -.env-dropdown { - background: var(--bg-input); - border: 1px solid var(--border); - border-radius: 6px; - padding: 5px 10px; - color: var(--text-normal); - font-size: 12px; - font-family: 'SF Mono', Monaco, monospace; - cursor: pointer; -} - -.env-dropdown:hover { - border-color: var(--accent); -} - -.env-dropdown:focus { - outline: none; - border-color: var(--accent); -} - -.brand-section { - display: flex; - align-items: center; - gap: 6px; -} - -.presented-by { - font-size: 10px; - color: var(--text-dim); -} - -.brand-logo { - height: 14px; - width: auto; - opacity: 0.7; -} - -/* Update button */ -.update-btn { - display: inline-flex; - align-items: center; - gap: 4px; - padding: 2px 8px; - font-size: 11px; - line-height: 1; - font-family: inherit; - background: var(--success); - color: #000; - border: none; - border-radius: 4px; - cursor: pointer; - margin-left: 8px; - transition: opacity 0.2s; -} - -.update-btn:hover { - opacity: 0.85; -} - -.update-btn:disabled { - opacity: 0.5; - cursor: not-allowed; -} - -.update-btn .update-icon { - width: 12px; - height: 12px; -} - -.update-btn.hidden { - display: none; -} - -/* Scrollbar */ -::-webkit-scrollbar { - width: 6px; -} - -::-webkit-scrollbar-track { - background: transparent; -} - -::-webkit-scrollbar-thumb { - background: rgba(255, 255, 255, 0.1); - border-radius: 3px; -} +:root { color-scheme: light dark; font: 13px/1.45 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; color: light-dark(#202020, #ededed); background: light-dark(#f5f5f5, #252525); } +* { box-sizing: border-box; } +body { margin: 0; } +[hidden] { display: none !important; } +.title-bar { height: 36px; width: 100%; -webkit-app-region: drag; user-select: none; } +main { padding: 8px 28px 24px; text-align: center; } +.app-mark { display: block; margin: 0 auto 10px; } +h1 { font-size: 23px; line-height: 1.2; font-weight: 600; margin: 0 0 22px; } +p { margin: 0 0 18px; overflow-wrap: anywhere; } +#login-row { display: flex; justify-content: center; align-items: center; gap: 6px; margin-bottom: 24px; } +input { margin: 0; accent-color: #007aff; } +#location { color: light-dark(#626262, #bdbdbd); font-size: 12px; } +#actions { display: flex; gap: 10px; } +button { font: inherit; border-radius: 7px; border: 1px solid transparent; min-height: 44px; padding: 8px 14px; cursor: pointer; } +#primary { flex: 1; min-width: 0; background: #006ee6; color: white; font-weight: 500; } +#cancel { flex: none; white-space: nowrap; background: light-dark(#e6e6e6, #444); color: inherit; } +button:disabled { opacity: .5; cursor: default; } +button, a, input, label { -webkit-app-region: no-drag; } +:focus-visible { outline: 3px solid #2687ed; outline-offset: 3px; } +a, .text-button { color: light-dark(#0066cc, #78b6ff); } +#release-notes { display: inline-block; margin: -4px 0 20px; } +.text-button { background: none; min-height: 32px; padding: 8px; margin-top: 8px; } +progress { display: block; width: 100%; height: 6px; accent-color: #007aff; margin: 24px 0 28px; } diff --git a/test/ci-plan.test.js b/test/ci-plan.test.js new file mode 100644 index 0000000..94dcdff --- /dev/null +++ b/test/ci-plan.test.js @@ -0,0 +1,136 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); +const test = require('node:test'); +const yaml = require('js-yaml'); + +const root = path.join(__dirname, '..'); +const workflows = Object.fromEntries(['test', 'runtime-smoke', 'linux-arm64', 'build'].map((name) => [ + name, yaml.load(fs.readFileSync(path.join(root, `.github/workflows/${name}.yml`), 'utf8')), +])); + +// Import the actual planner only inside tests, so the original YAML policy +// checks can also run before the planner exists. +const plan = (context) => require('../scripts/ci-plan').plan(context); + +for (const [name, workflow] of Object.entries(workflows)) { + test(`${name} cancels superseded runs in a distinct workflow group`, () => { + assert.equal(workflow.concurrency?.['cancel-in-progress'], true); + assert.equal(workflow.concurrency.group, `${name}-` + '${{ github.head_ref || github.ref }}'); + }); + if (workflow.on.pull_request !== undefined) { + test(`${name} ignores documentation-only pull requests`, () => { + assert.deepEqual(workflow.on.pull_request['paths-ignore'], ['**/*.md', 'docs/**']); + }); + } +} + +test('every platform job depends on and checks the shared plan', () => { + for (const name of ['runtime-smoke', 'linux-arm64', 'build']) { + const workflow = workflows[name]; + assert.equal(workflow.jobs.plan['runs-on'], 'ubuntu-latest'); + const step = workflow.jobs.plan.steps.find((step) => step.run === 'node scripts/ci-plan.js'); + assert.ok(step, `${name} runs the real planner`); + assert.equal(step.env.INPUT_PLATFORMS, '${{ inputs.platforms }}'); + for (const [id, job] of Object.entries(workflow.jobs)) { + if (id === 'plan') continue; + assert.ok(job.needs.includes('plan'), `${name}/${id} needs plan`); + assert.match(job.if, /needs\.plan\.outputs\.platforms/, `${name}/${id} checks plan`); + } + } +}); + +test('manual dispatch defaults to none and build keeps tag-only automatic triggers', () => { + for (const name of ['runtime-smoke', 'linux-arm64', 'build']) { + assert.equal(workflows[name].on.workflow_dispatch.inputs.platforms.default, 'none'); + } + assert.deepEqual(Object.keys(workflows.build.on).sort(), ['push', 'workflow_dispatch']); + assert.deepEqual(workflows.build.on.push, { tags: ['v*'] }); + assert.equal(workflows.build.on.workflow_dispatch.inputs.notarize.default, false); + assert.equal(workflows.build.jobs['linux-arm64'].with.platforms, 'linux'); + assert.equal(workflows.build.jobs.release.steps.find((step) => step.uses?.startsWith('softprops/')).uses, + 'softprops/action-gh-release@v2'); + for (const name of ['test', 'runtime-smoke', 'linux-arm64']) { + assert.deepEqual(workflows[name].on.push, { branches: ['main'] }); + } +}); + +test('only HEAD is packaged for Mac dialogs and workflows contain no obsolete release', () => { + const steps = workflows['runtime-smoke'].jobs['mac-dialogs'].steps; + assert.ok(steps.some((step) => step.run === 'node scripts/mac-dialog-e2e.js dist-electron/mac-arm64/ElastOS.app')); + for (const workflow of Object.values(workflows)) { + assert.doesNotMatch(JSON.stringify(workflow), /a66ca52|launcher-baseline|0\.8\.0-alpha\.22/); + } +}); + +for (const [branch, expected] of [ + ['test/launcher-mac-dmg', ['mac']], ['test/launcher-mac-other', ['mac']], + ['test/launcher-jetson', ['linux']], ['test/launcher-linux-x64', ['linux']], + ['test/launcher-windows', ['windows']], ['feature/unknown', []], + ['test/launcher-macos', ['mac']], ['feature/test/launcher-mac', []], +]) { + for (const eventName of ['pull_request', 'push']) { + test(`${eventName} ${branch} selects ${expected.join(',') || 'none'}`, () => { + assert.deepEqual(plan({ eventName, ref: `refs/heads/${branch}`, headRef: branch, baseRef: 'develop' }).platforms, expected); + }); + } +} + +test('main takes precedence over a platform PR head and a push ignores head/base fields', () => { + const all = ['mac', 'linux', 'windows']; + assert.deepEqual(plan({ eventName: 'pull_request', ref: 'refs/pull/63/merge', headRef: 'test/launcher-mac-dmg', baseRef: 'main' }).platforms, all); + assert.deepEqual(plan({ eventName: 'push', ref: 'refs/heads/main' }).platforms, all); + assert.deepEqual(plan({ eventName: 'push', ref: 'refs/heads/unknown', headRef: 'test/launcher-mac-dmg', baseRef: 'main' }).platforms, []); + assert.deepEqual(plan({ eventName: 'push', ref: 'refs/tags/v2.0.0' }).platforms, all); +}); + +test('dispatch is explicit even on main and reusable calls accept the caller selection', () => { + for (const requested of ['none', 'mac', 'linux', 'windows', 'all']) { + const expected = requested === 'all' ? ['mac', 'linux', 'windows'] : requested === 'none' ? [] : [requested]; + assert.deepEqual(plan({ eventName: 'workflow_dispatch', ref: 'refs/heads/main', requested }).platforms, expected); + } + assert.deepEqual(plan({ eventName: 'workflow_dispatch', ref: 'refs/heads/main' }).platforms, []); + assert.deepEqual(plan({ eventName: 'push', ref: 'refs/tags/v2.0.0', requested: 'linux' }).platforms, ['linux']); + assert.throws(() => plan({ eventName: 'workflow_dispatch', requested: 'bogus' }), /Invalid platforms/); +}); + +test('runtime and build matrices contain only selected platforms, preserving both Linux architectures', () => { + assert.deepEqual(plan({ requested: 'none' }).runtime, []); + assert.deepEqual(plan({ requested: 'windows' }).runtime, []); + assert.deepEqual(plan({ requested: 'mac' }).runtime.map((row) => row.platform), ['darwin-arm64']); + assert.deepEqual(plan({ requested: 'linux' }).runtime.map((row) => row.platform), ['linux-x64', 'linux-arm64']); + for (const requested of ['none', 'mac', 'linux', 'windows', 'all']) { + const result = plan({ requested }); + assert.deepEqual(result.build.map((row) => row.platform), result.platforms.map((platform) => platform === 'windows' ? 'win' : platform)); + } + const smoke = workflows['runtime-smoke'].jobs; + for (const id of ['smoke', 'electron-e2e']) { + assert.equal(smoke[id].strategy.matrix.include, '${{ fromJSON(needs.plan.outputs.runtime) }}'); + assert.equal(smoke[id].if, "contains(needs.plan.outputs.platforms, 'mac') || contains(needs.plan.outputs.platforms, 'linux')"); + } + for (const id of ['windows-wsl', 'electron-e2e-windows', 'windows-app', 'clean-machine-windows']) { + assert.equal(smoke[id].if, "contains(needs.plan.outputs.platforms, 'windows')"); + } + assert.equal(smoke['mac-dialogs'].if, "contains(needs.plan.outputs.platforms, 'mac')"); + assert.equal(smoke['clean-machine-linux'].if, "contains(needs.plan.outputs.platforms, 'linux')"); + assert.equal(workflows['linux-arm64'].jobs.package.if, "contains(needs.plan.outputs.platforms, 'linux')"); + assert.equal(workflows.build.jobs.build.strategy.matrix.include, '${{ fromJSON(needs.plan.outputs.build) }}'); +}); + +test('planner CLI reads GitHub context and emits workflow output using the same function', (t) => { + const output = path.join(require('node:os').tmpdir(), `ci-plan-${process.pid}.txt`); + t.after(() => fs.unlinkSync(output)); + const result = spawnSync(process.execPath, ['scripts/ci-plan.js'], { + cwd: root, encoding: 'utf8', env: { + ...process.env, GITHUB_EVENT_NAME: 'pull_request', GITHUB_HEAD_REF: 'test/launcher-mac-dmg', + GITHUB_BASE_REF: 'develop', GITHUB_REF: 'refs/pull/63/merge', INPUT_PLATFORMS: '', GITHUB_OUTPUT: output, + }, + }); + assert.equal(result.status, 0, result.stderr); + const emitted = Object.fromEntries(fs.readFileSync(output, 'utf8').trim().split('\n').map((line) => { + const split = line.indexOf('='); + return [line.slice(0, split), JSON.parse(line.slice(split + 1))]; + })); + assert.deepEqual(emitted, plan({ eventName: 'pull_request', headRef: 'test/launcher-mac-dmg', baseRef: 'develop' })); +}); diff --git a/test/controller-fixture.js b/test/controller-fixture.js new file mode 100644 index 0000000..cf65ca8 --- /dev/null +++ b/test/controller-fixture.js @@ -0,0 +1,73 @@ +const { createLaunchController } = require('../dist/main/launchController'); +const gateway = require('../dist/main/targets/runtimeGateway'); +const windows = require('../dist/main/targets/windowsRuntime'); +const targets = require('../dist/main/targets'); +const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); + +// Real controller, target and supervisor. Only installation, update commands, +// process handles and health are fake. Every replacement shares the same world. +function runtimeFixtures(t, platform) { + let world; + function supervisor(lifetime) { + const runtime = world; + const sup = gateway.createGatewaySupervisor({ + lifetime, platform, binary: '/fixture/elastos', args: gateway.homeLaunchForPlatform(platform).args, + spawn() { + runtime.calls.push('start'); runtime.running = true; + const proc = { + pid: 123, spawnedHere: true, exited: false, + onOutput() {}, onExit(fn) { this.exit = fn; }, + async hasExited() { await runtime.wait.hasExited?.(); await runtime.wait.start?.(); return this.exited; }, + signal() { this.exited = true; runtime.running = false; this.exit?.(0); }, + }; + runtime.proc = proc; + return proc; + }, + async fetchHealth() { + await runtime.wait.start?.(); + return runtime.running ? { status: 200, body: 'OK' } : null; + }, + sleep: async () => { runtime.clock += 1000; }, now: () => runtime.clock, + openUrl() {}, log() {}, + }); + const stop = sup.stop; + sup.stop = async (...args) => { + runtime.calls.push('stop'); + await runtime.wait.stop?.(); + return stop(...args); + }; + runtime.supervisors.push(sup); + return sup; + } + t.mock.method(gateway, 'createDefaultGatewaySupervisor', (_file, actualPlatform, lifetime) => { + if (actualPlatform !== platform) throw new Error(`Wrong platform: ${actualPlatform}`); + return supervisor(lifetime); + }); + t.mock.method(windows, 'createDistroGatewaySupervisor', supervisor); + t.mock.method(windows, 'distroIsInstalled', () => true); + t.mock.method(gateway, 'installedGatewayOnThisComputer', async () => 'none'); + t.mock.method(require('../dist/main/targets/runtimeProbe'), 'findRuntimeBinary', () => '/fixture/elastos'); + t.mock.method(require('../dist/main/targets/runtimePin'), 'loadActiveRuntimePin', () => ({ + maintainerDid: 'did:example:test', publisherGateway: 'https://example.invalid', version: '2.0.0', + })); + for (const [method, action] of [['applyRuntimeUpdate', 'update'], ['rollbackRuntime', 'rollback']]) { + t.mock.method(require('../dist/main/targets/runtimeUpdate'), method, async () => { + world.calls.push(action); await world.wait[action]?.(); + }); + } + t.mock.method(targets, 'createLaunchTarget', () => createRuntimeTarget(platform, platform === 'darwin' ? 'arm64' : 'x64', world.lifetime)); + return () => { + world = { lifetime: { shuttingDown: false, shutdown() { this.shuttingDown = true; } }, calls: [], running: false, wait: {}, clock: 0, supervisors: [] }; + const launch = createLaunchController({ env: {} }); + // These observations are controlled separately from process ownership. + launch.target.getStatus = async () => world.running ? 'running' : 'stopped'; + launch.target.openInBrowser = () => {}; + launch.target.checkForUpdate = async () => ({ latest: '2.0.1', updateAvailable: true, releaseUrl: '' }); + launch.getOpenAtLogin = () => false; + launch.resumeInstallPlan = async () => 'none'; + launch.describeResetBackup = async () => ({ present: true, enough: true }); + launch.describeFailure = async () => ({ message: 'The download stopped.', fixLabel: null }); + return { launch, runtime: world }; + }; +} +module.exports = { runtimeFixtures }; diff --git a/test/darwin-kernel-path.test.js b/test/darwin-kernel-path.test.js new file mode 100644 index 0000000..94677c0 --- /dev/null +++ b/test/darwin-kernel-path.test.js @@ -0,0 +1,22 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); + +const { installedGatewayKind } = require('../dist/main/targets/runtimeGateway'); + +test('a proved kernel path accepts a gateway whose command does not start with that path', () => { + const kernel = '/Users/example/.local/share/elastos/elastos'; + const facts = { + lockText: JSON.stringify({ pid: 10, addr: 'localhost:8090' }), + verifiedExecutable: kernel, + pidAlive: () => true, + ownsSocket: () => true, + }; + assert.equal(installedGatewayKind({ + ...facts, + command: 'elastos gateway --addr localhost:8090', + }), 'current'); + assert.equal(installedGatewayKind({ + ...facts, + command: 'elastos serve', + }), null); +}); diff --git a/test/e2e-waits.test.js b/test/e2e-waits.test.js new file mode 100644 index 0000000..fb8705c --- /dev/null +++ b/test/e2e-waits.test.js @@ -0,0 +1,146 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const waits = require('../scripts/tray-e2e'); + +function clock(t) { + let now = 0; + t.mock.method(Date, 'now', () => now); + t.mock.method(global, 'setTimeout', (fn, ms) => { now += ms; queueMicrotask(fn); }); + return () => now; +} + +function fixture(t, focused, nullFocusedWindow = false) { + const now = clock(t); + const calls = []; + const logs = path.join(__dirname, `.e2e-logs-${process.pid}`); + fs.mkdirSync(logs); + t.after(() => { fs.unlinkSync(path.join(logs, 'main.log')); fs.rmdirSync(logs); }); + fs.writeFileSync(path.join(logs, 'main.log'), Array.from({ length: 65 }, (_, i) => `launcher line ${i + 1}`).join('\n') + '\n'); + const win = { + id: 7, getTitle: () => 'ElastOS', isVisible: () => true, + isFocused: () => focused(now()), focus: () => calls.push('window.focus'), + webContents: { executeJavaScript: async () => ({ kind: 'install', message: 'Home is ready.', primary: 'Open Home' }) }, + }; + const app = { evaluate: async (fn, arg) => vm.runInNewContext(`(${fn})`, { + global, process: {}, + })({ + app: { focus: options => calls.push({ ...options }), getPath: () => path.join(logs, 'different-electron-log-folder') }, + BrowserWindow: { getAllWindows: () => [win], getFocusedWindow: () => !nullFocusedWindow && win.isFocused() ? win : null }, + }, arg) }; + t.mock.method(console, 'error', () => {}); + global.__elastosLogPath = path.join(logs, 'main.log'); + global.__openedHome = ['http://localhost:8090/home/']; + t.after(() => { delete global.__openedHome; delete global.__elastosLogPath; }); + return { app, calls, now }; +} + +test('focusWindow requests app and window focus and waits for the actual focused window', async t => { + const { app, calls, now } = fixture(t, now => now >= 750); + await waits.focusWindow(app); + assert.equal(now(), 750); + assert.deepEqual(calls, [{ steal: true }, 'window.focus']); +}); + +test('focusWindow uses the window own focus when the global focused window stays null', async t => { + const { app, now } = fixture(t, now => now >= 750, true); + await waits.focusWindow(app); + assert.equal(now(), 750); +}); + +test('focusWindow fails with focus, renderer state, browser calls and exactly the last 60 log lines', async t => { + const { app, now } = fixture(t, () => false); + await assert.rejects(waits.focusWindow(app), error => { + assert.match(error.message, /Launcher window did not gain focus/); + assert.match(error.message, /focused window: null/); + assert.match(error.message, /"id":7/); + assert.match(error.message, /Home is ready/); + assert.match(error.message, /__openedHome:.*localhost:8090/); + const tail = error.message.split('launcher log (last 60 lines):\n')[1]; + assert.equal(tail.split('\n').length, 60); + assert.equal(tail.split('\n')[0], 'launcher line 6'); + assert.equal(tail.split('\n').at(-1), 'launcher line 65'); + assert.ok(console.error.mock.calls.length, 'diagnostics printed before rejection'); + return true; + }); + assert.equal(now(), 10000); +}); + +test('waitFor includes diagnostics when its predicate throws and preserves the original cause', async t => { + const { app } = fixture(t, () => true); + const cause = new Error('Runtime reported an install error'); + await assert.rejects(waits.waitFor(() => { throw cause; }, 1000, 'Install timeout', app), error => { + assert.equal(error.cause, cause); + assert.match(error.message, /Runtime reported an install error/); + assert.match(error.message, /focused window: 7/); + assert.match(error.message, /launcher line 65/); + return true; + }); +}); + +for (const platform of ['mac', 'linux', 'windows']) { + test(`${platform} lifecycle waits for a fresh async Open Home browser call`, async t => { + const now = clock(t); + let clickedAt; + // An earlier click must not satisfy this lifecycle step. + global.__elastosTray = true; + global.__openedHome = ['http://localhost:8090/home/']; + t.after(() => { delete global.__openedHome; delete global.__elastosTray; }); + const shell = {}; + let context; + const app = { evaluate: async (fn, arg) => { + if (clickedAt !== undefined && now() - clickedAt >= 750 && !global.__openedHome.length) shell.openExternal('http://localhost:8090/home/'); + return vm.runInContext(`(${fn})`, context)({ shell, BrowserWindow: { getAllWindows: () => [] } }, arg); + } }; + const stop = new Error('stop after the browser assertion'); + const script = path.resolve(__dirname, `../scripts/${platform}-lifecycle-e2e.js`); + const sandbox = { + module: { exports: {} }, global, process: {}, Date, setTimeout, console, fetch: async () => { + assert.ok(now() - clickedAt >= 750, 'browser assertion ran before openApp completed'); + throw stop; + }, + require: name => { + if (name === './tray-e2e') return { ...waits, trayState: async () => {}, noWindow: async () => {}, clickMenu: async () => { + assert.equal(global.__openedHome.length, 0, 'browser history must be cleared before the menu click'); + clickedAt = now(); + } }; + if (name.startsWith('../dist/')) return {}; + return require(name); + }, + }; + context = vm.createContext(sandbox); + vm.runInContext(fs.readFileSync(script, 'utf8'), context, { filename: script }); + await assert.rejects(sandbox.module.exports(app, {}, '/fixture', {}), error => error === stop); + assert.equal(now(), 750); + }); +} + +test('waitFor still prints the launcher log when Electron has exited', async t => { + const { app } = fixture(t, () => true); + await waits.waitFor(() => true, 1000, 'initial ready', app); + t.mock.method(app, 'evaluate', async () => { throw new Error('Electron connection closed'); }); + await assert.rejects(waits.waitFor(() => false, 1000, 'Home health did not become false', app), error => { + assert.match(error.message, /Home health did not become false/); + assert.match(error.message, /focused window:.*Electron connection closed/); + assert.match(error.message, /current window state:.*Electron connection closed/); + assert.match(error.message, /__openedHome:.*Electron connection closed/); + assert.match(error.message, /launcher log \(last 60 lines\):\nlauncher line 6/); + assert.match(error.message, /launcher line 65$/); + return true; + }); +}); + +test('waitFor retries the log path lookup after the launcher finishes initializing', async t => { + const { app } = fixture(t, () => true); + const logPath = global.__elastosLogPath; + delete global.__elastosLogPath; + await waits.waitFor(() => true, 1000, 'early observation', app); + global.__elastosLogPath = logPath; + await assert.rejects(waits.waitFor(() => false, 1000, 'later timeout', app), error => { + assert.match(error.message, /launcher log \(last 60 lines\):\nlauncher line 6/); + assert.match(error.message, /launcher line 65$/); + return true; + }); +}); diff --git a/test/electron-e2e.test.js b/test/electron-e2e.test.js new file mode 100644 index 0000000..9f4f927 --- /dev/null +++ b/test/electron-e2e.test.js @@ -0,0 +1,210 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const { mainFixture } = require('./main-fixture'); + +// Run the complete CI entry point against the real main-process retry handler. +test('Windows install e2e answers native Set Up and waits through setup to Home is ready', async () => { + const f = await mainFixture({ installed: false, platform: 'win32' }); + const install = f.launch.install; + let setup = false; + f.launch.install = async progress => { + if (!setup) throw new Error('Windows needs Linux support.'); + await install(progress); + }; + f.launch.describeFailure = async () => ({ kind: 'windows', message: 'Windows needs Linux support.', fixLabel: 'Try Again' }); + f.launch.getPreflight = async () => ({ checks: [] }); + let finishSetup; + f.launch.fixFailure = async () => { + await new Promise(resolve => { finishSetup = resolve; }); + setup = true; + return 'still-blocked'; + }; + let clicking; + let primaryDisabled = false; + const page = { + locator: selector => ({ + waitFor: async () => {}, + innerText: async () => { + const state = await f.invoke('getWindowState'); + if (selector === '#message') return state.message; + return state.kind === 'error' ? state.actionLabel : state.ready ? 'Open Home' : 'Install'; + }, + }), + getAttribute: async () => (await f.invoke('getWindowState')).kind, + click: async () => { + const state = await f.invoke('getWindowState'); + if (state.kind === 'error') { + primaryDisabled = true; + clicking = f.invoke('retry'); + await new Promise(resolve => setImmediate(resolve)); + } else if (!state.ready) await f.invoke('install', false); + else await f.invoke('openHome'); + }, + waitForFunction: async predicate => { + assert.equal(predicate(), false); + assert.ok(finishSetup, 'Set Up confirmation must be accepted'); + finishSetup(); + await clicking; + primaryDisabled = false; + assert.equal(predicate(), true); + }, + evaluate: async () => f.invoke('copyDiagnostics'), + }; + const logs = []; + const dialog = {}; + Object.defineProperty(dialog, 'showMessageBox', { + set(handler) { + f.dialog.showMessageBox = async (...args) => { + const options = args.at(-1); + f.dialogs.push(options); + return handler(...args); + }; + }, + }); + const electronApp = { + firstWindow: async () => page, + evaluate: async (fn, arg) => fn({ + shell: {}, dialog, app: { exit() {} }, clipboard: { readText: () => [ + 'Release head signature matches the pinned maintainer', 'install.sh SHA-256 matches the pin', 'Installed head CID matches the pin', + ].join('\n') }, + }, arg), + process: () => ({ kill() {} }), + }; + let exit; + const done = new Promise(resolve => { exit = resolve; }); + const script = path.resolve(__dirname, '../scripts/electron-e2e.js'); + const sandbox = { + __dirname: path.dirname(script), console: { log: line => logs.push(line), error: line => logs.push(String(line)) }, + process: { platform: 'win32', env: {}, exit }, global: {}, + setTimeout: () => 0, clearTimeout() {}, + document: { querySelector: () => ({ disabled: primaryDisabled }) }, + require: name => { + if (name === 'electron') return '/fixture/electron'; + if (name === 'playwright') return { _electron: { launch: async () => electronApp } }; + if (name === 'node:os') return { homedir: () => '/fixture' }; + if (name === 'node:fs') return { mkdirSync() {}, chmodSync() {}, mkdtempSync: () => '/fixture/home', existsSync: () => true }; + if (name === '../dist/main/targets/runtimeGateway') return { + HOME_URL: 'http://localhost:8090/home/', isHealthOk: () => true, probeGatewayHealth: async () => ({}), + }; + if (name === './tray-e2e') return { + waitFor: async predicate => { for (let i = 0; i < 8; i++) if (await predicate()) return; throw new Error('Install did not finish'); }, + noWindow: async () => {}, + }; + if (name === './windows-lifecycle-e2e') return async app => app; + return require(name); + }, + }; + f.launch.openInBrowser = () => sandbox.__openedHome.push('http://localhost:8090/home/'); + sandbox.global = sandbox; + vm.runInNewContext(fs.readFileSync(script, 'utf8'), sandbox, { filename: script }); + assert.equal(await done, 0, logs.join('\n')); + assert.ok(logs.includes('PASS install through window reaches Home is ready with signed-install evidence')); + assert.equal(f.calls.filter(call => call === 'install').length, 1); + assert.deepEqual(f.dialogs[0].buttons, ['Cancel', 'Set Up']); + assert.equal(f.dialogs[0].defaultId, 0); + assert.equal(setup, true); + assert.equal((await f.dialog.showMessageBox({ buttons: ['Cancel', 'Reset'] })).response, 0); +}); + +for (const mode of ['delayed focus', 'never focused', 'duplicate tab']) { + test(`Mac install e2e handles ${mode} before the native Open Home click`, async t => { + let now = 0; + t.mock.method(Date, 'now', () => now); + t.mock.method(global, 'setTimeout', (fn, ms) => { now += ms; queueMicrotask(fn); }); + const waits = require('../scripts/tray-e2e'); + let ready = false, closed = false, focusAt, nativeClicks = 0, compiles = 0; + const focusCalls = []; + const logs = []; + const shell = {}; + const sandbox = {}; + const win = { + id: 1, getTitle: () => 'ElastOS', isVisible: () => !closed, + isFocused: () => !ready || (mode !== 'never focused' && focusAt !== undefined && now - focusAt >= 750), + focus: () => { focusAt = now; focusCalls.push('window.focus'); }, + getContentBounds: () => ({ x: 10, y: 20, width: 360, height: 400 }), + webContents: { executeJavaScript: async () => ({ kind: 'install', message: 'Home is ready.' }) }, + }; + const page = { + locator: selector => ({ waitFor: async () => {}, innerText: async () => selector === '#message' ? 'Home is ready.' : ready ? 'Open Home' : 'Install', + boundingBox: async () => ({ x: 5, y: 300, width: 360, height: 40 }), + }), + waitForTimeout: async () => {}, + getAttribute: async () => 'install', evaluate: async () => {}, + }; + const app = { + firstWindow: async () => page, + evaluate: async (fn, arg) => vm.runInNewContext(`(${fn})`, { + global: sandbox, process: { mainModule: { require: name => { + assert.equal(name, 'electron-log'); + return { transports: { file: { getFile: () => ({ path: '/fixture/no-logs/main.log' }) } } }; + } } }, + })({ + app: { focus: options => focusCalls.push({ ...options }), exit() {}, getPath: () => '/fixture/no-logs' }, + BrowserWindow: { getAllWindows: () => [win], getFocusedWindow: () => win.isFocused() ? win : null }, + shell, clipboard: { readText: () => ['Release head signature matches the pinned maintainer', 'install.sh SHA-256 matches the pin', 'Installed head CID matches the pin'].join('\n') }, + }, arg), + process: () => ({ kill() {} }), + }; + t.mock.method(require('node:child_process'), 'spawnSync', (file, args) => { + if (file === 'swiftc') { + compiles++; + now += 20000; + focusAt = undefined; + } else if (args.length === 4) { + win.getContentBounds = () => ({ x: 70, y: 65, width: 360, height: 400 }); + } else { + nativeClicks++; + assert.equal(win.isFocused(), true, 'native click reached an inactive window'); + if (!ready) { + ready = true; + focusAt = undefined; // home --browser brings another app to the front. + if (mode === 'duplicate tab') shell.openExternal('http://localhost:8090/home/'); + } else { + shell.openExternal('http://localhost:8090/home/'); + closed = true; + } + } + return { status: 0 }; + }); + const nativeFile = require.resolve('../scripts/mac-native'); + delete require.cache[nativeFile]; + const native = require(nativeFile); + t.after(() => { delete require.cache[nativeFile]; }); + let finish; + const done = new Promise(resolve => { finish = resolve; }); + const script = path.resolve(__dirname, '../scripts/electron-e2e.js'); + Object.assign(sandbox, { + __dirname: path.dirname(script), Date, global: sandbox, + console: { log: line => logs.push(String(line)), error: line => logs.push(String(line)) }, + process: { platform: 'darwin', env: { GITHUB_ACTIONS: 'true' }, exit: finish }, + setTimeout: () => 0, + require: name => { + if (name === 'electron') return '/fixture/electron'; + if (name === 'playwright') return { _electron: { launch: async () => app } }; + if (name === 'node:os') return { homedir: () => '/fixture' }; + if (name === 'node:fs') return { mkdirSync() {}, chmodSync() {}, mkdtempSync: () => '/fixture/home' }; + if (name === '../dist/main/targets/runtimeGateway') return { HOME_URL: 'http://localhost:8090/home/', isHealthOk: () => true, probeGatewayHealth: async () => ({}) }; + if (name === './tray-e2e') return waits; + if (name === './mac-native') return native; + if (name === './mac-lifecycle-e2e') return async () => app; + return require(name); + }, + }); + // The real helper prints failure evidence; keep it in the fixture's output. + t.mock.method(console, 'error', line => logs.push(String(line))); + vm.runInNewContext(fs.readFileSync(script, 'utf8'), sandbox, { filename: script }); + assert.equal(await done, mode === 'delayed focus' ? 0 : 1, logs.join('\n')); + assert.equal(nativeClicks, mode === 'delayed focus' ? 2 : 1); + assert.equal(compiles, 1, 'compile the helper once per app and page'); + if (mode === 'delayed focus') { + assert.equal(now, 20950); + assert.deepEqual(focusCalls, [{ steal: true }, 'window.focus', { steal: true }, 'window.focus', { steal: true }, 'window.focus']); + } else if (mode === 'never focused') { + assert.match(logs.join('\n'), /Launcher window did not gain focus/); + assert.match(logs.join('\n'), /current window state:.*Home is ready/); + } else assert.match(logs.join('\n'), /Mac Install opened a duplicate browser tab/); + }); +} diff --git a/test/electron-main.test.js b/test/electron-main.test.js new file mode 100644 index 0000000..9949e4e --- /dev/null +++ b/test/electron-main.test.js @@ -0,0 +1,19 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { readMain } = require('../scripts/electron-main'); + +test('main observations run outside the inspector stack and preserve results and errors', async () => { + let inside = false, calls = 0; + const electron = { read(value) { assert.equal(inside, false); calls++; return value; } }; + const app = { async evaluate(fn, arg) { + inside = true; + let result; + try { result = fn(electron, arg); } finally { inside = false; } + return result; + } }; + assert.deepEqual(await readMain(app, (e, value) => e.read(value), { ready: true }), { ready: true }); + assert.equal(calls, 1); + await assert.rejects(readMain(app, () => { throw new Error('observation failed'); }), /observation failed/); + const closed = new Error('Electron exited'); + await assert.rejects(readMain({ evaluate: async () => { throw closed; } }, () => true), error => error === closed); +}); diff --git a/test/failure-window.test.js b/test/failure-window.test.js new file mode 100644 index 0000000..ef5a208 --- /dev/null +++ b/test/failure-window.test.js @@ -0,0 +1,114 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const http = require('node:http'); +const os = require('node:os'); +const path = require('node:path'); +const test = require('node:test'); +const { mainFixture, tick } = require('./main-fixture'); +const { createLaunchController } = require('../dist/main/launchController'); +const { createRuntimeTarget } = require('../dist/main/targets/runtimeTarget'); +const gateway = require('../dist/main/targets/runtimeGateway'); +const preflight = require('../dist/main/targets/preflight'); +const probe = require('../dist/main/targets/runtimeProbe'); +const { runtimeDataDir, runtimeComponentsPath, runtimeHostLockPath } = require('../dist/main/targets/runtimePaths'); + +const portMessage = 'Another app is preventing Home from starting; ElastOS will not close the other app.'; + +async function fixture(t, staleLock = false) { + for (const [name, value] of [['platform', 'darwin'], ['arch', 'arm64']]) { + const original = Object.getOwnPropertyDescriptor(process, name); + Object.defineProperty(process, name, { value }); + t.after(() => Object.defineProperty(process, name, original)); + } + // Everything on disk belongs to this clone. The foreign listener uses an OS-assigned port. + const home = fs.mkdtempSync(path.join(__dirname, '.failure-home-')); + const directories = [home, path.join(home, 'Library'), path.join(home, 'Library', 'Application Support'), runtimeDataDir('darwin', home)]; + for (const directory of directories.slice(1)) fs.mkdirSync(directory); + const data = directories.at(-1); + const components = runtimeComponentsPath(data); + const lock = runtimeHostLockPath(data); + const lockText = JSON.stringify({ pid: 4242, role: 'gateway', addr: '127.0.0.1:8090' }); + fs.writeFileSync(components, '{}'); + if (staleLock) fs.writeFileSync(lock, lockText); + t.after(() => { + if (fs.existsSync(lock)) fs.unlinkSync(lock); + fs.unlinkSync(components); + for (const directory of directories.reverse()) fs.rmdirSync(directory); + }); + t.mock.method(os, 'homedir', () => home); + t.mock.method(process, 'kill', () => { throw new Error('No fixture process is alive or may be signalled'); }); + t.mock.method(preflight, 'collectPreflight', async () => ({ ok: true, checks: [{ id: 'port', level: 'pass', message: '' }] })); + t.mock.method(probe, 'probeRuntimeInstallation', async () => ({ kind: 'version', version: '2.0.0' })); + t.mock.method(probe, 'findRuntimeBinary', () => path.join(home, 'elastos')); + t.mock.method(require('../dist/main/targets/runtimePin'), 'loadActiveRuntimePin', () => ({ version: '2.0.0' })); + + const listener = http.createServer((_request, response) => response.end('OK')); + await new Promise((resolve, reject) => { listener.once('error', reject); listener.listen(0, '127.0.0.1', resolve); }); + t.after(() => new Promise(resolve => listener.close(resolve))); + const url = `http://127.0.0.1:${listener.address().port}`; + t.mock.method(gateway, 'probeGatewayHealth', async () => ({ status: 200, body: 'OK' })); + t.mock.method(gateway, 'confirmInstalledGateway', async () => false); + t.mock.method(preflight, 'portBusy', async () => listener.listening); + t.mock.method(gateway, 'createDefaultGatewaySupervisor', (_file, platform, lifetime) => gateway.createGatewaySupervisor({ + platform, lifetime, binary: path.join(home, 'elastos'), args: ['home', '--browser'], adoptForControls: true, + fetchHealth: () => gateway.probeGatewayHealth(), adoptInstalled: async () => null, + spawn() { throw new Error('Must not spawn while a foreign listener is running'); }, + sleep: async () => {}, now: Date.now, openUrl() {}, log() {}, + })); + t.mock.method(require('../dist/main/targets'), 'createLaunchTarget', () => createRuntimeTarget('darwin', 'arm64', { + shuttingDown: false, shutdown() { this.shuttingDown = true; }, + })); + const launch = createLaunchController({ env: {} }); + launch.target.openInBrowser = () => {}; + launch.getOpenAtLogin = () => false; + launch.resumeInstallPlan = async () => 'none'; + launch.checkForUpdate = async () => null; + return { launch, listener, url, lock, lockText }; +} + +for (const staleLock of [true, false]) { + test(`real controller startup shows its foreign-port error with ${staleLock ? 'a stale lock' : 'no lock'}`, async t => { + const { launch, listener, url, lock, lockText } = await fixture(t, staleLock); + const f = await mainFixture({ controller: launch, platform: 'darwin' }); + const state = await f.invoke('getWindowState'); + assert.equal(state.kind, 'error'); + assert.equal(state.message, portMessage); + assert.equal(state.actionLabel, 'Try Again'); + await f.invoke('retry'); + assert.equal((await f.invoke('getWindowState')).message, portMessage); + assert.equal(listener.listening, true); + assert.equal(await (await fetch(url)).text(), 'OK'); + assert.equal(fs.existsSync(lock), staleLock); + if (staleLock) assert.equal(fs.readFileSync(lock, 'utf8'), lockText); + f.app.emit('before-quit', { preventDefault() {} }); + for (let attempt = 0; attempt < 100 && !f.calls.includes('quit'); attempt++) await tick(); + assert.ok(f.calls.includes('quit')); + assert.equal(listener.listening, true); + assert.equal(await (await fetch(url)).text(), 'OK'); + assert.ok(process.kill.mock.calls.every(call => call.arguments[1] === 0)); + }); +} + +test('real controller action screen uses the caught error even when a later action replaces lastError', async t => { + const { launch } = await fixture(t); + launch.target.getStatus = async () => 'running'; + const f = await mainFixture({ controller: launch, platform: 'darwin' }); + launch.target.stop = async () => { throw new Error('Another program is answering on port 8090. Home was not adopted.'); }; + launch.target.start = async () => { throw new Error('The download failed.'); }; + const collect = preflight.collectPreflight; + t.mock.method(preflight, 'collectPreflight', async () => { + await assert.rejects(launch.start(), /download failed/); + return collect(); + }); + await f.click('Stop Home'); + assert.equal((await f.invoke('getWindowState')).message, portMessage); + assert.equal((await launch.describeFailure()).message, 'The download stopped.'); + assert.equal((await launch.describeFailure('Another program is answering on port 8090.')).message, portMessage); +}); + +test('main publishes the actual logger path for e2e diagnostics', async () => { + delete global.__elastosLogPath; + await mainFixture(); + assert.equal(global.__elastosLogPath, '/fixture/main.log'); + delete global.__elastosLogPath; +}); diff --git a/test/helpers/signed-release.js b/test/helpers/signed-release.js new file mode 100644 index 0000000..1af8d3d --- /dev/null +++ b/test/helpers/signed-release.js @@ -0,0 +1,29 @@ +const crypto = require('node:crypto'); +const { releaseHeadCid, canonicalJson } = require('../../dist/main/targets/releaseHead'); +const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519'); +const publicBytes = publicKey.export({ format: 'der', type: 'spki' }).subarray(-32); +function base58(bytes) { + let number = BigInt(`0x${bytes.toString('hex')}`); + let out = ''; + const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + while (number) { out = alphabet[Number(number % 58n)] + out; number /= 58n; } + return out; +} +const FIXTURE_DID = `did:key:z${base58(Buffer.concat([Buffer.from([0xed, 0x01]), publicBytes]))}`; +const FIXTURE_VERSION = '2.0.0'; +const FIXTURE_RELEASE_CID = 'release-a'; +const SCRIPT = '#!/bin/bash\necho stamped-installer\n'; +const SCRIPT_SHA = crypto.createHash('sha256').update(SCRIPT).digest('hex'); +function signed(payload, domain) { + const digest = crypto.createHash('sha256').update(`${domain}\0${canonicalJson(payload)}`).digest(); + return JSON.stringify({ payload, signature: crypto.sign(null, digest, privateKey).toString('hex'), signer_did: FIXTURE_DID }); +} +const MANIFEST = signed({ schema: 'elastos.release/v1', version: FIXTURE_VERSION, channel: 'stable', installer_sha256: SCRIPT_SHA }, 'elastos.release.v1'); +function signedHead(overrides = {}, manifest = MANIFEST) { + return signed({ schema: 'elastos.release.head/v1', channel: 'stable', version: FIXTURE_VERSION, + latest_release_cid: FIXTURE_RELEASE_CID, release_sha256: crypto.createHash('sha256').update(manifest).digest('hex'), ...overrides }, 'elastos.release.head.v1'); +} +const SIGNED_HEAD = signedHead(); +const FIXTURE_HEAD_CID = releaseHeadCid(SIGNED_HEAD); + +module.exports = { FIXTURE_DID, FIXTURE_VERSION, FIXTURE_RELEASE_CID, SCRIPT, SCRIPT_SHA, MANIFEST, SIGNED_HEAD, FIXTURE_HEAD_CID, signed, signedHead }; diff --git a/test/host-tools.test.js b/test/host-tools.test.js index a733009..4bb4878 100644 --- a/test/host-tools.test.js +++ b/test/host-tools.test.js @@ -13,6 +13,7 @@ const { BASH_MESSAGE, MUSL_MESSAGE, PYTHON_VERIFY_MESSAGE, + detectLinuxLibc, prepareInstallerEnvironment, } = require('../dist/main/targets/hostTools'); const { evaluatePreflight } = require('../dist/main/targets/preflight'); @@ -176,7 +177,7 @@ test('a hidden or stub python is provisioned and a working one is reused', async assert.equal(downloads, 1); const python = spawnSync('python3', ['-c', ''], { env: prepared.env, encoding: 'utf8' }); assert.equal(python.status, 0); - const which = spawnSync('bash', ['-lc', 'command -v python3'], { env: prepared.env, encoding: 'utf8' }); + const which = spawnSync('/bin/bash', ['-c', 'command -v python3'], { env: prepared.env, encoding: 'utf8' }); assert.match(which.stdout, /\/python\/bin\/python3\n$/); const sum = spawnSync('sha256sum', [path.join(dir, 'src', 'python', 'lib', 'd'.repeat(90), 'mod.py')], { env: prepared.env, @@ -258,6 +259,11 @@ test('a tampered python archive is refused and nothing is unpacked', async () => assert.equal(fs.existsSync(path.join(home, '.elastos-launcher', 'python', 'python', 'bin', 'python3')), false); }); +test('a glibc computer that also has a musl loader is not musl', () => { + assert.equal(detectLinuxLibc('linux', () => ['ld-musl-aarch64.so.1', 'ld-linux-aarch64.so.1']), 'glibc'); + assert.equal(detectLinuxLibc('linux', () => ['ld-musl-x86_64.so.1']), 'musl'); +}); + test('musl and a missing shell block install, and a bad python hash is refused', async () => { const dir = tempDir(); await assert.rejects( @@ -375,3 +381,24 @@ test('the installer path never asks for Xcode Command Line Tools', () => { const hit = files.filter((file) => fs.readFileSync(file, 'utf8').includes('xcode-select')); assert.deepEqual(hit, []); }); + +test('the installer curl shim uses verified metadata even if the publisher moves', async (t) => { + const { installerFetch } = require('../dist/main/targets/hostToolEntry'); + const dir = tempDir(); + const file = path.join(dir, 'release-metadata.json'); + const url = 'https://publisher.example/release-head.json'; + const bytes = JSON.stringify({ [url]: 'verified head bytes' }); + fs.writeFileSync(file, bytes); + const names = ['ELASTOS_LAUNCHER_METADATA_PATH', 'ELASTOS_LAUNCHER_METADATA_SHA256']; + const saved = names.map((name) => process.env[name]); + process.env[names[0]] = file; + process.env[names[1]] = crypto.createHash('sha256').update(bytes).digest('hex'); + t.after(() => { + names.forEach((name, i) => { if (saved[i] === undefined) delete process.env[name]; else process.env[name] = saved[i]; }); + fs.rmSync(dir, { recursive: true }); + }); + t.mock.method(global, 'fetch', async () => { throw new Error('publisher now serves an older head'); }); + assert.equal(await (await installerFetch(url)).text(), 'verified head bytes'); + fs.writeFileSync(file, JSON.stringify({ [url]: 'older head' })); + await assert.rejects(() => installerFetch(url), /changed after verification/); +}); diff --git a/test/install-start.test.js b/test/install-start.test.js new file mode 100644 index 0000000..f1672e2 --- /dev/null +++ b/test/install-start.test.js @@ -0,0 +1,81 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { mainFixture, tick } = require('./main-fixture'); +const { runtimeFixtures } = require('./controller-fixture'); +const defer = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; }; + +function fixture(t, platform) { + const { launch, runtime } = runtimeFixtures(t, platform)(); + let installed = false; + t.mock.method(require('../dist/main/targets/runtimeInstall'), 'installRuntimeOnThisComputer', async () => { + runtime.calls.push('install'); installed = true; + }); + launch.target.getStatus = async () => !installed ? 'not-installed' : runtime.running ? 'running' : 'stopped'; + launch.setOpenAtLogin = () => {}; + launch.finishResumeInstall = ok => runtime.calls.push(['resume', ok]); + return { launch, runtime }; +} + +for (const platform of ['darwin', 'linux', 'win32']) { + for (const path of ['Install', 'Reset then Install', 'setup resume']) { + test(`${platform} real controller: ${path} starts Home before declaring ready`, async t => { + const { launch, runtime } = fixture(t, platform); + const start = defer(); + runtime.wait.start = () => start.promise; + if (path === 'setup resume') launch.resumeInstallPlan = async () => 'install'; + const f = await mainFixture({ controller: launch, platform }); + let installing; + try { + if (path === 'Reset then Install') { + launch.resetRuntime = async () => {}; + f.answers.push({ response: 1, checkboxChecked: false }); + await f.click('Reset ElastOS…'); + } + if (path !== 'setup resume') installing = f.invoke('install', false); + await tick(); + assert.deepEqual(await f.invoke('getWindowState'), { kind: 'progress', message: 'Starting Home' }); + assert.deepEqual(runtime.calls, ['install', 'start']); + start.resolve(); + await installing; await tick(); await tick(); + assert.equal(runtime.running, true); + assert.deepEqual(await f.invoke('getWindowState'), { kind: 'install', ready: true, message: 'Home is ready.' }); + if (path === 'setup resume') assert.deepEqual(runtime.calls.at(-1), ['resume', true]); + } finally { start.resolve(); await installing; await tick(); } + }); + } + + test(`${platform} real controller: start failure offers Try Again and retry starts Home`, async t => { + const { launch, runtime } = fixture(t, platform); + runtime.wait.start = async () => { throw new Error('Home start failed'); }; + const f = await mainFixture({ controller: launch, platform }); + await f.invoke('install', false); + const state = await f.invoke('getWindowState'); + assert.equal(state.kind, 'error'); + assert.equal(state.actionLabel, 'Try Again'); + assert.notEqual(state.ready, true); + delete runtime.wait.start; + await f.invoke('retry'); + assert.equal(runtime.running, true); + assert.equal((await f.invoke('getWindowState')).ready, true); + }); + + for (const during of ['install', 'start']) { + test(`${platform} real controller: Quit during ${during} never publishes ready or restarts Home`, async t => { + const { launch, runtime } = fixture(t, platform); + const work = defer(); + if (during === 'install') t.mock.method(require('../dist/main/targets/runtimeInstall'), 'installRuntimeOnThisComputer', () => work.promise); + else runtime.wait.start = () => work.promise; + const f = await mainFixture({ controller: launch, platform }); + const installing = f.invoke('install', false); + await tick(); + const atQuit = runtime.calls.length; + f.app.emit('before-quit', { preventDefault() {} }); + work.resolve(); + await installing; await tick(); await tick(); + assert.equal(runtime.calls.slice(atQuit).includes('start'), false); + assert.equal(runtime.running, false); + assert.notEqual((await f.invoke('getWindowState')).ready, true); + assert.ok(f.calls.includes('quit')); + }); + } +} diff --git a/test/installer-ux.test.js b/test/installer-ux.test.js index e300494..dfebc8f 100644 --- a/test/installer-ux.test.js +++ b/test/installer-ux.test.js @@ -13,19 +13,9 @@ const { publisherHost, publisherOffline, } = require('../dist/main/targets/preflight'); -const { linuxAutostartFile, syncLinuxAutostart } = require('../dist/main/targets/openAtLogin'); -const flow = require('../src/renderer/flow.js'); - -const base = { - platform: 'linux', - arch: 'x64', - freeBytes: DISK_FLOOR_BYTES, - portBusy: false, - healthOk: false, - offline: false, - wsl: false, - kvm: true, -}; +const { linuxAutostartFile, linuxAutostartExecPath, syncLinuxAutostart } = require('../dist/main/targets/openAtLogin'); + +const base = { platform: 'linux', arch: 'x64', freeBytes: DISK_FLOOR_BYTES, portBusy: false, healthOk: false, offline: false, wsl: false, kvm: true }; test('preflight blocks disk, offline, a busy port, and Intel Mac', () => { assert.equal(evaluatePreflight(base).ok, true); @@ -35,10 +25,10 @@ test('preflight blocks disk, offline, a busy port, and Intel Mac', () => { assert.match(disk.checks.find((check) => check.id === 'disk').message, /2 GB/); const offline = evaluatePreflight({ ...base, offline: true }); - assert.match(offline.checks.find((check) => check.id === 'network').message, /offline/); + assert.match(offline.checks.find((check) => check.id === 'network').message, /internet/); const port = evaluatePreflight({ ...base, portBusy: true, healthOk: false }); - assert.match(port.checks.find((check) => check.id === 'port').message, /8090/); + assert.match(port.checks.find((check) => check.id === 'port').message, /Another app/); const already = evaluatePreflight({ ...base, portBusy: true, healthOk: true }); assert.equal(already.checks.find((check) => check.id === 'port').level, 'pass'); @@ -102,26 +92,19 @@ test('sign-in launch writes a desktop file and can remove it', () => { }; const written = syncLinuxAutostart(true, '/home/tester', '/usr/bin/elastos', fs); assert.match(files.get(written), /Name=ElastOS/); - assert.match(linuxAutostartFile('/usr/bin/elastos'), /Exec=\/usr\/bin\/elastos/); + assert.match(files.get(written), /X-GNOME-Autostart-enabled=true/); + assert.match(linuxAutostartFile('/usr/bin/elastos'), /Exec=\/usr\/bin\/elastos --login\n/); + assert.equal( + linuxAutostartExecPath({ APPIMAGE: '/home/me/ElastOS.AppImage' }, '/tmp/.mount_abc/elastos'), + '/home/me/ElastOS.AppImage', + ); + assert.equal(linuxAutostartExecPath({ APPIMAGE: ' ' }, '/usr/bin/elastos'), '/usr/bin/elastos'); + assert.match(linuxAutostartFile('/home/me/ElastOS App.AppImage'), /Exec="\/home\/me\/ElastOS App\.AppImage"/); + assert.match(linuxAutostartFile('/home/me/ElastOS-$APP.AppImage'), /Exec="\/home\/me\/ElastOS-\\\$APP\.AppImage"/); assert.equal(syncLinuxAutostart(false, '/home/tester', '/usr/bin/elastos', fs), null); assert.equal(files.size, 0); }); -test('the install button is the primary action until the computer is healthy', () => { - assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'not-installed', busy: false }).label, 'Install'); - assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'running', busy: false }).label, 'Open my computer'); - assert.equal(flow.primaryAction({ targetId: 'runtime', status: 'error', busy: false }).id, 'retry'); - assert.match(flow.firstRunCopy('runtime', 'not-installed'), /One button/); - assert.equal(flow.firstRunCopy('runtime', 'running'), ''); - const copy = flow.confirmCopy('runtime', []); - assert.match(copy.title, /ElastOS/); - assert.match(copy.body, /removes the ElastOS program/); - const steps = flow.stepStates('Downloading ElastOS (about 1 minute)'); - assert.equal(steps[1].state, 'active'); - assert.equal(steps[0].state, 'done'); - assert.equal(flow.urlLabel('http://localhost:8090/home/'), 'localhost:8090/home'); -}); - test('the port check covers 127.0.0.1 and ::1, and a host without IPv6 checks 127.0.0.1 only', async () => { const asked = []; const answer = (map) => async (port, host) => { asked.push(host); return map[host]; }; @@ -157,18 +140,19 @@ test('preflight blocks when localhost does not point to this computer', () => { assert.equal(evaluatePreflight(base).checks.some((check) => check.id === 'localhost'), false); }); -test('Windows shows that its Browser is not available yet, and only Windows', () => { - const { browserNote, WINDOWS_BROWSER_MESSAGE } = require('../dist/main/targets/runtimeSupport'); - assert.equal(WINDOWS_BROWSER_MESSAGE, 'Browser is not available on this computer yet.'); - assert.equal(browserNote('win32'), WINDOWS_BROWSER_MESSAGE); - for (const platform of ['darwin', 'linux']) assert.equal(browserNote(platform), null); - assert.equal(flow.browserNoteText({ browserNote: WINDOWS_BROWSER_MESSAGE }), WINDOWS_BROWSER_MESSAGE); - assert.equal(flow.browserNoteText({ browserNote: null }), ''); - assert.equal(flow.browserNoteText(undefined), ''); - const html = fs.readFileSync(path.join(__dirname, '..', 'src', 'renderer', 'index.html'), 'utf8'); - assert.match(html, /