diff --git a/.dockerignore b/.dockerignore index e2694b4..0550bfc 100644 --- a/.dockerignore +++ b/.dockerignore @@ -4,4 +4,5 @@ dist release EchoionWeb/frontend/node_modules EchoionWeb/frontend/web-dist +components docs diff --git a/.gitea/RELEASING.md b/.gitea/RELEASING.md index 0e7bf94..1d3a23c 100644 --- a/.gitea/RELEASING.md +++ b/.gitea/RELEASING.md @@ -58,44 +58,50 @@ Enable Actions and add these repository secrets: | Secret | Purpose | | --- | --- | -| `RELEASE_CHECKOUT_SSH_KEY` | Read-only key used for the root checkout. | -| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot. It needs read access to the component repositories plus release/tag and `release-feed` write access in this repository. | +| `RELEASE_CHECKOUT_SSH_KEY` | Read-only SSH key used for root, component, and `release-feed` checkouts. Grant it access to every private component repository before cutover. | +| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot. It needs read access to every component repository plus release/tag and `release-feed` write access in this repository. | | `RELEASE_TAG_ALLOWED_SIGNERS` | Complete OpenSSH `allowed_signers` lines for maintainers allowed to publish `v*` tags. | | `RELEASE_FEED_ED25519_PRIVATE_KEY` | PEM private key matching `release-keys/echoion-release-2026-07.pub.pem`. Preserve its newlines. | -Component checkouts use the release PAT with `persist-credentials: false`, so -the credential is removed before repository scripts run. The feed signing key -must not be stored in Git, runner images, Actions variables, or release assets. +Component checkouts use SSH with `persist-credentials: false`. Release API +operations use the bot PAT, but Git fetches and pushes never rewrite remotes to +HTTPS. The feed signing key must not be stored in Git, runner images, Actions +variables, or release assets. ## Independent component repositories -Echoion does not use Git submodules. `components.lock.json` is the immutable -checkout manifest for `EchoionApi`, `EchoionCore`, and `EchoionDesktop`. CMake -uses a component already present beside the root checkout; otherwise it fetches -the locked revision. All three Gitea workflows check out those revisions as -ordinary repositories before entering Docker. +Echoion does not use Git submodules. `components.json` describes the nine +independent repositories: `EchoionApi`, `EchoionHost`, `EchoionCore`, +`EchoionWeb`, `EchoionStandalone`, `EchoionUpdater`, `EchoionDesktop`, +`EchoionPluginUrlShortenerInternal`, and +`EchoionPluginUrlShortenerExternal`. `components.lock.json` is the immutable +release checkout manifest. All Gitea workflows check out the locked revisions +as ordinary SSH repositories before entering Docker. For a new developer checkout: ```bash -python3 scripts/sync-components.py +scripts/prepare-release.sh --workspace .. ``` -After changing a component, commit and push that component first, then refresh -and commit the root lock: +For ordinary development CMake follows each component's `main` branch unless a +`CPM__SOURCE` override is supplied. Release builds use the exact +lock. After changing a component, make a signed commit and push it over SSH +first, then refresh and commit the root lock: ```bash -python3 scripts/sync-components.py --record +scripts/prepare-release.sh --workspace .. git add components.lock.json +git commit -S -m 'Release: lock Echoion 2.0.0 components' ``` -`--record` refuses dirty component repositories, so a lock can never point at -uncommitted source. `--update` moves existing clean component checkouts to the -locked revisions. Product version changes are separate: edit only +The preparer refuses dirty, inaccessible, missing, non-fast-forward, or +version/tag-inconsistent component repositories, so a lock can never point at +unpublished source. Product version changes are separate: edit only `project(Echoion VERSION ...)` in root `CMakeLists.txt`; orchestrated component builds and release overrides inherit that value. A stable or beta release tag -must have the same numeric base as this CMake version, so `v1.2.3` and -`v1.2.3-rc.1` both require `project(Echoion VERSION 1.2.3 ...)`. The release +must have the same numeric base as this CMake version, so `v2.0.0` and +`v2.0.0-rc.1` both require `project(Echoion VERSION 2.0.0 ...)`. The release workflow rejects mismatches before building. Nightlies use the newer of the root CMake version and the next patch after the @@ -114,17 +120,28 @@ Gitea uses the same allowlist for tag creation and later tag changes; when immutable release tags are required, add a server-side pre-receive policy that rejects updates and deletion after creation. Protect `main` in the normal way. -The updater feed URL is: +The updater source can use the feed base: ```text -https://///raw/branch/release-feed/feeds/echoion-runtime.json +https://///raw/branch/release-feed ``` -The embedded updater trust configuration is represented by -`release-keys/official-update-keys.json`. `scripts/release.sh` validates and +or an exact channel catalog: + +```text +https://///raw/branch/release-feed/feeds/stable/catalog.json +``` + +The catalog resolves immutable component documents under +`feeds///.json` and plugin documents under +`feeds//plugins//.json`. The embedded updater +trust configuration is represented by +`.gitea/release-keys/official-update-keys.json`. `scripts/release.sh` validates and embeds that JSON automatically. Release workflows also pass the HTTPS -`release-feed` branch URL through `--official-update-feed-url`, so a fresh -installation has a signed official source without operator-side duplication. +channel catalog through `--official-update-feed-url`, so a fresh installation +has a signed official source without operator-side duplication. The v1 +`feeds/echoion-runtime.json` feed is not published at the 2.0 cutover; v1 +operators must stop their service and run the signed v2 installer manually. ## Stable and beta releases @@ -136,9 +153,9 @@ for the tag: ```bash git config gpg.format ssh git config user.signingkey ~/.ssh/echoion-release-maintainer -git tag -s -a v1.2.3 -m 'Echoion 1.2.3' -test "$(git cat-file -t refs/tags/v1.2.3)" = tag -git push origin v1.2.3 +git tag -s -a v2.0.0 -m 'Echoion 2.0.0' +test "$(git cat-file -t refs/tags/v2.0.0)" = tag +git push origin v2.0.0 ``` The private-key path works without an SSH agent. A `.pub` path may be used @@ -155,8 +172,9 @@ The workflow creates or resumes a draft, replaces incomplete draft assets, uploads every file in `dist/`, downloads every asset through Gitea, checks its size and SHA-256, and only then publishes. A rerun against an already published release is read-only and succeeds only when all remote assets still -match. The signed aggregate feed is committed after release publication; a -feed failure can therefore be retried without replacing a published release. +match. The signed catalog and all component feeds are committed together after +release publication; a feed failure can therefore be retried without replacing +a published release. ## Nightly releases @@ -167,15 +185,16 @@ semantic release, nightlies use the root CMake `project(Echoion VERSION x.y.z)` value without incrementing it. Drafts, failed publications, and `nightly-*` releases do not affect the base. Nightlies use the `nightly` channel, publish as prereleases, and keep the newest 14 Gitea -releases. The aggregate feed also keeps the newest 14 distinct nightly versions -while retaining stable and beta records. Gitea materializes a missing +releases. Channel catalogs remain separate, and nightly publication never +advances stable component state. Gitea materializes a missing `nightly-*` Git tag only when the download-verified draft is published; the publisher then verifies its commit immediately and never moves an existing tag whose target differs. Stable and beta publishing require their signed tag to exist before creating a draft. If `nightly-*` is protected separately, allow the release bot to create and delete it. -Every aggregate envelope expires 45 days after generation. Scheduled +Every rolling catalog and `latest.json` envelope expires 45 days after +generation. Scheduled nightlies normally refresh it daily. Alert when the feed branch has not advanced for more than seven days, and treat 30 days without a successful signing run as urgent. @@ -204,17 +223,12 @@ openssl pkey -pubin -in echoion-release-YYYY-MM.pub.pem -outform DER | printf '\n' ``` -Add the new public key to official builds before signing any feed with it. -Keep the old public key embedded for at least one full update lifetime. During -the first signing run with the new key, pass each prior envelope key explicitly -to `aggregate_update_feed.py` as -`--trusted-existing-key OLD_KEY_ID=OLD_PUBLIC_KEY_PATH`; this permits only -verification of the old envelope and never selects the old key for signing. -Update the signing key id and public-key paths in both release workflows, add -the old-key verification argument while an old envelope may exist, and replace -the private-key secret. The merger verifies the newly generated signature -against the new committed public key before writing either output. Never print -the private key or pass it as a command-line argument. +Add the new public key to official builds before signing any feed with it and +keep the old public key embedded for at least one full update lifetime. Update +the signing key id in both release workflows and replace the private-key +secret only after the build containing both trust roots is installed broadly. +Immutable version feeds are never rewritten during rotation. Never print the +private key or pass it as a command-line argument. ## Recovery rules @@ -227,5 +241,6 @@ the private key or pass it as a command-line argument. - A failed feed push leaves the published release available but undiscoverable to auto-update. Rerun the workflow; publication verification is idempotent and the feed step will run again. -- Never edit `release-feed` manually. The merger verifies the existing - Ed25519 envelope before using any prior entries. +- Never edit `release-feed` manually. The publisher validates immutable + version feeds, replay sequences, and component state before committing the + complete transaction. diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 4920b9d..57e022f 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -1,4 +1,4 @@ -name: Container CI +name: Modular container CI on: push: @@ -22,7 +22,7 @@ jobs: docker version docker info - - name: Check out source + - name: Check out root over SSH uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: fetch-depth: 0 @@ -32,79 +32,53 @@ jobs: git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw== persist-credentials: false - - name: Read locked component repositories - id: components + - name: Verify source-free root and resolve every lock over SSH shell: bash + env: + ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} run: | set -euo pipefail - python3 - "$GITHUB_OUTPUT" <<'PY' - import json - import pathlib - import sys - - lock = json.loads(pathlib.Path("components.lock.json").read_text()) - with pathlib.Path(sys.argv[1]).open("a") as output: - for component, key in ( - ("EchoionApi", "api"), - ("EchoionCore", "core"), - ("EchoionDesktop", "desktop"), - ): - entry = lock["components"][component] - print(f"{key}_repository={entry['repository']}", file=output) - print(f"{key}_revision={entry['revision']}", file=output) - PY - - - name: Check out EchoionApi - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.api_repository }} - ref: ${{ steps.components.outputs.api_revision }} - path: EchoionApi - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false - - - name: Check out EchoionCore - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.core_repository }} - ref: ${{ steps.components.outputs.core_revision }} - path: EchoionCore - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false - - - name: Check out EchoionDesktop - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.desktop_repository }} - ref: ${{ steps.components.outputs.desktop_revision }} - path: EchoionDesktop - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false + test ! -e .gitmodules + if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }' + then + echo "root release contains a gitlink" >&2 + exit 1 + fi + scripts/ci-checkout-components.sh \ + "$PWD/components" \ + "$PWD/dependencies" + scripts/prepare-release.sh \ + --workspace "$PWD/components" \ + --check - name: Build, test, and package without starting Echoion env: - CI_VERSION: 0.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }} + CI_VERSION: 2.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }} run: | - set -eu - scripts/release.sh --version "$CI_VERSION" + set -euo pipefail + scripts/release.sh \ + --version "$CI_VERSION" \ + --component-workspace "$PWD/components" \ + --void-source "$PWD/dependencies/VoidLibrary" \ + --void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \ + --update-channel beta \ + --update-sequence "${{ gitea.run_number }}" - - name: Test release control-plane scripts + - name: Test release control-plane scripts offline shell: bash run: | - set -eu + set -euo pipefail bash scripts/tests/test-gitea-tag-verification.sh . scripts/lib/docker-daemon-path.sh docker_workspace=$(docker_daemon_path "$PWD") - docker run --rm --network none \ - --volume "$docker_workspace:/workspace:ro" \ - --workdir /workspace \ - echoion-release-builder:gcc-16.1.0 \ - python3 scripts/tests/test_aggregate_update_feed.py - docker run --rm --network none \ - --volume "$docker_workspace:/workspace:ro" \ - --workdir /workspace \ - echoion-release-builder:gcc-16.1.0 \ - python3 scripts/tests/test_gitea_release.py + for test_script in \ + scripts/tests/test_package_components.py \ + scripts/tests/test_publish_component_feeds.py \ + scripts/tests/test_gitea_release.py + do + docker run --rm --network none \ + --volume "$docker_workspace:/workspace:ro" \ + --workdir /workspace \ + echoion-release-builder:gcc-16.1.0 \ + python3 "$test_script" + done diff --git a/.gitea/workflows/nightly.yml b/.gitea/workflows/nightly.yml index b7507e3..6282f95 100644 --- a/.gitea/workflows/nightly.yml +++ b/.gitea/workflows/nightly.yml @@ -1,4 +1,4 @@ -name: Nightly release +name: Nightly modular release on: schedule: @@ -8,6 +8,10 @@ on: permissions: contents: read +concurrency: + group: echoion-release-feed + cancel-in-progress: false + jobs: publish-nightly: runs-on: ubuntu-24.04 @@ -21,7 +25,7 @@ jobs: docker version docker info - - name: Check out main + - name: Check out signed main over SSH uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: ref: main @@ -32,59 +36,26 @@ jobs: git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw== persist-credentials: false - - name: Read locked component repositories - id: components + - name: Verify root cutover and check out locked components over SSH shell: bash + env: + ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} run: | set -euo pipefail - python3 - "$GITHUB_OUTPUT" <<'PY' - import json - import pathlib - import sys + test ! -e .gitmodules + if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }' + then + echo "root release contains a gitlink" >&2 + exit 1 + fi + scripts/ci-checkout-components.sh \ + "$PWD/components" \ + "$PWD/dependencies" + scripts/prepare-release.sh \ + --workspace "$PWD/components" \ + --check - lock = json.loads(pathlib.Path("components.lock.json").read_text()) - with pathlib.Path(sys.argv[1]).open("a") as output: - for component, key in ( - ("EchoionApi", "api"), - ("EchoionCore", "core"), - ("EchoionDesktop", "desktop"), - ): - entry = lock["components"][component] - print(f"{key}_repository={entry['repository']}", file=output) - print(f"{key}_revision={entry['revision']}", file=output) - PY - - - name: Check out EchoionApi - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.api_repository }} - ref: ${{ steps.components.outputs.api_revision }} - path: EchoionApi - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false - - - name: Check out EchoionCore - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.core_repository }} - ref: ${{ steps.components.outputs.core_revision }} - path: EchoionCore - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false - - - name: Check out EchoionDesktop - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.desktop_repository }} - ref: ${{ steps.components.outputs.desktop_revision }} - path: EchoionDesktop - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false - - - name: Derive the nightly identity + - name: Derive nightly identity and URLs shell: bash env: GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} @@ -108,36 +79,37 @@ jobs: --run-number "$RUN_NUMBER" ) tag="nightly-${date_id}-${RUN_NUMBER}" - artifact="echoion-${version}-linux-x86_64.tar.zst" - url="${SERVER_URL}/${REPOSITORY}/releases/download/${tag}/${artifact}" - feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/echoion-runtime.json" python3 scripts/validate-semver.py "$version" { printf 'RELEASE_TAG=%s\n' "$tag" printf 'RELEASE_VERSION=%s\n' "$version" printf 'RELEASE_CHANNEL=nightly\n' - printf 'RELEASE_PRERELEASE=true\n' - printf 'RELEASE_ARTIFACT_URL=%s\n' "$url" - printf 'RELEASE_FEED_URL=%s\n' "$feed_url" + printf 'RELEASE_SEQUENCE=%s\n' "$RUN_NUMBER" + printf 'RELEASE_ARTIFACT_BASE_URL=%s\n' \ + "${SERVER_URL}/${REPOSITORY}/releases/download/${tag}" + printf 'RELEASE_FEED_URL=%s\n' \ + "${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/nightly/catalog.json" printf 'RELEASE_TARGET=%s\n' "$(git rev-parse HEAD)" } >>"$GITHUB_ENV" - - name: Build and test the dynamic nightly in Docker + - name: Build and test all locked repositories in Docker shell: bash run: | set -euo pipefail scripts/release.sh \ --version "$RELEASE_VERSION" \ - --update-url "$RELEASE_ARTIFACT_URL" \ + --component-workspace "$PWD/components" \ + --void-source "$PWD/dependencies/VoidLibrary" \ + --void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \ --official-update-feed-url "$RELEASE_FEED_URL" \ --update-channel nightly \ - --update-valid-days 45 + --update-sequence "$RELEASE_SEQUENCE" { printf 'Automated nightly from %s.\n\n' "$RELEASE_TARGET" printf 'This prerelease is retained for fourteen nightly runs.\n' } >"$RUNNER_TEMP/release-notes.md" - - name: Create draft, upload, download-verify, and publish + - name: Upload, download-verify, publish, and retain fourteen nightlies shell: bash env: GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} @@ -159,17 +131,6 @@ jobs: --artifacts dist \ --allow-missing-draft-tag \ --prerelease - - - name: Retain fourteen Gitea nightly releases - shell: bash - env: - GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} - API_URL: ${{ gitea.api_url }} - REPOSITORY: ${{ gitea.repository }} - run: | - set -euo pipefail - owner=${REPOSITORY%%/*} - repo=${REPOSITORY#*/} python3 scripts/gitea_release.py \ --api-url "$API_URL" \ prune-nightlies \ @@ -179,63 +140,55 @@ jobs: --keep 14 \ --protect-tag "$RELEASE_TAG" - - name: Check out the aggregate feed branch + - name: Check out release-feed over SSH uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: ref: release-feed path: feed-state - token: ${{ secrets.RELEASE_BOT_TOKEN }} - fetch-depth: 1 + fetch-depth: 0 + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + ssh-user: gitea + ssh-known-hosts: >- + git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw== - - name: Sign and push the aggregate feed last + - name: Sign and push the nightly feed transaction shell: bash env: FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }} + FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }} run: | set -euo pipefail - key="$RUNNER_TEMP/echoion-release-2026-07.pem" - payload="$RUNNER_TEMP/echoion-runtime.payload.json" - envelope="$RUNNER_TEMP/echoion-runtime.json" - trap 'rm -f -- "$key" "$payload" "$envelope"' EXIT + feed_key="$RUNNER_TEMP/echoion-feed-ed25519.pem" + commit_key="$RUNNER_TEMP/echoion-feed-commit-key" + trap 'rm -f -- "$feed_key" "$commit_key"' EXIT umask 077 - printf '%s\n' "$FEED_PRIVATE_KEY" >"$key" - chmod 0600 "$key" - openssl pkey -in "$key" -noout - mkdir -p feed-state/feeds - existing=() - if [[ -s feed-state/feeds/echoion-runtime.json ]]; then - existing+=( - --existing-envelope feed-state/feeds/echoion-runtime.json - ) - fi - python3 scripts/aggregate_update_feed.py \ - --new-payload \ - "dist/echoion-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ - --new-payload \ - "dist/echoion-core-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ - --new-payload \ - "dist/url-shortener-internal-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ - --new-payload \ - "dist/url-shortener-external-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ - "${existing[@]}" \ - --public-key \ - .gitea/release-keys/echoion-release-2026-07.pub.pem \ - --private-key "$key" \ - --key-id echoion-release-2026-07 \ + printf '%s\n' "$FEED_PRIVATE_KEY" >"$feed_key" + printf '%s\n' "$FEED_COMMIT_SIGNING_KEY" >"$commit_key" + chmod 0600 "$feed_key" "$commit_key" + python3 scripts/publish-component-feeds.py \ + --registry components.json \ + --lock components.lock.json \ + --artifacts dist/components \ + --feed-root feed-state \ + --base-url \ + "${{ gitea.server_url }}/${{ gitea.repository }}/raw/branch/release-feed" \ + --artifact-base-url "$RELEASE_ARTIFACT_BASE_URL" \ + --channel nightly \ + --sequence "$RELEASE_SEQUENCE" \ --valid-days 45 \ - --nightly-retention 14 \ - --output-payload "$payload" \ - --output-envelope "$envelope" - install -m 0644 "$payload" \ - feed-state/feeds/echoion-runtime.payload.json - install -m 0644 "$envelope" feed-state/feeds/echoion-runtime.json + --key-id echoion-release-2026-07 \ + --private-key "$feed_key" git -C feed-state config user.name 'Echoion Release Bot' git -C feed-state config user.email 'release-bot@echoion.invalid' - git -C feed-state add \ - feeds/echoion-runtime.json feeds/echoion-runtime.payload.json + git -C feed-state config gpg.format ssh + git -C feed-state config user.signingkey "$commit_key" + git -C feed-state config commit.gpgsign true + git -C feed-state add feeds/nightly state if git -C feed-state diff --cached --quiet; then exit 0 fi - git -C feed-state commit -m \ + git -C feed-state commit -S -m \ "Feed: nightly ${RELEASE_VERSION}" + git -C feed-state cat-file commit HEAD | + grep -q '^gpgsig ' git -C feed-state push origin HEAD:release-feed diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 4a82383..e82afec 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -1,4 +1,4 @@ -name: Signed release +name: Signed modular release on: push: @@ -8,6 +8,10 @@ on: permissions: contents: read +concurrency: + group: echoion-release-feed + cancel-in-progress: false + jobs: publish: runs-on: ubuntu-24.04 @@ -21,7 +25,7 @@ jobs: docker version docker info - - name: Check out the signed tag + - name: Check out the signed root tag over SSH uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: ref: ${{ gitea.ref }} @@ -32,59 +36,38 @@ jobs: git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw== persist-credentials: false - - name: Read locked component repositories - id: components + - name: Reject embedded component sources and gitlinks shell: bash run: | set -euo pipefail - python3 - "$GITHUB_OUTPUT" <<'PY' + test ! -e .gitmodules + if git ls-files -s | awk '$1 == "160000" { found=1 } END { exit !found }' + then + echo "root release contains a gitlink" >&2 + exit 1 + fi + python3 - <<'PY' import json import pathlib - import sys - - lock = json.loads(pathlib.Path("components.lock.json").read_text()) - with pathlib.Path(sys.argv[1]).open("a") as output: - for component, key in ( - ("EchoionApi", "api"), - ("EchoionCore", "core"), - ("EchoionDesktop", "desktop"), - ): - entry = lock["components"][component] - print(f"{key}_repository={entry['repository']}", file=output) - print(f"{key}_revision={entry['revision']}", file=output) + components = json.loads(pathlib.Path("components.json").read_text()) + embedded = [ + name for name in components["components"] + if pathlib.Path(name).exists() + ] + if embedded: + raise SystemExit(f"embedded component sources: {embedded}") PY - - name: Check out EchoionApi - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.api_repository }} - ref: ${{ steps.components.outputs.api_revision }} - path: EchoionApi - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false + - name: Check out every locked component and dependency over SSH + shell: bash + env: + ECHOION_COMPONENT_SSH_KEY: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + run: >- + scripts/ci-checkout-components.sh + "$PWD/components" + "$PWD/dependencies" - - name: Check out EchoionCore - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.core_repository }} - ref: ${{ steps.components.outputs.core_revision }} - path: EchoionCore - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false - - - name: Check out EchoionDesktop - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - repository: ${{ steps.components.outputs.desktop_repository }} - ref: ${{ steps.components.outputs.desktop_revision }} - path: EchoionDesktop - fetch-depth: 1 - token: ${{ secrets.RELEASE_BOT_TOKEN }} - persist-credentials: false - - - name: Verify protected annotated SSH tag + - name: Verify protected annotated SSH tag and release lock shell: bash env: TAG: ${{ gitea.ref_name }} @@ -112,6 +95,9 @@ jobs: --notes-output "$RUNNER_TEMP/release-notes.md" ) printf 'RELEASE_TARGET=%s\n' "$target_commit" >>"$GITHUB_ENV" + scripts/prepare-release.sh \ + --workspace "$PWD/components" \ + --check owner=${REPOSITORY%%/*} repo=${REPOSITORY#*/} python3 scripts/gitea_release.py \ @@ -121,13 +107,14 @@ jobs: --repo "$repo" \ --required-pattern 'v*' - - name: Derive the stable or beta release + - name: Derive release channel and URLs shell: bash env: TAG: ${{ gitea.ref_name }} API_URL: ${{ gitea.api_url }} SERVER_URL: ${{ gitea.server_url }} REPOSITORY: ${{ gitea.repository }} + RUN_NUMBER: ${{ gitea.run_number }} run: | set -euo pipefail version=${TAG#v} @@ -140,39 +127,37 @@ jobs: --cmake-file CMakeLists.txt ) tag_base=${version%%[-+]*} - if [[ "$tag_base" != "$project_version" ]]; then - printf 'release tag %s does not match root CMake project version %s\n' \ - "$TAG" "$project_version" >&2 - exit 1 - fi + test "$tag_base" = "$project_version" channel=stable prerelease=false if [[ "$version" == *-* ]]; then channel=beta prerelease=true fi - artifact="echoion-${version}-linux-x86_64.tar.zst" - url="${SERVER_URL}/${REPOSITORY}/releases/download/${TAG}/${artifact}" - feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/echoion-runtime.json" + feed_url="${SERVER_URL}/${REPOSITORY}/raw/branch/release-feed/feeds/${channel}/catalog.json" + artifact_url="${SERVER_URL}/${REPOSITORY}/releases/download/${TAG}" { printf 'RELEASE_TAG=%s\n' "$TAG" printf 'RELEASE_VERSION=%s\n' "$version" printf 'RELEASE_CHANNEL=%s\n' "$channel" printf 'RELEASE_PRERELEASE=%s\n' "$prerelease" - printf 'RELEASE_ARTIFACT_URL=%s\n' "$url" + printf 'RELEASE_SEQUENCE=%s\n' "$RUN_NUMBER" + printf 'RELEASE_ARTIFACT_BASE_URL=%s\n' "$artifact_url" printf 'RELEASE_FEED_URL=%s\n' "$feed_url" } >>"$GITHUB_ENV" - - name: Build and test the dynamic release in Docker + - name: Build, test, and package all locked repositories in Docker shell: bash run: | set -euo pipefail scripts/release.sh \ --version "$RELEASE_VERSION" \ - --update-url "$RELEASE_ARTIFACT_URL" \ + --component-workspace "$PWD/components" \ + --void-source "$PWD/dependencies/VoidLibrary" \ + --void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \ --official-update-feed-url "$RELEASE_FEED_URL" \ --update-channel "$RELEASE_CHANNEL" \ - --update-valid-days 45 + --update-sequence "$RELEASE_SEQUENCE" - name: Create draft, upload, download-verify, and publish shell: bash @@ -200,63 +185,56 @@ jobs: --artifacts dist \ "${prerelease[@]}" - - name: Check out the aggregate feed branch + - name: Check out the protected release-feed branch over SSH uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 with: ref: release-feed path: feed-state - token: ${{ secrets.RELEASE_BOT_TOKEN }} - fetch-depth: 1 + fetch-depth: 0 + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + ssh-user: gitea + ssh-known-hosts: >- + git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw== - - name: Sign and push the aggregate feed last + - name: Sign and push the complete channel feed transaction shell: bash env: FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }} + FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }} run: | set -euo pipefail - key="$RUNNER_TEMP/echoion-release-2026-07.pem" - payload="$RUNNER_TEMP/echoion-runtime.payload.json" - envelope="$RUNNER_TEMP/echoion-runtime.json" - trap 'rm -f -- "$key" "$payload" "$envelope"' EXIT + feed_key="$RUNNER_TEMP/echoion-feed-ed25519.pem" + commit_key="$RUNNER_TEMP/echoion-feed-commit-key" + trap 'rm -f -- "$feed_key" "$commit_key"' EXIT umask 077 - printf '%s\n' "$FEED_PRIVATE_KEY" >"$key" - chmod 0600 "$key" - openssl pkey -in "$key" -noout - mkdir -p feed-state/feeds - existing=() - if [[ -s feed-state/feeds/echoion-runtime.json ]]; then - existing+=( - --existing-envelope feed-state/feeds/echoion-runtime.json - ) - fi - python3 scripts/aggregate_update_feed.py \ - --new-payload \ - "dist/echoion-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ - --new-payload \ - "dist/echoion-core-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ - --new-payload \ - "dist/url-shortener-internal-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ - --new-payload \ - "dist/url-shortener-external-${RELEASE_VERSION}-linux-x86_64.update-payload.json" \ - "${existing[@]}" \ - --public-key \ - .gitea/release-keys/echoion-release-2026-07.pub.pem \ - --private-key "$key" \ - --key-id echoion-release-2026-07 \ + printf '%s\n' "$FEED_PRIVATE_KEY" >"$feed_key" + printf '%s\n' "$FEED_COMMIT_SIGNING_KEY" >"$commit_key" + chmod 0600 "$feed_key" "$commit_key" + openssl pkey -in "$feed_key" -noout + python3 scripts/publish-component-feeds.py \ + --registry components.json \ + --lock components.lock.json \ + --artifacts dist/components \ + --feed-root feed-state \ + --base-url \ + "${{ gitea.server_url }}/${{ gitea.repository }}/raw/branch/release-feed" \ + --artifact-base-url "$RELEASE_ARTIFACT_BASE_URL" \ + --channel "$RELEASE_CHANNEL" \ + --sequence "$RELEASE_SEQUENCE" \ --valid-days 45 \ - --nightly-retention 14 \ - --output-payload "$payload" \ - --output-envelope "$envelope" - install -m 0644 "$payload" \ - feed-state/feeds/echoion-runtime.payload.json - install -m 0644 "$envelope" feed-state/feeds/echoion-runtime.json + --key-id echoion-release-2026-07 \ + --private-key "$feed_key" git -C feed-state config user.name 'Echoion Release Bot' git -C feed-state config user.email 'release-bot@echoion.invalid' - git -C feed-state add \ - feeds/echoion-runtime.json feeds/echoion-runtime.payload.json + git -C feed-state config gpg.format ssh + git -C feed-state config user.signingkey "$commit_key" + git -C feed-state config commit.gpgsign true + git -C feed-state add feeds state if git -C feed-state diff --cached --quiet; then exit 0 fi - git -C feed-state commit -m \ + git -C feed-state commit -S -m \ "Feed: ${RELEASE_CHANNEL} ${RELEASE_VERSION}" + git -C feed-state cat-file commit HEAD | + grep -q '^gpgsig ' git -C feed-state push origin HEAD:release-feed diff --git a/.gitignore b/.gitignore index 1e6e55e..7130fa1 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,10 @@ AGENTS.md /EchoionApi/ /EchoionCore/ /EchoionDesktop/ +/EchoionHost/ +/EchoionStandalone/ +/EchoionUpdater/ +/EchoionWeb/ +/EchoionPluginUrlShortenerInternal/ +/EchoionPluginUrlShortenerExternal/ +/components/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 4153fed..a7a7ace 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 4.0.0) -project(Echoion VERSION 1.0.7 LANGUAGES CXX) +project(Echoion VERSION 2.0.0 LANGUAGES CXX) include(GNUInstallDirs) include(cmake/DependencyLock.cmake) @@ -8,15 +8,8 @@ include(cmake/DependencyLock.cmake) # component project consumes this value when orchestrated by Echoion; their # standalone fallback is intentionally 0.0.0 and is never used for a product # release. -if(DEFINED ECHOION_RELEASE_VERSION AND - NOT ECHOION_RELEASE_VERSION STREQUAL "") - set(ECHOION_COMPONENT_VERSION "${ECHOION_RELEASE_VERSION}") - string(REGEX REPLACE "[-+].*$" "" - ECHOION_PRODUCT_VERSION "${ECHOION_RELEASE_VERSION}") -else() - set(ECHOION_PRODUCT_VERSION "${PROJECT_VERSION}") - set(ECHOION_COMPONENT_VERSION "${PROJECT_VERSION}") -endif() +set(ECHOION_PRODUCT_VERSION "${PROJECT_VERSION}") +set(ECHOION_COMPONENT_VERSION "${PROJECT_VERSION}") # Default to a Release build when the developer/CI did not pick a config. # Without this, single-config generators leave CMAKE_BUILD_TYPE empty and GCC @@ -113,7 +106,7 @@ CPMAddPackage( # which CPM honours over the git checkout below. CPMAddPackage( NAME Void - GIT_REPOSITORY https://git.faumaray.ru/void/voidlibrary.git + GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidlibrary.git # Keep clean/container releases reproducible. CPM_Void_SOURCE still # overrides this revision for local dependency development. GIT_TAG ${ECHOION_VOID_REVISION} @@ -126,7 +119,7 @@ CPMAddPackage( # -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak CPMAddPackage( NAME VoidTeamspeak - GIT_REPOSITORY https://git.faumaray.ru/void/voidteamspeak.git + GIT_REPOSITORY ssh://gitea@git.faumaray.ru/void/voidteamspeak.git # This revision supplies the typed administration API used by Standalone. GIT_TAG ${ECHOION_VOID_TEAMSPEAK_REVISION} OPTIONS @@ -182,12 +175,17 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON) # Options option(BUILD_API "Build EchoionApi" ON) +option(BUILD_HOST "Build EchoionHost module loader" ON) option(BUILD_CORE "Build EchoionCore" ON) option(BUILD_DESKTOP "Build EchoionDesktop" ON) option(BUILD_WEB "Build EchoionWeb browser dashboard" ON) option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON) +option(BUILD_UPDATER "Build EchoionUpdater lifecycle helper" ON) option(BUILD_FIRST_PARTY_PLUGINS "Build bundled Echoion extension plugins" ON) option(BUILD_TESTS "Build tests" OFF) +set(ECHOION_COMPONENT_WORKSPACE + "${CMAKE_CURRENT_SOURCE_DIR}/.." + CACHE PATH "Directory containing permanent Echoion component repositories") if(BUILD_TESTS) enable_testing() @@ -196,17 +194,22 @@ endif() # Find packages find_package(Threads REQUIRED) -# Add subdirectories +# All component source directories come from CPM. Local development can set +# CPM__SOURCE; normal development follows main; release builds use +# exact components.lock.json revisions. +set(ECHOION_ORCHESTRATOR_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + if(BUILD_API) echoion_add_component(EchoionApi) endif() if(BUILD_FIRST_PARTY_PLUGINS) - add_subdirectory(plugins) + echoion_add_component(EchoionPluginUrlShortenerInternal) + echoion_add_component(EchoionPluginUrlShortenerExternal) endif() -if(BUILD_STANDALONE) - add_subdirectory(EchoionHost) +if(BUILD_HOST OR BUILD_STANDALONE) + echoion_add_component(EchoionHost) endif() if(BUILD_CORE) @@ -217,7 +220,7 @@ endif() # targets Core discovers. Core owns and starts the web server, so link them # here (both targets now exist) and flag Core so the wiring compiles in. if(BUILD_WEB AND BUILD_CORE) - add_subdirectory(EchoionWeb) + echoion_add_component(EchoionWeb) if(TARGET EchoionCore AND TARGET EchoionWeb) target_link_libraries(EchoionCore PRIVATE EchoionWeb) target_compile_definitions(EchoionCore PRIVATE ECHOION_WITH_WEB) @@ -231,13 +234,13 @@ endif() # It validates and journals local operations but leaves network/feed work to # the daemon through typed request files. Define it before Standalone so the # Linux release-staging test can use the real helper binary. -if(UNIX AND NOT APPLE) - add_subdirectory(packaging/updater) +if(BUILD_UPDATER AND UNIX AND NOT APPLE) + echoion_add_component(EchoionUpdater) endif() # EchoionStandalone links the host-common loader and native protocol client. if(BUILD_STANDALONE) - add_subdirectory(EchoionStandalone) + echoion_add_component(EchoionStandalone) endif() if(BUILD_DESKTOP) @@ -274,7 +277,7 @@ if(ECHOION_INSTALL_RUNTIME_BUNDLE) endif() if(TARGET EchoionWeb) - install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/EchoionWeb/frontend/web-dist/" + install(DIRECTORY "${EchoionWeb_SOURCE_DIR}/frontend/web-dist/" DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web" COMPONENT Runtime) endif() @@ -282,6 +285,11 @@ if(ECHOION_INSTALL_RUNTIME_BUNDLE) install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.json" DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion" COMPONENT Runtime) + install(FILES + "${CMAKE_CURRENT_SOURCE_DIR}/components.json" + "${CMAKE_CURRENT_SOURCE_DIR}/components.lock.json" + DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion" + COMPONENT Runtime) install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion.service.in" "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.service.in" @@ -301,6 +309,112 @@ if(ECHOION_INSTALL_RUNTIME_BUNDLE) endif() endif() +# Independent component package staging. Each named install component contains +# only that component's first-party payload; release tooling adds its private +# runtime dependency closure and a signed-feed manifest afterwards. +option(ECHOION_INSTALL_COMPONENT_PACKAGES + "Provide one install component for every independently released component" + ON) +if(ECHOION_INSTALL_COMPONENT_PACKAGES) + if(TARGET EchoionApiPluginSdk) + install(TARGETS EchoionApiPluginSdk + ARCHIVE DESTINATION lib + COMPONENT PackageEchoionApi) + install(DIRECTORY "${EchoionApi_SOURCE_DIR}/include/" + DESTINATION include + COMPONENT PackageEchoionApi) + install(FILES + "${EchoionApi_SOURCE_DIR}/abi/echoion-module-v1.json" + DESTINATION abi + COMPONENT PackageEchoionApi) + endif() + + if(TARGET EchoionHost) + install(TARGETS EchoionHost + LIBRARY DESTINATION lib + COMPONENT PackageEchoionHost + RUNTIME DESTINATION bin + COMPONENT PackageEchoionHost) + install(FILES "${EchoionHost_SOURCE_DIR}/abi/module.json" + DESTINATION abi + COMPONENT PackageEchoionHost) + endif() + + if(TARGET EchoionCore) + install(TARGETS EchoionCore + LIBRARY DESTINATION lib + COMPONENT PackageEchoionCore + RUNTIME DESTINATION bin + COMPONENT PackageEchoionCore) + install(FILES "${EchoionCore_SOURCE_DIR}/abi/module.json" + DESTINATION abi + COMPONENT PackageEchoionCore) + endif() + + if(TARGET EchoionWeb) + install(TARGETS EchoionWeb + LIBRARY DESTINATION lib + COMPONENT PackageEchoionWeb + RUNTIME DESTINATION bin + COMPONENT PackageEchoionWeb) + install(FILES "${EchoionWeb_SOURCE_DIR}/abi/module.json" + DESTINATION abi + COMPONENT PackageEchoionWeb) + install(DIRECTORY "${EchoionWeb_SOURCE_DIR}/frontend/web-dist/" + DESTINATION share/echoion/web + COMPONENT PackageEchoionWeb) + endif() + + if(TARGET EchoionStandalone) + install(TARGETS EchoionStandalone + RUNTIME DESTINATION bin + COMPONENT PackageEchoionStandalone) + endif() + + if(TARGET EchoionUpdater) + install(TARGETS EchoionUpdater + RUNTIME DESTINATION bin + COMPONENT PackageEchoionUpdater) + endif() + + if(TARGET EchoionDesktop) + install(TARGETS EchoionDesktop + RUNTIME DESTINATION bin + COMPONENT PackageEchoionDesktop + BUNDLE DESTINATION bin + COMPONENT PackageEchoionDesktop) + if(TARGET Qt6::QXcbIntegrationPlugin) + install(IMPORTED_RUNTIME_ARTIFACTS Qt6::QXcbIntegrationPlugin + LIBRARY DESTINATION plugins/platforms + COMPONENT PackageEchoionDesktop) + endif() + endif() + + if(TARGET EchoionUrlShortenerInternalPlugin) + install(TARGETS EchoionUrlShortenerInternalPlugin + LIBRARY DESTINATION lib + COMPONENT PackageEchoionPluginUrlShortenerInternal + RUNTIME DESTINATION lib + COMPONENT PackageEchoionPluginUrlShortenerInternal) + install(FILES + "${EchoionPluginUrlShortenerInternal_SOURCE_DIR}/abi/module.json" + DESTINATION abi + COMPONENT PackageEchoionPluginUrlShortenerInternal) + endif() + + if(TARGET EchoionUrlShortenerExternalPlugin) + install(TARGETS EchoionUrlShortenerExternalPlugin + LIBRARY DESTINATION lib + COMPONENT PackageEchoionPluginUrlShortenerExternal + RUNTIME DESTINATION lib + COMPONENT PackageEchoionPluginUrlShortenerExternal) + install(FILES + "${EchoionPluginUrlShortenerExternal_SOURCE_DIR}/abi/module.json" + DESTINATION abi + COMPONENT PackageEchoionPluginUrlShortenerExternal) + endif() +endif() + # Bundling and deployment helpers # Function to bundle Qt dependencies function(bundle_qt_dependencies target) @@ -376,10 +490,46 @@ if(BUILD_CORE AND TARGET EchoionCore) endif() if(BUILD_TESTS AND UNIX) + find_package(Python3 REQUIRED COMPONENTS Interpreter) + add_test(NAME echoion_prepare_release_tests + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_prepare_release.py") + add_test(NAME echoion_component_package_tests + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_package_components.py") + add_test(NAME echoion_component_feed_tests + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_publish_component_feeds.py") + + if(NOT COMMAND void_add_tests AND DEFINED Void_SOURCE_DIR) + include("${Void_SOURCE_DIR}/cmake/VoidTesting.cmake") + endif() + if(COMMAND void_add_tests AND + TARGET EchoionHost AND TARGET EchoionCore AND TARGET EchoionWeb AND + TARGET EchoionUrlShortenerInternalPlugin AND + TARGET EchoionUrlShortenerExternalPlugin) + add_executable(EchoionModuleTests tests/ModuleDescriptors.cpp) + target_compile_features(EchoionModuleTests PRIVATE cxx_std_26) + target_link_libraries(EchoionModuleTests PRIVATE + Echoion::ApiModuleAbi + Void::Testing + ${CMAKE_DL_LIBS}) + target_compile_definitions(EchoionModuleTests PRIVATE + "ECHOION_TEST_HOST=\"$\"" + "ECHOION_TEST_CORE=\"$\"" + "ECHOION_TEST_WEB=\"$\"" + "ECHOION_TEST_PLUGIN_INTERNAL=\"$\"" + "ECHOION_TEST_PLUGIN_EXTERNAL=\"$\"") + void_add_tests(EchoionModuleTests) + add_test(NAME echoion_module_descriptor_tests + COMMAND EchoionModuleTests) + endif() + add_test(NAME echoion_release_manifest_packaging_tests COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh" - "${CMAKE_CURRENT_SOURCE_DIR}") + "${CMAKE_CURRENT_SOURCE_DIR}" + "${ECHOION_COMPONENT_WORKSPACE}") add_test(NAME echoion_runtime_dependency_packaging_tests COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh" @@ -428,11 +578,13 @@ if(DEFINED ECHOION_RUNTIME_VERSION) endif() message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}") message(STATUS " Build API: ${BUILD_API}") +message(STATUS " Build Host: ${BUILD_HOST}") message(STATUS " Build first-party plugins: ${BUILD_FIRST_PARTY_PLUGINS}") message(STATUS " Build Core: ${BUILD_CORE}") message(STATUS " Build Desktop: ${BUILD_DESKTOP}") message(STATUS " Build Web: ${BUILD_WEB}") message(STATUS " Build Standalone: ${BUILD_STANDALONE}") +message(STATUS " Build Updater: ${BUILD_UPDATER}") message(STATUS " Build Tests: ${BUILD_TESTS}") message(STATUS " Static Link: ${ECHOION_STATIC_LINK}") message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}") diff --git a/CMakePresets.json b/CMakePresets.json index 359a3cb..4855ac6 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -26,7 +26,7 @@ "ECHOION_BUILD_WEB": "ON", "BUILD_STANDALONE": "ON", "BUILD_FIRST_PARTY_PLUGINS": "ON", - "BUILD_DESKTOP": "OFF", + "BUILD_DESKTOP": "ON", "BUILD_TESTS": "ON" } } diff --git a/EchoionHost/CMakeLists.txt b/EchoionHost/CMakeLists.txt deleted file mode 100644 index 345de79..0000000 --- a/EchoionHost/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -cmake_minimum_required(VERSION 4.0.0) -if(NOT DEFINED ECHOION_PRODUCT_VERSION) - set(ECHOION_PRODUCT_VERSION 0.0.0) -endif() -project(EchoionHost VERSION "${ECHOION_PRODUCT_VERSION}" LANGUAGES CXX) - -add_library(EchoionHost STATIC - src/CoreLoader.cpp -) -add_library(Echoion::Host ALIAS EchoionHost) - -target_compile_features(EchoionHost PUBLIC cxx_std_26) -set_target_properties(EchoionHost PROPERTIES POSITION_INDEPENDENT_CODE ON) -target_include_directories(EchoionHost PUBLIC - $ - $ -) -target_link_libraries(EchoionHost - PUBLIC - Echoion::ApiBase - Echoion::ApiConfig - Echoion::ApiPlugin - Echoion::ApiOpaque - Echoion::ApiCoreInterface - PRIVATE - Echoion::ApiLogger - Void::Data - Void::Log - Void::Plugin - Void::System - Void::Stacktrace - Threads::Threads -) - -if(NOT MSVC) - target_compile_options(EchoionHost PRIVATE - -Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wshadow) -endif() diff --git a/EchoionHost/include/echoion/host/CoreLoader.hpp b/EchoionHost/include/echoion/host/CoreLoader.hpp deleted file mode 100644 index 3946d94..0000000 --- a/EchoionHost/include/echoion/host/CoreLoader.hpp +++ /dev/null @@ -1,100 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Host -{ - - class CoreLoader - { - public: - - CoreLoader(); - ~CoreLoader(); - - Api::Result load(const std::filesystem::path& libraryPath); - Api::Result unload(); - Api::Result - hotReload(const std::filesystem::path& newLibraryPath); - [[nodiscard]] bool isLoaded() const noexcept; - [[nodiscard]] Api::CoreInterfacePtr getCore() const; - void setConfigPath(const std::filesystem::path& configPath); - [[nodiscard]] std::filesystem::path getConfigPath() const; - [[nodiscard]] bool isHotReloading() const noexcept; - Api::Result - checkpoint(const std::filesystem::path& destination); - Api::Result - restoreCheckpoint(const std::filesystem::path& source); - - // Automatic hot reload - void enableAutoReload(); - void disableAutoReload(); - [[nodiscard]] bool isAutoReloadEnabled() const noexcept; - - // Callback for hot reload completion (called after auto-reload - // finishes) - using HotReloadCallback = std::function; - using HotReloadPrepareCallback = std::function; - void setHotReloadPrepareCallback(HotReloadPrepareCallback callback) - { - hotReloadPrepareCallback_ = std::move(callback); - } - void setHotReloadCallback(HotReloadCallback callback) - { - hotReloadCallback_ = std::move(callback); - } - - private: - - Api::Result - loadLibraryInternal(const std::filesystem::path& path); - Api::Result unloadLibraryInternal(); - [[nodiscard]] Api::Result refreshCoreHandle(); - - Void::Plugin::PluginManager pluginManager_; - std::string pluginName_; - Api::CoreInterfacePtr core_; - std::filesystem::path currentLibraryPath_; - std::filesystem::path configPath_; - mutable std::mutex mutex_; - std::atomic loaded_{false}; - std::atomic hotReloading_{false}; - - // Auto reload - Void::FileSystem::FileWatcher fileWatcher_; - std::atomic autoReloadEnabled_{false}; - - // Deferred reload - waits for current track to finish - std::thread deferredReloadThread_; - std::atomic hasPendingReload_{false}; - std::atomic stopDeferredReload_{false}; - std::condition_variable deferredReloadCv_; - std::filesystem::path pendingReloadPath_; - std::string pendingTrackId_; // Track ID that was playing when - // reload scheduled - mutable std::mutex pendingReloadMutex_; - - // Hot reload completion callback - HotReloadPrepareCallback hotReloadPrepareCallback_; - HotReloadCallback hotReloadCallback_; - - void onCoreFileChanged(); - void waitForTrackAndReload(const std::filesystem::path& targetPath, - const std::string& trackId); - [[nodiscard]] bool isPlaybackActive() const; - [[nodiscard]] bool - isSameTrackPlaying(const std::string& trackId) const; - }; - -} // namespace Echoion::Host diff --git a/EchoionHost/src/CoreLoader.cpp b/EchoionHost/src/CoreLoader.cpp deleted file mode 100644 index 77f891a..0000000 --- a/EchoionHost/src/CoreLoader.cpp +++ /dev/null @@ -1,585 +0,0 @@ -#include "echoion/host/CoreLoader.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef _WIN32 -#include -#include -#endif - -namespace Echoion::Host -{ - namespace - { - bool canCreateHotReloadCopy(const std::filesystem::path& libraryPath) - { - const auto directory = libraryPath.parent_path(); -#ifdef _WIN32 - std::error_code error; - const auto status = std::filesystem::status(directory, error); - if (error || !std::filesystem::is_directory(status)) { - return false; - } - constexpr auto writable = std::filesystem::perms::owner_write | - std::filesystem::perms::group_write | - std::filesystem::perms::others_write; - return (status.permissions() & writable) != - std::filesystem::perms::none; -#else - struct stat metadata{}; - if (::stat(directory.c_str(), &metadata) != 0 || - !S_ISDIR(metadata.st_mode)) { - return false; - } - - const auto effectiveUser = ::geteuid(); - const auto effectiveGroup = ::getegid(); - bool usesDirectoryGroup = effectiveGroup == metadata.st_gid; - if (!usesDirectoryGroup) { - const int count = ::getgroups(0, nullptr); - if (count > 0) { - std::vector groups(static_cast(count)); - if (::getgroups(count, groups.data()) == count) { - usesDirectoryGroup = - std::ranges::contains(groups, metadata.st_gid); - } - } - } - - mode_t required{}; - if (effectiveUser == metadata.st_uid) { - required = S_IWUSR | S_IXUSR; - } else if (usesDirectoryGroup) { - required = S_IWGRP | S_IXGRP; - } else { - required = S_IWOTH | S_IXOTH; - } - return (metadata.st_mode & required) == required && - ::access(directory.c_str(), W_OK | X_OK) == 0; -#endif - } - } // namespace - - CoreLoader::CoreLoader() - : pluginManager_(Void::Plugin::PluginManager::Options{ - .dlclose_on_swap = false, - // Packaged Core libraries live in an immutable, service-readable - // directory. Initial load must never create a hotswap sibling - // there. - .copy_on_load = false, - .config_provider = - [this](std::string_view) { return configPath_.string(); }, - .instance_validator = - [](Void::Plugin::IPlugin& plugin, - const Void::Plugin::PluginInfo&) { - return dynamic_cast(&plugin) != - nullptr; - }}) - { - } - - void CoreLoader::enableAutoReload() - { - std::lock_guard lock(mutex_); - if (autoReloadEnabled_.load()) { - return; - } - if (!currentLibraryPath_.empty() && - std::filesystem::exists(currentLibraryPath_)) { - if (!canCreateHotReloadCopy(currentLibraryPath_)) { - Void::Log::info( - "CoreLoader", "{}", - std::format( - "Auto-reload disabled for read-only Core directory: {}", - currentLibraryPath_.parent_path().string())); - return; - } - autoReloadEnabled_ = true; - Void::Log::info("CoreLoader", "{}", - std::format("Enabling auto-reload for: {}", - currentLibraryPath_.string())); - - fileWatcher_.watch( - currentLibraryPath_, - [this](const Void::FileSystem::FileWatcher::Event& event) { - if (event.exists) { - onCoreFileChanged(); - } - }); - } - } - - void CoreLoader::disableAutoReload() - { - autoReloadEnabled_ = false; - if (!currentLibraryPath_.empty()) { - fileWatcher_.unwatch(currentLibraryPath_); - } - Void::Log::info("CoreLoader", "{}", "Auto-reload disabled"); - } - - bool CoreLoader::isAutoReloadEnabled() const noexcept - { - return autoReloadEnabled_.load(); - } - - void CoreLoader::onCoreFileChanged() - { - if (!autoReloadEnabled_.load() || hotReloading_.load()) { - return; - } - - Void::Log::info( - "CoreLoader", "{}", - "Core file changed, scheduling hot reload after current track..."); - - // Small delay to ensure file write is complete - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - - // Check if playback is active - if so, defer reload - if (isPlaybackActive()) { - std::string currentTrackId; - { - std::lock_guard lock(pendingReloadMutex_); - hasPendingReload_ = true; - pendingReloadPath_ = currentLibraryPath_; - - // Capture current track ID - auto state = core_->getPlaybackSummary(); - if (state && state->currentTrack.has_value()) { - pendingTrackId_ = state->currentTrack->id; - currentTrackId = pendingTrackId_; - } - } - - Void::Log::info( - "CoreLoader", "{}", - std::format("Playback active (track: {}), deferring reload " - "until track finishes", - currentTrackId)); - - // Start background thread to wait for track end - if (deferredReloadThread_.joinable()) { - deferredReloadThread_.join(); - } - deferredReloadThread_ = std::thread([this, currentTrackId]() { - waitForTrackAndReload(pendingReloadPath_, currentTrackId); - }); - } else { - // No playback, reload immediately - auto result = hotReload(currentLibraryPath_); - if (!result) { - Void::Log::error("CoreLoader", "{}", - std::format("Auto hot-reload failed: {}", - result.error().message)); - } else { - Void::Log::info("CoreLoader", "{}", - "Auto hot-reload completed successfully"); - } - } - } - - bool CoreLoader::isPlaybackActive() const - { - if (!core_) { - return false; - } - - auto state = core_->getPlaybackSummary(); - if (!state) { - return false; - } - - // Check if currently playing a track - return state->isPlaying && state->currentTrack.has_value(); - } - - bool CoreLoader::isSameTrackPlaying(const std::string& trackId) const - { - if (!core_ || trackId.empty()) { - return false; - } - - auto state = core_->getPlaybackSummary(); - if (!state || !state->currentTrack.has_value()) { - return false; - } - - return state->currentTrack->id == trackId; - } - - void CoreLoader::waitForTrackAndReload( - const std::filesystem::path& targetPath, const std::string& trackId) - { - Void::Log::info( - "CoreLoader", "{}", - std::format("Waiting for track {} to finish before reload...", - trackId)); - - // Poll every 500ms to check if the specific track finished - // (playback may continue with next track, but we only care about THIS - // track). The wait is interruptible so the destructor can join this - // thread instead of detaching it (detaching risks use-after-free when - // the plugin unloads mid-wait). - while (isSameTrackPlaying(trackId)) { - std::unique_lock lock(pendingReloadMutex_); - if (deferredReloadCv_.wait_for( - lock, std::chrono::milliseconds(500), - [this] { return stopDeferredReload_.load(); })) { - Void::Log::info( - "CoreLoader", "{}", - "Deferred hot-reload cancelled (loader shutting down)"); - return; - } - } - - if (stopDeferredReload_.load()) { - return; - } - - Void::Log::info("CoreLoader", "{}", - "Track finished, starting hot reload"); - - // Clear pending flag - { - std::lock_guard lock(pendingReloadMutex_); - hasPendingReload_ = false; - pendingTrackId_.clear(); - } - - // Now do the reload - auto result = hotReload(targetPath); - if (!result) { - Void::Log::error("CoreLoader", "{}", - std::format("Deferred hot-reload failed: {}", - result.error().message)); - } else { - Void::Log::info("CoreLoader", "{}", - "Deferred hot-reload completed successfully"); - } - } - - CoreLoader::~CoreLoader() - { - if (autoReloadEnabled_.load()) { - disableAutoReload(); - } - // Signal the deferred reload thread to stop and wait for it. It must - // never outlive this object: it dereferences core_ and this. - stopDeferredReload_ = true; - deferredReloadCv_.notify_all(); - if (deferredReloadThread_.joinable()) { - deferredReloadThread_.join(); - } - if (auto result = unload(); !result) { - Void::Log::warn("CoreLoader", "{}", - std::format("Unload from destructor failed: {}", - result.error().message)); - } - } - - Api::Result CoreLoader::load(const std::filesystem::path& libraryPath) - { - std::unique_lock lock(mutex_); - - if (loaded_) { - return Api::fail(Api::ErrorCode::AlreadyExists, - "Core already loaded"); - } - - if (!std::filesystem::exists(libraryPath)) { - return Api::fail( - Api::ErrorCode::NotFound, - std::format("Library not found: {}", libraryPath.string())); - } - - auto result = loadLibraryInternal(libraryPath); - if (result) { - currentLibraryPath_ = libraryPath; - } - - return result; - } - - Api::Result CoreLoader::unload() - { - std::lock_guard lock(mutex_); - - return unloadLibraryInternal(); - } - - Api::Result - CoreLoader::hotReload(const std::filesystem::path& newLibraryPath) - { - std::unique_lock lock(mutex_); - - if (!loaded_) { - return Api::fail(Api::ErrorCode::NotFound, - "No core loaded to reload"); - } - - auto targetPath = - newLibraryPath.empty() ? currentLibraryPath_ : newLibraryPath; - - if (!std::filesystem::exists(targetPath)) { - return Api::fail( - Api::ErrorCode::NotFound, - std::format("New library not found: {}", targetPath.string())); - } - const bool replacingPath = targetPath != currentLibraryPath_; - if (!replacingPath && !canCreateHotReloadCopy(targetPath)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "in-place Core reload requires a writable library directory; " - "use " - "an immutable versioned path for installed updates"); - } - - hotReloading_ = true; - Void::Log::info("CoreLoader", "{}", - "Starting transactional hot reload..."); - - // No callback may execute code from the old shared object after this - // barrier returns. State capture and dlclose are safe only after event - // producers have been drained. - if (hotReloadPrepareCallback_) { - hotReloadPrepareCallback_(); - } - - // Core owns exclusive process resources (HTTP/RPC listeners), so its - // two generations cannot both be initialized during an RCU swap. - // Capture state first, then stop the old services while its plugin - // instance remains pinned for rollback. - Api::StateBlob state; - if (core_) { - state = core_->saveState(); - if (auto stopped = core_->shutdown(); !stopped) { - hotReloading_ = false; - lock.unlock(); - if (hotReloadCallback_) { - hotReloadCallback_(); - } - return stopped; - } - } - - const auto reloadResult = - replacingPath ? pluginManager_.replace(pluginName_, targetPath) - : pluginManager_.reload(pluginName_); - if (!reloadResult) { - hotReloading_ = false; - auto message = - std::format("new Core rejected; running Core retained: {}", - Void::Plugin::to_string(reloadResult.error())); - if (core_) { - if (auto initialized = core_->initialize(configPath_); - !initialized) { - message += - std::format("; retained Core reactivation failed: {}", - initialized.error().message); - } else if (!state.empty()) { - if (auto restored = core_->restoreState(state); !restored) { - message += std::format( - "; retained Core state restore failed: {}", - restored.error().message); - } - } - } - Void::Log::warn("CoreLoader", "{}", message); - lock.unlock(); - // The prepare callback removed the event route. Restore it against - // the still-current Core even though no swap occurred. - if (hotReloadCallback_) { - hotReloadCallback_(); - } - return Api::fail(Api::ErrorCode::PluginError, message); - } - - if (auto refreshed = refreshCoreHandle(); !refreshed) { - hotReloading_ = false; - return refreshed; - } - currentLibraryPath_ = targetPath; - if (!state.empty()) { - if (auto restored = core_->restoreState(state); !restored) { - Void::Log::warn("CoreLoader", - "new Core state restore failed: {}", - restored.error().message); - } - } - hotReloading_ = false; - - Void::Log::info("CoreLoader", "{}", "Hot reload complete"); - lock.unlock(); - if (hotReloadCallback_) { - hotReloadCallback_(); - } - return {}; - } - - bool CoreLoader::isLoaded() const noexcept { return loaded_.load(); } - - Api::CoreInterfacePtr CoreLoader::getCore() const - { - std::lock_guard lock(mutex_); - return core_; - } - - void CoreLoader::setConfigPath(const std::filesystem::path& configPath) - { - std::lock_guard lock(mutex_); - configPath_ = configPath; - } - - std::filesystem::path CoreLoader::getConfigPath() const - { - std::lock_guard lock(mutex_); - return configPath_; - } - - bool CoreLoader::isHotReloading() const noexcept - { - return hotReloading_.load(); - } - - Api::Result - CoreLoader::checkpoint(const std::filesystem::path& destination) - { - std::lock_guard lock(mutex_); - if (!core_) { - return Api::fail(Api::ErrorCode::NotInitialized, - "cannot checkpoint without a loaded Core"); - } - const auto state = core_->saveState(); - std::string bytes; - bytes.reserve(8 + state.timestamp.size() + state.data.size()); - auto appendU32 = [&bytes](uint32_t value) { - for (int shift : {24, 16, 8, 0}) { - bytes.push_back(static_cast((value >> shift) & 0xffU)); - } - }; - appendU32(state.version); - appendU32(static_cast(state.timestamp.size())); - bytes.append(state.timestamp); - bytes.append(reinterpret_cast(state.data.data()), - state.data.size()); - if (auto result = Void::FileSystem::atomic_write(destination, bytes); - !result) { - return Api::fail(Api::ErrorCode::PluginError, - result.error().message()); - } - return {}; - } - - Api::Result - CoreLoader::restoreCheckpoint(const std::filesystem::path& source) - { - std::lock_guard lock(mutex_); - if (!core_) { - return Api::fail(Api::ErrorCode::NotInitialized, - "cannot restore without a loaded Core"); - } - auto contents = Void::FileSystem::read_file(source); - if (!contents) { - return Api::fail(Api::ErrorCode::NotFound, - contents.error().message()); - } - if (contents->size() < 8) { - return Api::fail(Api::ErrorCode::ParseError, - "checkpoint header is truncated"); - } - auto readU32 = [&contents](std::size_t offset) { - uint32_t value = 0; - for (std::size_t index = 0; index < 4; ++index) { - value = (value << 8U) | - static_cast((*contents)[offset + index]); - } - return value; - }; - Api::StateBlob state; - state.version = readU32(0); - const auto timestampSize = readU32(4); - if (timestampSize > contents->size() - 8) { - return Api::fail(Api::ErrorCode::ParseError, - "checkpoint timestamp is truncated"); - } - state.timestamp = contents->substr(8, timestampSize); - const auto dataOffset = 8 + timestampSize; - state.data.assign(contents->begin() + - static_cast(dataOffset), - contents->end()); - return core_->restoreState(state); - } - - Api::Result - CoreLoader::loadLibraryInternal(const std::filesystem::path& path) - { - auto result = pluginManager_.load(path); - if (!result) { - return Api::fail( - Api::ErrorCode::PluginError, - std::format("failed to load Core plugin: {}", - Void::Plugin::to_string(result.error()))); - } - pluginName_ = std::move(*result); - if (auto refreshed = refreshCoreHandle(); !refreshed) { - std::ignore = pluginManager_.unload(pluginName_); - pluginName_.clear(); - return refreshed; - } - loaded_ = true; - Void::Log::info("CoreLoader", "Core plugin '{}' loaded", pluginName_); - return {}; - } - - Api::Result CoreLoader::refreshCoreHandle() - { - auto pin = std::make_shared( - pluginManager_.acquire(pluginName_)); - if (!*pin) { - return Api::fail(Api::ErrorCode::PluginError, - "Core plugin disappeared from the registry"); - } - auto* interface = dynamic_cast(pin->get()); - if (interface == nullptr) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "Void plugin does not implement Echoion Core interface"); - } - core_ = Api::CoreInterfacePtr{std::move(pin), interface}; - return {}; - } - - Api::Result CoreLoader::unloadLibraryInternal() - { - if (!loaded_) { - return {}; - } - - Void::Log::info("CoreLoader", "{}", "Unloading core library..."); - - core_.reset(); - if (!pluginName_.empty()) { - if (auto result = pluginManager_.unload(pluginName_); !result) { - return Api::fail( - Api::ErrorCode::PluginError, - std::format("failed to unload Core plugin: {}", - Void::Plugin::to_string(result.error()))); - } - pluginName_.clear(); - } - - loaded_ = false; - std::cout << "[Echoion] Core library unloaded" << '\n'; - return {}; - } - -} // namespace Echoion::Host diff --git a/EchoionStandalone/CMakeLists.txt b/EchoionStandalone/CMakeLists.txt deleted file mode 100644 index 8d45dcf..0000000 --- a/EchoionStandalone/CMakeLists.txt +++ /dev/null @@ -1,207 +0,0 @@ -# EchoionStandalone — the daemon that runs Core without a TeamSpeak client. -# -# It uses the host-common CoreLoader/FileWatcher to load and hot-reload Core, -# and implements IPluginInterface with the reusable VoidTeamspeak client. - -cmake_minimum_required(VERSION 4.0.0) -if(NOT DEFINED ECHOION_PRODUCT_VERSION) - set(ECHOION_PRODUCT_VERSION 0.0.0) -endif() -project(EchoionStandalone VERSION "${ECHOION_PRODUCT_VERSION}" LANGUAGES CXX) - -set(CMAKE_CXX_STANDARD 26) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -find_package(PkgConfig REQUIRED) -pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET - libswresample>=4 - libavutil>=57 -) -pkg_check_modules(OPUS REQUIRED IMPORTED_TARGET opus) -find_package(Threads REQUIRED) -find_package(OpenSSL REQUIRED) - -set(ECHOION_UPDATE_FEED_URL "" CACHE STRING - "Build-time default URL for the official signed update feed") -set(ECHOION_UPDATE_PUBLIC_KEYS_JSON "[]" CACHE STRING - "Build-time Ed25519 trust anchors as [{\"id\":...,\"ed25519\":...}]") -set(ECHOION_RUNTIME_VERSION "${PROJECT_VERSION}" CACHE STRING - "Canonical SemVer reported when no installed release manifest is present") -string(LENGTH "${ECHOION_RUNTIME_VERSION}" _runtime_version_length) -if(_runtime_version_length GREATER 64 OR - NOT ECHOION_RUNTIME_VERSION MATCHES - "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$") - message(FATAL_ERROR - "ECHOION_RUNTIME_VERSION must be canonical SemVer without build metadata") -endif() -if(ECHOION_RUNTIME_VERSION MATCHES "-([^+]+)$") - set(_runtime_prerelease "${CMAKE_MATCH_1}") - string(REPLACE "." ";" _runtime_prerelease_identifiers - "${_runtime_prerelease}") - foreach(_identifier IN LISTS _runtime_prerelease_identifiers) - if(_identifier MATCHES "^0[0-9]+$") - message(FATAL_ERROR - "ECHOION_RUNTIME_VERSION has a non-canonical numeric prerelease identifier") - endif() - endforeach() -endif() -foreach(_update_default IN ITEMS - ECHOION_UPDATE_FEED_URL ECHOION_UPDATE_PUBLIC_KEYS_JSON - ECHOION_RUNTIME_VERSION) - if("${${_update_default}}" MATCHES "\\)ECHOION_UPDATE\\\"") - message(FATAL_ERROR "${_update_default} contains the generated-header delimiter") - endif() -endforeach() -set(ECHOION_TOOLCHAIN_ABI - "${CMAKE_CXX_COMPILER_ID}-${CMAKE_CXX_COMPILER_VERSION}-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") -configure_file( - "${CMAKE_CURRENT_SOURCE_DIR}/include/echoion/standalone/UpdateBuildDefaults.hpp.in" - "${CMAKE_CURRENT_BINARY_DIR}/generated/echoion/standalone/UpdateBuildDefaults.hpp" - @ONLY) - -add_executable(EchoionStandalone - src/main.cpp - src/StandaloneClientInterface.cpp - src/AudioEncoder.cpp - src/MessageChunker.cpp - src/ReleaseManifest.cpp - src/RuntimePaths.cpp - src/EventCallbackGate.cpp - src/UpdateService.cpp -) - -target_include_directories(EchoionStandalone PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/include" - "${CMAKE_CURRENT_BINARY_DIR}/generated" -) - -target_link_libraries(EchoionStandalone PRIVATE - Void::TeamSpeak - Echoion::Host - Echoion::ApiBase - Echoion::ApiPlugin - Echoion::ApiOpaque - Echoion::ApiPluginInterface - Echoion::ApiCoreInterface - Echoion::ApiLogger - Void::Data - Void::Core - Void::Log - Void::System - Void::Stacktrace - Void::Archive - Void::Crypto - Void::Net - Void::Plugin - Void::Update - Threads::Threads - PkgConfig::SWRESAMPLE - PkgConfig::OPUS - OpenSSL::Crypto -) - -set_target_properties(EchoionStandalone PROPERTIES - OUTPUT_NAME "echoiond" - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin -) - -install(TARGETS EchoionStandalone RUNTIME DESTINATION bin) - -if(BUILD_TESTS AND TARGET EchoionCore) - add_executable(echoion_core_loader_reload_tests - tests/test_core_loader_reload.cpp) - target_link_libraries(echoion_core_loader_reload_tests PRIVATE - Echoion::Host Echoion::ApiCoreInterface) - target_compile_features(echoion_core_loader_reload_tests PRIVATE cxx_std_26) - target_compile_definitions(echoion_core_loader_reload_tests PRIVATE - "ECHOION_TEST_CORE_PATH=\"$\"") - add_dependencies(echoion_core_loader_reload_tests EchoionCore) - add_test(NAME echoion_core_loader_reload_tests - COMMAND echoion_core_loader_reload_tests) -endif() - -if(BUILD_TESTS) - add_executable(echoion_standalone_message_tests - tests/test_message_chunker.cpp - src/MessageChunker.cpp - ) - target_include_directories(echoion_standalone_message_tests PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/include" - ) - target_compile_features(echoion_standalone_message_tests PRIVATE cxx_std_20) - add_test(NAME echoion_standalone_message_tests - COMMAND echoion_standalone_message_tests) - - add_executable(echoion_release_manifest_tests - tests/test_release_manifest.cpp - src/ReleaseManifest.cpp - ) - target_include_directories(echoion_release_manifest_tests PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/include" - ) - target_compile_features(echoion_release_manifest_tests PRIVATE cxx_std_26) - target_link_libraries(echoion_release_manifest_tests PRIVATE - Echoion::ApiBase Void::Data Void::System OpenSSL::Crypto) - add_test(NAME echoion_release_manifest_tests - COMMAND echoion_release_manifest_tests) - - add_executable(echoion_runtime_paths_tests - tests/test_runtime_paths.cpp - src/RuntimePaths.cpp - ) - target_include_directories(echoion_runtime_paths_tests PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/include" - ) - target_compile_features(echoion_runtime_paths_tests PRIVATE cxx_std_26) - add_test(NAME echoion_runtime_paths_tests - COMMAND echoion_runtime_paths_tests) - - add_executable(echoion_event_callback_gate_tests - tests/test_event_callback_gate.cpp - src/EventCallbackGate.cpp - ) - target_include_directories(echoion_event_callback_gate_tests PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/include" - ) - target_compile_features(echoion_event_callback_gate_tests PRIVATE cxx_std_26) - target_link_libraries(echoion_event_callback_gate_tests PRIVATE - Echoion::ApiBase Echoion::ApiConfig Echoion::ApiPlugin - Void::Core Threads::Threads) - add_test(NAME echoion_event_callback_gate_tests - COMMAND echoion_event_callback_gate_tests) - - add_executable(echoion_update_service_tests - tests/test_update_service.cpp - src/UpdateService.cpp - ) - target_include_directories(echoion_update_service_tests PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}/include" - ) - target_compile_features(echoion_update_service_tests PRIVATE cxx_std_26) - target_link_libraries(echoion_update_service_tests PRIVATE - Echoion::ApiBase Echoion::ApiConfig - Void::Archive Void::Crypto Void::Data Void::Log Void::Net Void::Plugin - Void::System Void::Update Threads::Threads) - add_test(NAME echoion_update_service_tests - COMMAND echoion_update_service_tests) - - add_executable(echoion_update_build_defaults_tests - tests/test_update_build_defaults.cpp) - target_include_directories(echoion_update_build_defaults_tests PRIVATE - "${CMAKE_CURRENT_BINARY_DIR}/generated") - target_compile_features(echoion_update_build_defaults_tests PRIVATE - cxx_std_20) - target_compile_definitions(echoion_update_build_defaults_tests PRIVATE - "ECHOION_EXPECTED_RUNTIME_VERSION=\"${ECHOION_RUNTIME_VERSION}\"") - add_test(NAME echoion_update_build_defaults_tests - COMMAND echoion_update_build_defaults_tests) - - if(TARGET EchoionUpdater) - add_test(NAME echoion_stage_release_tests - COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_stage_release.sh" - "${CMAKE_SOURCE_DIR}/scripts/stage-release.sh" - $ - "${CMAKE_SOURCE_DIR}/packaging/service") - endif() -endif() diff --git a/EchoionStandalone/include/echoion/standalone/AudioEncoder.hpp b/EchoionStandalone/include/echoion/standalone/AudioEncoder.hpp deleted file mode 100644 index bd40cd7..0000000 --- a/EchoionStandalone/include/echoion/standalone/AudioEncoder.hpp +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -// Converts Echoion's internal PCM (192 kHz stereo S16, delivered in 20 ms -// chunks) into TeamSpeak-ready Opus frames: resample to 48 kHz stereo, then -// Opus-encode in exact 20 ms (960 samples/ch) frames. A small PCM ring absorbs -// the resampler's priming latency so every emitted frame is exactly 960/ch. - -#include -#include -#include - -struct SwrContext; -struct OpusEncoder; - -namespace Echoion::Standalone -{ - - class AudioEncoder - { - public: - - // inRate defaults to Echoion's 192 kHz internal pipeline. - explicit AudioEncoder(int bitrate = 96000, int inRate = 192000); - ~AudioEncoder(); - - AudioEncoder(const AudioEncoder&) = delete; - AudioEncoder& operator=(const AudioEncoder&) = delete; - - // Feed one chunk of interleaved stereo S16 at inRate. Returns zero or - // more complete Opus frames (each a 20 ms packet). - std::vector> - encode(std::span interleaved); - - private: - - SwrContext* swr_ = nullptr; - OpusEncoder* enc_ = nullptr; - int inRate_ = 192000; - std::vector pcm_; // resampled 48 kHz interleaved stereo - }; - -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/include/echoion/standalone/EventCallbackGate.hpp b/EchoionStandalone/include/echoion/standalone/EventCallbackGate.hpp deleted file mode 100644 index ed484f3..0000000 --- a/EchoionStandalone/include/echoion/standalone/EventCallbackGate.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - // Owns plugin-event callbacks across a dynamically loaded Core boundary. - // quiesce() is a lifetime barrier: after it returns no callback object, nor - // callback invocation, can still reference code from the old Core image. - class EventCallbackGate final - { - public: - void add(Api::EventCallback callback); - void quiesce(); - void dispatch(const Api::PluginEvent& event); - - private: - std::mutex mutex_; - std::condition_variable cv_; - std::vector callbacks_; - std::size_t activeDispatches_{0}; - bool accepting_{true}; - }; -} diff --git a/EchoionStandalone/include/echoion/standalone/MessageChunker.hpp b/EchoionStandalone/include/echoion/standalone/MessageChunker.hpp deleted file mode 100644 index 4b224b2..0000000 --- a/EchoionStandalone/include/echoion/standalone/MessageChunker.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace Echoion::Standalone -{ - // Split TeamSpeak messages on UTF-8/line boundaries while preserving each - // complete markdown-it `:::details ... :::` container in one message. - [[nodiscard]] std::vector - chunkMessage(const std::string& message, std::size_t limit = 900); -} diff --git a/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp b/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp deleted file mode 100644 index 553230d..0000000 --- a/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include - -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - enum class ReleaseFileType : std::uint8_t { - Regular, - Symlink, - }; - - struct ReleaseFileEntry { - std::filesystem::path path; - ReleaseFileType type{ReleaseFileType::Regular}; - std::uintmax_t size{}; - std::filesystem::perms mode{std::filesystem::perms::unknown}; - std::string sha256; - std::filesystem::path target; - }; - - struct ReleaseManifest { - std::uint32_t schemaVersion{1}; - std::string version; - std::filesystem::path root; - std::filesystem::path executable; - std::filesystem::path core; - std::string executableSha256; - std::string coreSha256; - std::vector files; - - [[nodiscard]] static Api::Result - load(const std::filesystem::path& manifestPath); - [[nodiscard]] Api::Result validate() const; - [[nodiscard]] Api::Result validateInstallLayout() const; - }; -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/include/echoion/standalone/RuntimePaths.hpp b/EchoionStandalone/include/echoion/standalone/RuntimePaths.hpp deleted file mode 100644 index 8ee1646..0000000 --- a/EchoionStandalone/include/echoion/standalone/RuntimePaths.hpp +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - [[nodiscard]] std::expected - runningExecutablePath(); - - [[nodiscard]] std::filesystem::path deriveInstallRoot( - const std::filesystem::path& executablePath, - const std::optional& homeOverride = - std::nullopt); - - [[nodiscard]] std::filesystem::path resolveCorePath( - const std::filesystem::path& installRoot, - const std::filesystem::path& executableDirectory, - const std::optional& coreOverride = - std::nullopt); - - [[nodiscard]] std::filesystem::path resolveStateDirectory( - const std::optional& commandLineOverride, - const std::optional& environmentOverride, - const std::optional& xdgStateHome, - const std::optional& userHome, - const std::filesystem::path& fallback); - - [[nodiscard]] std::optional runtimeWorkingDirectory( - const std::filesystem::path& installRoot, - const std::filesystem::path& executableDirectory); - - [[nodiscard]] std::optional - bundledCertificateBundle(const std::filesystem::path& installRoot); - - [[nodiscard]] std::expected - resolveAvatarCacheDirectory( - const std::filesystem::path& configuredDirectory, - const std::filesystem::path& requestedDirectory = {}); -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp b/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp deleted file mode 100644 index a8a3a7d..0000000 --- a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp +++ /dev/null @@ -1,173 +0,0 @@ -#pragma once - -// Implements Echoion's host interface by adapting VoidTeamspeak's typed client -// operations and events. TeamSpeak protocol details remain inside -// VoidTeamspeak; Core only sees the host-neutral Echoion API contract. - -#include - -#include "echoion/standalone/EventCallbackGate.hpp" -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - - class AudioEncoder; - - // Runtime knobs the protocol client needs that ServerConfig does not carry. - // Sourced from environment / defaults by main(), so no Core changes are - // required. - struct StandaloneSettings { - std::string identityPath; // where to load/persist the TS identity - std::string avatarCachePath; - int securityLevel = 8; - int opusBitrate = 96000; - }; - - class StandaloneClientInterface : public Api::IPluginInterface - { - public: - - explicit StandaloneClientInterface(StandaloneSettings settings); - ~StandaloneClientInterface() override; - - // Lifecycle - Api::Result initialize() override; - Api::Result shutdown() override; - - // Clients - [[nodiscard]] Api::Result> - getClients() override; - [[nodiscard]] Api::Result> - getClient(uint64_t clientId) override; - [[nodiscard]] Api::Result> - getClientIp(uint64_t clientId) override; - [[nodiscard]] Api::Result> - getClientAvatarPath(uint64_t clientId) override; - [[nodiscard]] Api::Result> - getClientAvatarUrl(uint64_t clientId) override; - [[nodiscard]] Api::Result> - requestClientAvatar(uint64_t clientId, - const std::string& destDir) override; - Api::Result moveClient(uint64_t clientId, - uint64_t channelId) override; - Api::Result kickClient(uint64_t clientId, - const std::string& reason) override; - Api::Result - kickClientFromChannel(uint64_t clientId, - const std::string& reason) override; - Api::Result banClient(uint64_t clientId, - uint64_t durationSeconds, - const std::string& reason) override; - [[nodiscard]] Api::Result> - getBans() override; - Api::Result unban(uint64_t banId) override; - - // Channels - [[nodiscard]] Api::Result> - getChannels() const override; - [[nodiscard]] Api::Result> - getChannel(uint64_t channelId) const override; - Api::Result createChannel( - const Api::ChannelCreateOptions& options) override; - Api::Result - editChannel(uint64_t channelId, - const Api::ChannelEditOptions& options) override; - Api::Result reorderChannel(uint64_t channelId, - uint64_t parentId, - uint64_t orderAfterId) override; - Api::Result deleteChannel(uint64_t channelId, - bool force) override; - - [[nodiscard]] Api::Result> - getServerGroups() override; - Api::Result - addClientToServerGroup(uint64_t groupId, - uint64_t clientDatabaseId) override; - Api::Result - removeClientFromServerGroup(uint64_t groupId, - uint64_t clientDatabaseId) override; - [[nodiscard]] Api::Result - getTeamSpeakServerInfo() override; - - // Messaging - Api::Result - sendTextMessage(uint64_t targetId, - const std::string& message) override; - Api::Result - sendChannelMessage(uint64_t channelId, - const std::string& message) override; - Api::Result - sendServerMessage(const std::string& message) override; - - // Audio - Api::Result - sendAudioData(const std::span& data) override; - Api::Result - setWhisperList(const std::vector& clientIds) override; - - // Connection - Api::Result - connectToServer(const Api::ServerConfig& config) override; - Api::Result disconnectFromServer() override; - [[nodiscard]] bool isConnected() const override; - Api::Result reconnect() override; - - // Events - void registerEventCallback(const Api::EventCallback& cb) override; - void unregisterEventCallback(const Api::EventCallback& cb) override; - [[nodiscard]] Api::Result - hostControl(const std::string& method, - const std::string& requestJson) override; - using HostControlHandler = std::function( - const std::string&, const std::string&)>; - void setHostControlHandler(HostControlHandler handler); - // Prevent new event dispatches, release registered callbacks and - // wait until every callback already in flight has returned. The - // host must call this before unloading code that owns an event - // callback. - void quiesceEventCallbacks(); - - private: - - void wireCallbacks(); - void broadcast(const Api::PluginEvent& event); - void loadInitialSnapshot(); - [[nodiscard]] Api::Result commandResult( - const Void::Result::Result& - result) const; - - StandaloneSettings settings_; - std::shared_ptr identity_; - std::unique_ptr client_; - std::unique_ptr encoder_; - - Api::ServerConfig currentConfig_{}; - std::atomic initialized_{false}; - - mutable std::mutex mirrorMutex_; - std::map clients_; - std::map channels_; - std::optional serverInfo_; - std::map clientIps_; - std::map avatarHashes_; - std::map avatarUrls_; - std::map avatarPaths_; - std::vector whisperList_; - std::jthread snapshotThread_; - mutable std::mutex hostControlMutex_; - HostControlHandler hostControlHandler_; - - EventCallbackGate eventCallbacks_; - }; - -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in b/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in deleted file mode 100644 index 975eeb0..0000000 --- a/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -namespace Echoion::Standalone::UpdateBuildDefaults -{ - inline constexpr std::string_view FeedUrl = - R"ECHOION_UPDATE(@ECHOION_UPDATE_FEED_URL@)ECHOION_UPDATE"; - inline constexpr std::string_view PublicKeysJson = - R"ECHOION_UPDATE(@ECHOION_UPDATE_PUBLIC_KEYS_JSON@)ECHOION_UPDATE"; - inline constexpr std::string_view RuntimeVersion = - R"ECHOION_UPDATE(@ECHOION_RUNTIME_VERSION@)ECHOION_UPDATE"; - inline constexpr std::string_view ApiVersion = - R"ECHOION_UPDATE(@PROJECT_VERSION@)ECHOION_UPDATE"; - inline constexpr std::string_view ToolchainAbi = - R"ECHOION_UPDATE(@ECHOION_TOOLCHAIN_ABI@)ECHOION_UPDATE"; -} diff --git a/EchoionStandalone/include/echoion/standalone/UpdateService.hpp b/EchoionStandalone/include/echoion/standalone/UpdateService.hpp deleted file mode 100644 index 2b6f800..0000000 --- a/EchoionStandalone/include/echoion/standalone/UpdateService.hpp +++ /dev/null @@ -1,110 +0,0 @@ -#pragma once - -#include - -#include -#include -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - struct ManagedCoreStartupSelection { - std::filesystem::path corePath; - std::optional archivedStore; - bool runtimeBaselineChanged = false; - }; - - // Installed runtime releases own their bundled Core baseline. A runtime - // version change archives the previous managed store; Core-only updates - // remain active across ordinary restarts of the same runtime. - [[nodiscard]] Api::Result - selectManagedCoreForStartup( - const std::filesystem::path& stateDirectory, - const std::filesystem::path& bundledCore, - std::optional installedRuntimeVersion); - - // Roll back any uncommitted managed-plugin activation before Core loads and - // discovers plugin `current` links. This must run before PluginHost - // startup. - [[nodiscard]] Api::Result reconcileManagedPluginUpdates( - const std::filesystem::path& stateDirectory); - - // Host-owned update coordinator. Core only forwards authenticated RPC - // requests across the append-only host interface; all trust, download, - // staging and activation decisions remain in the long-lived daemon. - class UpdateService final - { - public: - - struct Options { - std::filesystem::path configPath; - std::filesystem::path stateDirectory; - std::filesystem::path installRoot; - std::filesystem::path runningExecutable; - std::filesystem::path currentCore; - std::filesystem::path releaseManifestPath; - std::string officialFeedUrl; - std::string officialPublicKeysJson = "[]"; - std::string runtimeVersion; - std::string apiVersion; - std::string toolchainAbi; - // Trusted administrator drop directory for file:// - // feeds/artifacts. Empty selects stateDirectory / - // "incoming". - std::filesystem::path incomingDirectory; - }; - - struct Hooks { - std::function( - const std::filesystem::path&)> - replaceCore; - std::function(const std::string&)> - managePlugins; - std::function(const std::string&)> - manageRuntime; - std::function playbackActive; - std::function coreVersion; - }; - - UpdateService(Options options, Hooks hooks); - ~UpdateService(); - - UpdateService(const UpdateService&) = delete; - UpdateService& operator=(const UpdateService&) = delete; - UpdateService(UpdateService&&) noexcept; - UpdateService& operator=(UpdateService&&) noexcept; - - [[nodiscard]] Api::Result start(); - void stop() noexcept; - - // Execute host mutations which must not run on the Core RPC stack. - // The daemon calls this from its polling loop after an RPC has - // returned. - void processPendingHostActions(); - - // Methods are the internal `updates.*` names forwarded by Core. - // Requests and successful responses are JSON documents matching the - // web contract. - [[nodiscard]] Api::Result - handle(const std::string& method, - const std::string& requestJson); - - private: - - class Impl; - std::unique_ptr impl_; - }; - - using UpdateControlHandler = std::function( - const std::string&, const std::string&)>; - - // Keep the service alive for the complete duration of an in-flight host - // control request. StandaloneClientInterface intentionally invokes a copied - // handler outside its mutex, so clearing the registered handler cannot - // cancel a callback which has already started. - [[nodiscard]] UpdateControlHandler - bindUpdateService(std::shared_ptr service); -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/AudioEncoder.cpp b/EchoionStandalone/src/AudioEncoder.cpp deleted file mode 100644 index f99f330..0000000 --- a/EchoionStandalone/src/AudioEncoder.cpp +++ /dev/null @@ -1,102 +0,0 @@ -#include "echoion/standalone/AudioEncoder.hpp" - -extern "C" { -#include -#include -#include -#include -#include -} - -#include - -namespace Echoion::Standalone -{ - namespace - { - constexpr int OUT_RATE = 48000; - constexpr int CHANNELS = 2; - constexpr int FRAME_SAMPLES = 960; // 20 ms @ 48 kHz per channel - constexpr int FRAME_SHORTS = FRAME_SAMPLES * CHANNELS; - constexpr int MAX_OPUS = 4000; - } // namespace - - AudioEncoder::AudioEncoder(int bitrate, int inRate) : inRate_(inRate) - { - AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO; - if (swr_alloc_set_opts2(&swr_, &stereo, AV_SAMPLE_FMT_S16, OUT_RATE, - &stereo, AV_SAMPLE_FMT_S16, inRate_, 0, - nullptr) < 0 || - swr_init(swr_) < 0) { - throw std::runtime_error("AudioEncoder: swresample init failed"); - } - - int err = 0; - enc_ = opus_encoder_create(OUT_RATE, CHANNELS, OPUS_APPLICATION_AUDIO, - &err); - if (err != OPUS_OK || !enc_) { - throw std::runtime_error("AudioEncoder: opus encoder init failed"); - } - opus_encoder_ctl(enc_, OPUS_SET_BITRATE(bitrate)); - opus_encoder_ctl(enc_, OPUS_SET_SIGNAL(OPUS_SIGNAL_MUSIC)); - } - - AudioEncoder::~AudioEncoder() - { - if (enc_) { - opus_encoder_destroy(enc_); - } - if (swr_) { - swr_free(&swr_); - } - } - - std::vector> - AudioEncoder::encode(std::span interleaved) - { - std::vector> out; - - const int inSamplesPerCh = - static_cast(interleaved.size() / CHANNELS); - if (inSamplesPerCh <= 0) { - return out; - } - - // Upper bound on resampled samples for this chunk. - int maxOut = static_cast( - av_rescale_rnd(swr_get_delay(swr_, inRate_) + inSamplesPerCh, - OUT_RATE, inRate_, AV_ROUND_UP)); - std::vector resampled( - static_cast(maxOut) * CHANNELS, 0); - - const uint8_t* inPtr = - reinterpret_cast(interleaved.data()); - uint8_t* outPtr = reinterpret_cast(resampled.data()); - int gotPerCh = swr_convert(swr_, &outPtr, maxOut, &inPtr, - inSamplesPerCh); - if (gotPerCh < 0) { - return out; - } - pcm_.insert(pcm_.end(), resampled.begin(), - resampled.begin() + - static_cast(gotPerCh) * CHANNELS); - - // Emit as many full 20 ms frames as we have buffered. - size_t consumed = 0; - while (pcm_.size() - consumed >= static_cast(FRAME_SHORTS)) { - uint8_t packet[MAX_OPUS]; - int n = opus_encode(enc_, pcm_.data() + consumed, FRAME_SAMPLES, - packet, MAX_OPUS); - if (n > 0) { - out.emplace_back(packet, packet + n); - } - consumed += FRAME_SHORTS; - } - if (consumed > 0) { - pcm_.erase(pcm_.begin(), - pcm_.begin() + static_cast(consumed)); - } - return out; - } - -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/EventCallbackGate.cpp b/EchoionStandalone/src/EventCallbackGate.cpp deleted file mode 100644 index ddf6f45..0000000 --- a/EchoionStandalone/src/EventCallbackGate.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include "echoion/standalone/EventCallbackGate.hpp" - -#include - -#include - -namespace Echoion::Standalone -{ - void EventCallbackGate::add(Api::EventCallback callback) - { - std::lock_guard lock(mutex_); - accepting_ = true; - callbacks_.push_back(std::move(callback)); - } - - void EventCallbackGate::quiesce() - { - std::unique_lock lock(mutex_); - accepting_ = false; - callbacks_.clear(); - cv_.wait(lock, [this] { return activeDispatches_ == 0; }); - } - - void EventCallbackGate::dispatch(const Api::PluginEvent& event) - { - std::vector callbacks; - { - std::lock_guard lock(mutex_); - if (!accepting_) return; - ++activeDispatches_; - callbacks = callbacks_; - } - const auto complete = Void::Scope::on_exit([this] { - std::lock_guard lock(mutex_); - --activeDispatches_; - cv_.notify_all(); - }); - for (const auto& callback : callbacks) { - if (callback) callback(event); - } - } -} diff --git a/EchoionStandalone/src/MessageChunker.cpp b/EchoionStandalone/src/MessageChunker.cpp deleted file mode 100644 index 00c65cd..0000000 --- a/EchoionStandalone/src/MessageChunker.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include "echoion/standalone/MessageChunker.hpp" - -#include - -namespace Echoion::Standalone -{ - std::vector chunkMessage(const std::string& message, - std::size_t limit) - { - if (limit == 0 || message.empty()) { - return message.empty() ? std::vector{} - : std::vector{message}; - } - if (message.size() <= limit) { - return {message}; - } - - const auto isBlank = [](const std::string& value) { - return value.find_first_not_of(" \t\r\n") == std::string::npos; - }; - std::vector chunks; - std::string current; - int detailsDepth = 0; - const auto flush = [&] { - if (!current.empty() && !isBlank(current)) { - chunks.push_back(current); - } - current.clear(); - }; - - std::size_t position = 0; - while (position < message.size()) { - const auto newline = message.find('\n', position); - std::string line = newline == std::string::npos - ? message.substr(position) - : message.substr(position, newline - position + 1); - position = newline == std::string::npos ? message.size() : newline + 1; - - const bool opens = line.starts_with(":::details"); - std::string_view trimmed = line; - while (!trimmed.empty() && - (trimmed.back() == '\n' || trimmed.back() == '\r' || - trimmed.back() == ' ' || trimmed.back() == '\t')) { - trimmed.remove_suffix(1); - } - const bool closes = trimmed == ":::"; - - if (detailsDepth == 0 && !current.empty() && - (opens || current.size() + line.size() > limit)) { - flush(); - } - - // A details block must remain syntactically complete even if it is - // longer than the preferred message limit. Normal lines are split at - // a UTF-8 code-point boundary. - if (detailsDepth == 0 && !opens) { - while (line.size() > limit) { - std::size_t cut = limit; - while (cut > 0 && - (static_cast(line[cut]) & 0xc0) == 0x80) { - --cut; - } - if (cut == 0) { - cut = limit; - } - flush(); - auto piece = line.substr(0, cut); - if (!isBlank(piece)) { - chunks.push_back(std::move(piece)); - } - line.erase(0, cut); - } - } - - current += line; - if (opens) { - ++detailsDepth; - } - if (closes && detailsDepth > 0) { - --detailsDepth; - } - } - flush(); - return chunks; - } -} diff --git a/EchoionStandalone/src/ReleaseManifest.cpp b/EchoionStandalone/src/ReleaseManifest.cpp deleted file mode 100644 index f39ff7a..0000000 --- a/EchoionStandalone/src/ReleaseManifest.cpp +++ /dev/null @@ -1,650 +0,0 @@ -#include "echoion/standalone/ReleaseManifest.hpp" - -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - namespace - { - constexpr auto kExecutablePermissions = - std::filesystem::perms::owner_exec | - std::filesystem::perms::group_exec | - std::filesystem::perms::others_exec; - constexpr auto kUnsafeWritablePermissions = - std::filesystem::perms::group_write | - std::filesystem::perms::others_write; - constexpr std::array kImmutableRoots{ - "bin", "lib", "service", "share"}; - constexpr double kMaximumExactJsonInteger = 9'007'199'254'740'991.0; - - Api::Result sha256(const std::filesystem::path& path) - { - std::ifstream input(path, std::ios::binary); - if (!input) { - return Api::fail(Api::ErrorCode::NotFound, - "release artifact not found: " + - path.string()); - } - using Context = - std::unique_ptr; - Context context(EVP_MD_CTX_new(), &EVP_MD_CTX_free); - if (!context || - EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr) != 1) { - return Api::fail(Api::ErrorCode::UnknownError, - "cannot initialize SHA-256"); - } - std::array buffer{}; - while (input) { - input.read(buffer.data(), - static_cast(buffer.size())); - if (const auto count = input.gcount(); - count > 0 && - EVP_DigestUpdate(context.get(), buffer.data(), - static_cast(count)) != 1) { - return Api::fail(Api::ErrorCode::UnknownError, - "cannot hash release artifact"); - } - } - std::array digest{}; - unsigned int size{}; - if (EVP_DigestFinal_ex(context.get(), digest.data(), &size) != 1) { - return Api::fail(Api::ErrorCode::UnknownError, - "cannot finalize release hash"); - } - std::ostringstream output; - output << std::hex << std::setfill('0'); - for (unsigned int index = 0; index < size; ++index) { - output << std::setw(2) - << static_cast(digest[index]); - } - return output.str(); - } - - bool isSafeRelativePath(const std::filesystem::path& path) - { - if (path.empty() || path.is_absolute() || path.has_root_name() || - path.filename().empty() || - std::ranges::contains(path.native(), '\0')) { - return false; - } - if (path.generic_string() != - path.lexically_normal().generic_string()) { - return false; - } - return std::ranges::none_of(path, [](const auto& component) { - return component == "." || component == ".."; - }); - } - - bool isSha256(std::string_view value) - { - return value.size() == 64 && - std::ranges::all_of( - value, [](const unsigned char character) { - return (character >= '0' && character <= '9') || - (character >= 'a' && character <= 'f'); - }); - } - - std::optional parseMode(std::string_view value) - { - if (value.size() != 4 || value.front() != '0' || - !std::ranges::all_of(value.substr(1), [](const char character) { - return character >= '0' && character <= '7'; - })) { - return std::nullopt; - } - unsigned int result{}; - for (const char character : value.substr(1)) { - result = - result * 8U + static_cast(character - '0'); - } - return static_cast(result); - } - - std::optional parseSize(const Void::Json::Value& entry) - { - const auto* value = entry.find("size"); - if (!value || !value->is_number()) { - return std::nullopt; - } - const double number = value->as_number(); - if (!std::isfinite(number) || number < 0.0 || - number > kMaximumExactJsonInteger || - std::trunc(number) != number) { - return std::nullopt; - } - return static_cast(number); - } - - std::filesystem::path - normalizedAbsolute(const std::filesystem::path& path) - { - std::error_code error; - auto absolute = std::filesystem::absolute(path, error); - return (error ? path : absolute).lexically_normal(); - } - - bool isWithin(const std::filesystem::path& root, - const std::filesystem::path& candidate) - { - const auto relative = candidate.lexically_relative(root); - return !relative.empty() && !relative.is_absolute() && - std::ranges::none_of(relative, [](const auto& component) { - return component == ".."; - }); - } - - bool hasUnsafeWritablePermissions( - const std::filesystem::file_status& status) - { - return (status.permissions() & kUnsafeWritablePermissions) != - std::filesystem::perms::none; - } - - std::optional - relativeToPayload(const std::filesystem::path& path, - const std::filesystem::path& prefix) - { - if (prefix.empty()) { - return path; - } - const auto relative = path.lexically_relative(prefix); - if (!isSafeRelativePath(relative)) { - return std::nullopt; - } - return relative; - } - - bool isImmutablePayloadPath(const std::filesystem::path& path, - const std::filesystem::path& prefix) - { - const auto relative = relativeToPayload(path, prefix); - if (!relative || relative->empty()) { - return false; - } - return std::ranges::contains(kImmutableRoots, - relative->begin()->generic_string()); - } - - Api::Result - payloadPrefix(const ReleaseManifest& manifest) - { - const auto executable = - manifest.executable.lexically_relative(manifest.root); - if (!isSafeRelativePath(executable) || - executable.filename() != "echoiond" || - executable.parent_path().filename() != "bin") { - return Api::fail(Api::ErrorCode::IncompatibleVersion, - "v2 release executable must use the payload " - "bin/echoiond layout"); - } - - const auto prefix = executable.parent_path().parent_path(); - const auto expectedCore = - (manifest.root / prefix / "lib" / "Echoion.ts") - .lexically_normal(); - if (manifest.core.lexically_normal() != expectedCore) { - return Api::fail(Api::ErrorCode::IncompatibleVersion, - "v2 release Core must use the payload " - "lib/Echoion.ts layout"); - } - return prefix; - } - - Api::Result - validateImmutableCoverage(const ReleaseManifest& manifest) - { - auto prefix = payloadPrefix(manifest); - if (!prefix) { - return std::unexpected(prefix.error()); - } - - std::unordered_set declared; - declared.reserve(manifest.files.size()); - for (const auto& entry : manifest.files) { - if (!isImmutablePayloadPath(entry.path, *prefix)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "release manifest entry is outside the immutable " - "payload roots: " + - entry.path.string()); - } - declared.insert(entry.path.generic_string()); - } - - const auto payloadRoot = manifest.root / *prefix; - std::error_code payloadError; - const auto payloadStatus = - std::filesystem::symlink_status(payloadRoot, payloadError); - if (payloadError || - payloadStatus.type() != std::filesystem::file_type::directory) { - return Api::fail(Api::ErrorCode::NotFound, - "immutable payload root is missing or has an " - "unexpected type: " + - payloadRoot.string()); - } - if (hasUnsafeWritablePermissions(payloadStatus)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "immutable payload directory is group- or " - "world-writable: " + - payloadRoot.string()); - } - - for (const auto name : kImmutableRoots) { - const auto directory = manifest.root / *prefix / name; - std::error_code error; - const auto rootStatus = - std::filesystem::symlink_status(directory, error); - if (error || rootStatus.type() != - std::filesystem::file_type::directory) { - return Api::fail( - Api::ErrorCode::NotFound, - "immutable payload directory is missing or has an " - "unexpected type: " + - directory.string()); - } - if (hasUnsafeWritablePermissions(rootStatus)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "immutable payload directory is group- or " - "world-writable: " + - directory.string()); - } - - std::filesystem::recursive_directory_iterator iterator{ - directory, std::filesystem::directory_options::none, error}; - const std::filesystem::recursive_directory_iterator end; - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "cannot inspect immutable payload directory: " + - directory.string()); - } - while (iterator != end) { - const auto status = iterator->symlink_status(error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "cannot inspect immutable payload entry: " + - iterator->path().string()); - } - if (status.type() == - std::filesystem::file_type::directory) { - if (hasUnsafeWritablePermissions(status)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "immutable payload directory is group- or " - "world-writable: " + - iterator->path().string()); - } - } else { - const auto relative = - iterator->path().lexically_relative(manifest.root); - if (status.type() != - std::filesystem::file_type::regular && - status.type() != - std::filesystem::file_type::symlink) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "special file is not allowed in " - "immutable payload: " + - relative.string()); - } - if (!declared.contains(relative.generic_string())) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "undeclared immutable payload entry: " + - relative.string()); - } - } - - iterator.increment(error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "cannot traverse immutable payload directory: " + - directory.string()); - } - } - } - return {}; - } - - Api::Result - loadVersionOne(const Void::Json::Value& json, - const std::filesystem::path& root) - { - ReleaseManifest manifest; - manifest.root = root; - manifest.version = json.get_str("version"); - const auto executableEntry = - std::filesystem::path(json.get_str("executable")); - const auto coreEntry = std::filesystem::path(json.get_str("core")); - if (!isSafeRelativePath(executableEntry) || - !isSafeRelativePath(coreEntry)) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "release artifact paths must stay within the " - "manifest directory"); - } - manifest.executable = root / executableEntry; - manifest.core = root / coreEntry; - if (const auto* hashes = json.find("sha256"); - hashes && hashes->is_object()) { - manifest.executableSha256 = hashes->get_str("executable"); - manifest.coreSha256 = hashes->get_str("core"); - } - if (manifest.version.empty() || - !isSha256(manifest.executableSha256) || - !isSha256(manifest.coreSha256)) { - return Api::fail(Api::ErrorCode::ParseError, - "release manifest is missing version, " - "artifacts, or hashes"); - } - return manifest; - } - - Api::Result - loadVersionTwo(const Void::Json::Value& json, - const std::filesystem::path& root) - { - ReleaseManifest manifest; - manifest.schemaVersion = 2; - manifest.root = root; - manifest.version = json.get_str("version"); - const auto executableEntry = - std::filesystem::path(json.get_str("executable")); - const auto coreEntry = std::filesystem::path(json.get_str("core")); - const auto* files = json.child_array("files"); - if (manifest.version.empty() || - !isSafeRelativePath(executableEntry) || - !isSafeRelativePath(coreEntry) || !files || - files->as_array().empty()) { - return Api::fail(Api::ErrorCode::ParseError, - "v2 release manifest is missing version, " - "artifacts, or files"); - } - - std::unordered_set paths; - manifest.files.reserve(files->as_array().size()); - for (const auto& value : files->as_array()) { - if (!value.is_object()) { - return Api::fail(Api::ErrorCode::ParseError, - "release file entries must be objects"); - } - ReleaseFileEntry entry; - entry.path = value.get_str("path"); - if (!isSafeRelativePath(entry.path)) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "release file path is absolute, " - "traversing, or not normalized"); - } - if (!paths.insert(entry.path.generic_string()).second) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "duplicate release file path: " + - entry.path.string()); - } - - const auto type = value.get_str("type"); - if (type == "file") { - entry.type = ReleaseFileType::Regular; - const auto size = parseSize(value); - const auto mode = parseMode(value.get_str("mode")); - entry.sha256 = value.get_str("sha256"); - if (!size || !mode || !isSha256(entry.sha256) || - value.has("target")) { - return Api::fail(Api::ErrorCode::ParseError, - "regular release file entry has " - "invalid metadata: " + - entry.path.string()); - } - entry.size = *size; - entry.mode = *mode; - if ((entry.mode & kUnsafeWritablePermissions) != - std::filesystem::perms::none) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "release file is group- or " - "world-writable: " + - entry.path.string()); - } - } else if (type == "symlink") { - entry.type = ReleaseFileType::Symlink; - entry.target = value.get_str("target"); - if (!isSafeRelativePath(entry.target) || - value.has("size") || value.has("sha256") || - value.has("mode")) { - return Api::fail( - Api::ErrorCode::ParseError, - "symbolic link entry has invalid metadata: " + - entry.path.string()); - } - } else { - return Api::fail(Api::ErrorCode::ParseError, - "unknown release file type: " + type); - } - manifest.files.push_back(std::move(entry)); - } - - const auto executable = std::ranges::find( - manifest.files, executableEntry, &ReleaseFileEntry::path); - const auto core = std::ranges::find(manifest.files, coreEntry, - &ReleaseFileEntry::path); - if (executable == manifest.files.end() || - core == manifest.files.end() || - executable->type != ReleaseFileType::Regular || - core->type != ReleaseFileType::Regular) { - return Api::fail(Api::ErrorCode::ParseError, - "release executable and Core must reference " - "regular file entries"); - } - if ((executable->mode & kExecutablePermissions) == - std::filesystem::perms::none) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "release executable entry is not executable"); - } - - manifest.executable = root / executableEntry; - manifest.core = root / coreEntry; - manifest.executableSha256 = executable->sha256; - manifest.coreSha256 = core->sha256; - return manifest; - } - } // namespace - - Api::Result - ReleaseManifest::load(const std::filesystem::path& manifestPath) - { - auto contents = Void::FileSystem::read_file(manifestPath); - if (!contents) { - return Api::fail(Api::ErrorCode::NotFound, - contents.error().message()); - } - auto json = Void::Json::parse(*contents); - if (!json || !json->is_object()) { - return Api::fail(Api::ErrorCode::ParseError, - json ? "release manifest must be an object" - : "invalid release manifest: " + - json.error().message); - } - - std::error_code error; - auto root = std::filesystem::weakly_canonical( - normalizedAbsolute(manifestPath).parent_path(), error); - if (error) { - return Api::fail(Api::ErrorCode::NotFound, - "cannot resolve release root: " + error.message()); - } - - const auto* schema = json->find("schemaVersion"); - if (!schema) { - return loadVersionOne(*json, root); - } - if (!schema->is_number() || schema->as_number() != 2.0) { - return Api::fail(Api::ErrorCode::IncompatibleVersion, - "unsupported release manifest schema version"); - } - return loadVersionTwo(*json, root); - } - - Api::Result ReleaseManifest::validate() const - { - if (schemaVersion == 1) { - std::error_code rootError; - const auto canonicalRoot = - std::filesystem::weakly_canonical(root, rootError); - if (rootError) { - return Api::fail(Api::ErrorCode::NotFound, - "cannot resolve release root: " + - rootError.message()); - } - for (const auto& [path, expected, executableFile] : - {std::tuple{executable, executableSha256, true}, - std::tuple{core, coreSha256, false}}) { - std::error_code error; - const auto status = - std::filesystem::symlink_status(path, error); - if (error || - status.type() != std::filesystem::file_type::regular) { - return Api::fail( - Api::ErrorCode::NotFound, - "release executable and Core must be regular files"); - } - const auto resolved = std::filesystem::canonical(path, error); - if (error || !isWithin(canonicalRoot, resolved)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "release artifact resolves outside the release root: " + - path.string()); - } - if (executableFile && - (status.permissions() & kExecutablePermissions) == - std::filesystem::perms::none) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "release executable is not executable"); - } - auto actual = sha256(path); - if (!actual) { - return std::unexpected(actual.error()); - } - if (*actual != expected) { - return Api::fail(Api::ErrorCode::IncompatibleVersion, - "SHA-256 mismatch for " + path.string()); - } - } - return {}; - } - - std::error_code rootError; - const auto canonicalRoot = - std::filesystem::weakly_canonical(root, rootError); - if (rootError) { - return Api::fail(Api::ErrorCode::NotFound, - "cannot resolve release root: " + - rootError.message()); - } - for (const auto& entry : files) { - const auto path = root / entry.path; - std::error_code error; - const auto status = std::filesystem::symlink_status(path, error); - if (error || - status.type() == std::filesystem::file_type::not_found) { - return Api::fail(Api::ErrorCode::NotFound, - "release payload entry is missing: " + - entry.path.string()); - } - const auto expectedType = entry.type == ReleaseFileType::Regular - ? std::filesystem::file_type::regular - : std::filesystem::file_type::symlink; - if (status.type() != expectedType) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "unexpected file type for release payload entry: " + - entry.path.string()); - } - - const auto resolved = std::filesystem::canonical(path, error); - if (error || !isWithin(canonicalRoot, resolved)) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "release payload entry resolves outside the " - "release root: " + - entry.path.string()); - } - - if (entry.type == ReleaseFileType::Symlink) { - const auto actualTarget = - std::filesystem::read_symlink(path, error); - if (error || actualTarget.generic_string() != - entry.target.generic_string()) { - return Api::fail(Api::ErrorCode::IncompatibleVersion, - "symbolic link target mismatch for " + - entry.path.string()); - } - continue; - } - - const auto size = std::filesystem::file_size(path, error); - if (error || size != entry.size) { - return Api::fail(Api::ErrorCode::IncompatibleVersion, - "file size mismatch for " + - entry.path.string()); - } - if ((status.permissions() & std::filesystem::perms::mask) != - entry.mode) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "file mode mismatch for " + - entry.path.string()); - } - auto actual = sha256(path); - if (!actual) { - return std::unexpected(actual.error()); - } - if (*actual != entry.sha256) { - return Api::fail(Api::ErrorCode::IncompatibleVersion, - "SHA-256 mismatch for " + entry.path.string()); - } - } - return validateImmutableCoverage(*this); - } - - Api::Result ReleaseManifest::validateInstallLayout() const - { - if (schemaVersion != 2) { - return Api::fail( - Api::ErrorCode::IncompatibleVersion, - "installation validation requires a v2 release manifest"); - } - if (auto result = validate(); !result) { - return result; - } - - const std::filesystem::path expectedExecutable{"bin/echoiond"}; - const std::filesystem::path expectedCore{"lib/Echoion.ts"}; - const std::filesystem::path expectedWeb{"share/echoion/web/index.html"}; - if (executable.lexically_normal() != (root / expectedExecutable) || - core.lexically_normal() != (root / expectedCore)) { - return Api::fail(Api::ErrorCode::IncompatibleVersion, - "installation manifest does not describe the " - "canonical runtime layout"); - } - const auto web = - std::ranges::find(files, expectedWeb, &ReleaseFileEntry::path); - if (web == files.end() || web->type != ReleaseFileType::Regular) { - return Api::fail(Api::ErrorCode::NotFound, - "installation manifest is missing the web " - "dashboard entry point"); - } - return {}; - } -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/RuntimePaths.cpp b/EchoionStandalone/src/RuntimePaths.cpp deleted file mode 100644 index ffceb14..0000000 --- a/EchoionStandalone/src/RuntimePaths.cpp +++ /dev/null @@ -1,194 +0,0 @@ -#include "echoion/standalone/RuntimePaths.hpp" - -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - namespace - { - std::filesystem::path absoluteNormalized(std::filesystem::path path) - { - std::error_code error; - auto absolute = std::filesystem::absolute(path, error); - if (error) { - return path.lexically_normal(); - } - return absolute.lexically_normal(); - } - - bool isWithinOrEqual(const std::filesystem::path& root, - const std::filesystem::path& candidate) - { - const auto relative = candidate.lexically_relative(root); - return !relative.empty() && !relative.is_absolute() && - std::ranges::none_of(relative, [](const auto& component) { - return component == ".."; - }); - } - } // namespace - - std::expected runningExecutablePath() - { - std::error_code error; - auto executable = - std::filesystem::read_symlink("/proc/self/exe", error); - if (error || executable.empty()) { - return std::unexpected("cannot resolve /proc/self/exe: " + - error.message()); - } - auto canonical = std::filesystem::weakly_canonical(executable, error); - if (error) { - return absoluteNormalized(std::move(executable)); - } - return canonical; - } - - std::filesystem::path deriveInstallRoot( - const std::filesystem::path& executablePath, - const std::optional& homeOverride) - { - if (homeOverride && !homeOverride->empty()) { - return absoluteNormalized(*homeOverride); - } - - const auto executableDirectory = - absoluteNormalized(executablePath).parent_path(); - if (executableDirectory.filename() == "bin") { - return executableDirectory.parent_path(); - } - return executableDirectory; - } - - std::filesystem::path resolveCorePath( - const std::filesystem::path& installRoot, - const std::filesystem::path& executableDirectory, - const std::optional& coreOverride) - { - if (coreOverride && !coreOverride->empty()) { - return coreOverride->is_absolute() - ? coreOverride->lexically_normal() - : (installRoot / *coreOverride).lexically_normal(); - } - - const std::array candidates{ - installRoot / "lib" / "Echoion.ts", - executableDirectory / "Echoion.ts", - installRoot / "bin" / "Echoion.ts", - installRoot / "plugins" / "Echoion.ts", - }; - for (const auto& candidate : candidates) { - std::error_code error; - if (std::filesystem::is_regular_file(candidate, error) && !error) { - return candidate.lexically_normal(); - } - } - return candidates.front().lexically_normal(); - } - - std::filesystem::path resolveStateDirectory( - const std::optional& commandLineOverride, - const std::optional& environmentOverride, - const std::optional& xdgStateHome, - const std::optional& userHome, - const std::filesystem::path& fallback) - { - if (commandLineOverride && !commandLineOverride->empty()) { - return absoluteNormalized(*commandLineOverride); - } - if (environmentOverride && !environmentOverride->empty()) { - return absoluteNormalized(*environmentOverride); - } - if (xdgStateHome && !xdgStateHome->empty()) { - return absoluteNormalized(*xdgStateHome / "echoion"); - } - if (userHome && !userHome->empty()) { - return absoluteNormalized(*userHome / ".local" / "state" / - "echoion"); - } - return absoluteNormalized(fallback); - } - - std::optional runtimeWorkingDirectory( - const std::filesystem::path& installRoot, - const std::filesystem::path& executableDirectory) - { - const auto packagedDirectory = installRoot / "share" / "echoion"; - std::error_code error; - if (std::filesystem::is_regular_file( - packagedDirectory / "web" / "index.html", error) && - !error) { - // Installed config paths are rooted at the release prefix (for - // example ./share/echoion/web), so the working directory must be - // the installation root rather than share/echoion itself. - return installRoot; - } - - error.clear(); - if (std::filesystem::is_regular_file( - executableDirectory / "web" / "index.html", error) && - !error) { - return executableDirectory; - } - return std::nullopt; - } - - std::optional - bundledCertificateBundle(const std::filesystem::path& installRoot) - { - const auto bundle = - installRoot / "share" / "echoion" / "certs" / "ca-certificates.crt"; - std::error_code error; - if (!std::filesystem::is_regular_file(bundle, error) || error || - std::filesystem::file_size(bundle, error) == 0 || error) { - return std::nullopt; - } - return bundle.lexically_normal(); - } - - std::expected - resolveAvatarCacheDirectory( - const std::filesystem::path& configuredDirectory, - const std::filesystem::path& requestedDirectory) - { - if (configuredDirectory.empty()) { - return std::unexpected("avatar cache directory is not configured"); - } - - std::error_code error; - const auto configured = std::filesystem::weakly_canonical( - absoluteNormalized(configuredDirectory), error); - if (error) { - return std::unexpected("cannot resolve avatar cache directory: " + - error.message()); - } - - if (!requestedDirectory.empty() && !requestedDirectory.is_absolute() && - (requestedDirectory != requestedDirectory.lexically_normal() || - std::ranges::any_of(requestedDirectory, [](const auto& component) { - return component == "." || component == ".."; - }))) { - return std::unexpected("avatar cache subdirectory must be " - "normalized and non-traversing"); - } - - const auto requested = requestedDirectory.empty() ? configured - : requestedDirectory.is_absolute() - ? requestedDirectory - : configured / requestedDirectory; - const auto resolved = std::filesystem::weakly_canonical( - absoluteNormalized(requested), error); - if (error) { - return std::unexpected( - "cannot resolve requested avatar directory: " + - error.message()); - } - if (!isWithinOrEqual(configured, resolved)) { - return std::unexpected("requested avatar directory is outside the " - "configured state cache"); - } - return resolved; - } -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/StandaloneClientInterface.cpp b/EchoionStandalone/src/StandaloneClientInterface.cpp deleted file mode 100644 index beb05bf..0000000 --- a/EchoionStandalone/src/StandaloneClientInterface.cpp +++ /dev/null @@ -1,1256 +0,0 @@ -#include "echoion/standalone/AudioEncoder.hpp" -#include "echoion/standalone/MessageChunker.hpp" -#include "echoion/standalone/RuntimePaths.hpp" -#include "echoion/standalone/StandaloneClientInterface.hpp" - -#include -#include - -#include -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - namespace - { - constexpr const char* LOG = "Standalone"; - - Api::Error teamSpeakError(const Void::TeamSpeak::Error& error) - { - using Code = Void::TeamSpeak::Error::Code; - Api::ErrorCode code = Api::ErrorCode::PluginError; - switch (error.code) { - case Code::InvalidArgument: - code = Api::ErrorCode::InvalidArgument; - break; - case Code::NotConnected: - code = Api::ErrorCode::ServiceUnavailable; - break; - case Code::Timeout: - case Code::Io: - code = Api::ErrorCode::NetworkError; - break; - case Code::NotSupported: - code = Api::ErrorCode::NotSupported; - break; - case Code::Protocol: - break; - } - return {code, error.message, "VoidTeamspeak"}; - } - - std::optional checkedClientId(uint64_t value) - { - if (value == 0 || value > std::numeric_limits::max()) { - return std::nullopt; - } - return Void::TeamSpeak::ClientId{static_cast(value)}; - } - - Api::ClientInfo apiClient(const Void::TeamSpeak::RemoteClient& client) - { - std::vector groups; - groups.reserve(client.serverGroups.size()); - for (const auto group : client.serverGroups) { - groups.push_back(group.value); - } - return { - .id = client.id.value, - .databaseId = - client.databaseId - ? std::optional{client.databaseId.value} - : std::nullopt, - .nickname = client.nickname, - .uniqueIdentifier = - client.uniqueId.empty() - ? std::nullopt - : std::optional{client.uniqueId}, - .channelId = client.channel.value, - .isTalking = client.talking, - .isMuted = client.muted(), - .isDeafened = client.deafened(), - .isAway = client.away, - .isQuery = client.isQuery(), - .serverGroups = std::move(groups), - }; - } - - Api::ChannelInfo apiChannel(const Void::TeamSpeak::Channel& channel, - uint32_t currentClients) - { - const auto maxClients = - channel.unlimitedClients || channel.maxClients <= 0 - ? 0U - : static_cast(channel.maxClients); - return { - .id = channel.id.value, - .name = channel.name, - .parentId = channel.parent - ? std::optional{channel.parent->value} - : std::nullopt, - .order = channel.orderAfter.value, - .isDefault = channel.defaultChannel, - .isPermanent = channel.permanent, - .isSemiPermanent = channel.semiPermanent, - .hasPassword = channel.passwordProtected, - .maxClients = maxClients, - .currentClients = currentClients, - }; - } - - } // namespace - - StandaloneClientInterface::StandaloneClientInterface( - StandaloneSettings settings) - : settings_(std::move(settings)) - { - } - - StandaloneClientInterface::~StandaloneClientInterface() - { - (void)shutdown(); - } - - Api::Result StandaloneClientInterface::initialize() - { - if (initialized_.exchange(true)) { - return {}; - } - encoder_ = std::make_unique(settings_.opusBitrate); - client_ = std::make_unique(); - Void::Log::info(LOG, "Standalone client interface initialized"); - return {}; - } - - Api::Result StandaloneClientInterface::shutdown() - { - if (!initialized_.exchange(false)) { - return {}; - } - if (client_) { - client_->close(); - } - if (snapshotThread_.joinable()) { - snapshotThread_.request_stop(); - snapshotThread_.join(); - } - if (client_) { - client_.reset(); - } - encoder_.reset(); - return {}; - } - - // ---- Connection -------------------------------------------------------- - - Api::Result StandaloneClientInterface::connectToServer( - const Api::ServerConfig& config) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, - "interface not initialized"); - } - currentConfig_ = config; - - // Load or create the persistent identity. - try { - std::filesystem::path idPath(settings_.identityPath); - if (!idPath.empty() && std::filesystem::exists(idPath)) { - identity_ = std::make_shared( - Void::TeamSpeak::Identity::load(idPath.string())); - Void::Log::info(LOG, "Loaded identity (uid={})", - identity_->uid()); - } else { - Void::Log::info(LOG, - "Generating identity (security level {})...", - settings_.securityLevel); - identity_ = std::make_shared( - Void::TeamSpeak::Identity::generate( - settings_.securityLevel)); - if (!idPath.empty()) { - std::filesystem::create_directories(idPath.parent_path()); - identity_->save(idPath.string()); - } - Void::Log::info(LOG, "Identity ready (uid={})", - identity_->uid()); - } - } catch (const std::exception& e) { - return Api::fail(Api::ErrorCode::PluginError, - std::string("identity error: ") + e.what()); - } - - wireCallbacks(); - - Void::TeamSpeak::ConnectOptions opts; - opts.host = config.address; - opts.port = config.port ? config.port : 9987; - opts.identity = identity_; - opts.nickname = - config.nickname.empty() ? "EchoionBot" : config.nickname; - opts.serverPassword = config.serverPassword; - opts.defaultChannel = config.defaultChannelId.value_or(std::string{}); - opts.channelPassword = config.channelPassword.value_or(std::string{}); - - if (auto connected = client_->connect(opts); !connected) { - return Api::fail(Api::ErrorCode::NetworkError, - "connect failed: " + connected.error().message); - } - Void::Log::info(LOG, "Connecting to {}:{} as {}", opts.host, opts.port, - opts.nickname); - return {}; - } - - void StandaloneClientInterface::wireCallbacks() - { - Void::TeamSpeak::Events cb; - cb.connected = [this] { - if (snapshotThread_.joinable()) { - snapshotThread_.request_stop(); - snapshotThread_.join(); - } - snapshotThread_ = std::jthread([this] { loadInitialSnapshot(); }); - }; - cb.disconnected = [this] { - Void::Log::warn(LOG, "Disconnected from server"); - { - std::lock_guard lock(mirrorMutex_); - clients_.clear(); - channels_.clear(); - serverInfo_.reset(); - clientIps_.clear(); - avatarHashes_.clear(); - avatarUrls_.clear(); - } - - // The directory service refreshes from topology events. Publish one - // after clearing the mirrors so a disconnect cannot leave the - // public dashboard reporting a connected server with stale clients. - Api::PluginEvent event; - event.type = Api::PluginEventType::ChannelUpdated; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.error = [](const Void::TeamSpeak::Error& error) { - Void::Log::error(LOG, "Protocol error: {}", error.message); - }; - cb.clientEntered = [this](const Void::TeamSpeak::RemoteClient& client) { - { - std::lock_guard lock{mirrorMutex_}; - clients_[client.id.value] = client; - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ClientConnected; - event.clientId = client.id.value; - event.clientName = client.nickname; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.clientLeft = [this](const Void::TeamSpeak::ClientLeft& left) { - std::string nickname; - { - std::lock_guard lock{mirrorMutex_}; - if (const auto iterator = clients_.find(left.id.value); - iterator != clients_.end()) { - nickname = iterator->second.nickname; - clients_.erase(iterator); - } - clientIps_.erase(left.id.value); - avatarHashes_.erase(left.id.value); - avatarUrls_.erase(left.id.value); - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ClientDisconnected; - event.clientId = left.id.value; - event.clientName = std::move(nickname); - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.clientMoved = [this](const Void::TeamSpeak::ClientMoved& moved) { - { - std::lock_guard lock{mirrorMutex_}; - auto& client = clients_[moved.id.value]; - client.id = moved.id; - client.channel = moved.channel; - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ClientMoved; - event.clientId = moved.id.value; - event.targetChannelId = moved.channel.value; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.clientUpdated = - [this](const Void::TeamSpeak::ClientUpdated& update) { - { - std::lock_guard lock{mirrorMutex_}; - auto& client = clients_[update.id.value]; - client.id = update.id; - if (update.nickname) { - client.nickname = *update.nickname; - } - if (update.uniqueId) { - client.uniqueId = *update.uniqueId; - } - if (update.inputMuted) { - client.inputMuted = *update.inputMuted; - } - if (update.outputMuted) { - client.outputMuted = *update.outputMuted; - } - if (update.inputHardware) { - client.inputHardware = *update.inputHardware; - } - if (update.outputHardware) { - client.outputHardware = *update.outputHardware; - } - if (update.away) { - client.away = *update.away; - } - if (update.talking) { - client.talking = *update.talking; - } - if (update.recording) { - client.recording = *update.recording; - } - if (update.channelCommander) { - client.channelCommander = *update.channelCommander; - } - if (update.prioritySpeaker) { - client.prioritySpeaker = *update.prioritySpeaker; - } - if (update.avatarHash) { - if (update.avatarHash->empty()) { - avatarHashes_.erase(update.id.value); - } else { - avatarHashes_[update.id.value] = *update.avatarHash; - } - } - if (update.avatarUrl) { - if (update.avatarUrl->empty()) { - avatarUrls_.erase(update.id.value); - } else { - avatarUrls_[update.id.value] = *update.avatarUrl; - } - } - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ClientUpdated; - event.clientId = update.id.value; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.talkStatusChanged = - [this](const Void::TeamSpeak::TalkStatusChanged& status) { - { - std::lock_guard lock{mirrorMutex_}; - auto& client = clients_[status.id.value]; - client.id = status.id; - client.talking = status.talking; - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ClientUpdated; - event.clientId = status.id.value; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.textMessage = [this](const Void::TeamSpeak::TextMessage& message) { - if (client_ && message.invoker == client_->id()) { - return; - } - Api::PluginEvent event; - event.type = Api::PluginEventType::TextMessageReceived; - event.clientId = message.invoker.value; - event.clientName = message.invokerName; - event.message = message.message; - if (message.target.kind == - Void::TeamSpeak::TextTargetKind::Channel) { - event.targetChannelId = message.target.id; - } - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.channelChanged = - [this](const Void::TeamSpeak::ChannelChanged& change) { - { - std::lock_guard lock{mirrorMutex_}; - const auto id = change.id.value; - if (change.kind == - Void::TeamSpeak::ChannelChangeKind::Deleted) { - channels_.erase(id); - } else { - auto& channel = channels_[id]; - channel.id = change.id; - change.patch.applyTo(channel); - } - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ChannelUpdated; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.serverUpdated = - [this](const Void::TeamSpeak::ServerUpdated& update) { - { - std::lock_guard lock{mirrorMutex_}; - if (!serverInfo_) { - serverInfo_.emplace(); - } - if (update.name) { - serverInfo_->name = *update.name; - } - if (update.welcomeMessage) { - serverInfo_->welcomeMessage = *update.welcomeMessage; - } - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ChannelUpdated; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.serverGroupMembershipChanged = - [this](const Void::TeamSpeak::ServerGroupMembershipChanged& - membership) { - uint64_t changedClient = 0; - { - std::lock_guard lock{mirrorMutex_}; - for (auto& [id, client] : clients_) { - if (client.databaseId != membership.client) { - continue; - } - changedClient = id; - auto group = std::ranges::find(client.serverGroups, - membership.group); - if (membership.added && - group == client.serverGroups.end()) { - client.serverGroups.push_back(membership.group); - } else if (!membership.added && - group != client.serverGroups.end()) { - client.serverGroups.erase(group); - } - break; - } - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ClientUpdated; - event.clientId = changedClient; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - cb.debug = [](std::string_view msg) { - Void::Log::debug(LOG, "{}", msg); - }; - cb.voice = [this](std::span) { - Api::PluginEvent event; - event.type = Api::PluginEventType::VoiceDataReceived; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - }; - client_->setEvents(std::move(cb)); - } - - Api::Result StandaloneClientInterface::commandResult( - const Void::Result::Result& result) const - { - return result ? Api::Result{} - : std::unexpected(teamSpeakError(result.error())); - } - - void StandaloneClientInterface::loadInitialSnapshot() - { - if (!client_) { - return; - } - auto clients = client_->clients(); - if (clients) { - std::lock_guard lock{mirrorMutex_}; - clients_.clear(); - for (auto& remote : *clients) { - clients_.emplace(remote.id.value, std::move(remote)); - } - } else { - Void::Log::warn(LOG, "Initial client snapshot failed: {}", - clients.error().message); - } - auto channels = client_->channels(); - if (channels) { - std::lock_guard lock{mirrorMutex_}; - channels_.clear(); - for (auto& channel : *channels) { - channels_.emplace(channel.id.value, std::move(channel)); - } - } else { - Void::Log::warn(LOG, "Initial channel snapshot failed: {}", - channels.error().message); - } - if (auto server = client_->serverInfo(); server) { - std::lock_guard lock{mirrorMutex_}; - serverInfo_ = std::move(*server); - } else { - Void::Log::warn(LOG, "Initial server snapshot failed: {}", - server.error().message); - } - if (auto subscribed = client_->subscribeAllChannels(); !subscribed) { - Void::Log::warn(LOG, "Channel subscription failed: {}", - subscribed.error().message); - } - Api::PluginEvent event; - event.type = Api::PluginEventType::ConnectionEstablished; - event.timestamp = std::chrono::system_clock::now(); - broadcast(event); - } - - Api::Result StandaloneClientInterface::disconnectFromServer() - { - if (client_) { - client_->disconnect(); - } - return {}; - } - - bool StandaloneClientInterface::isConnected() const - { - return client_ && - client_->state() == Void::TeamSpeak::ConnectionState::Connected; - } - - Api::Result StandaloneClientInterface::reconnect() - { - (void)disconnectFromServer(); - return connectToServer(currentConfig_); - } - - // TeamSpeak command parsing and event normalization live in VoidTeamspeak. - // This adapter only mirrors its typed callbacks into Echoion events. - void StandaloneClientInterface::broadcast(const Api::PluginEvent& event) - { - eventCallbacks_.dispatch(event); - } - - // ---- Clients / channels ------------------------------------------------ - - Api::Result> - StandaloneClientInterface::getClients() - { - std::lock_guard lock(mirrorMutex_); - std::vector out; - out.reserve(clients_.size()); - for (const auto& [id, c] : clients_) { - (void)id; - out.push_back(apiClient(c)); - } - return out; - } - - Api::Result> - StandaloneClientInterface::getClient(uint64_t clientId) - { - std::lock_guard lock(mirrorMutex_); - auto it = clients_.find(clientId); - if (it == clients_.end()) { - return std::optional{}; - } - return std::optional{apiClient(it->second)}; - } - - Api::Result> - StandaloneClientInterface::getClientIp(uint64_t clientId) - { - if (!client_ || !isConnected()) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "not connected"); - } - const auto id = checkedClientId(clientId); - if (!id) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID exceeds TeamSpeak protocol range"); - } - auto details = client_->clientDetails(*id); - if (!details) { - return std::unexpected(teamSpeakError(details.error())); - } - { - std::lock_guard lock{mirrorMutex_}; - clients_[clientId] = details->client; - if (details->connectionIp) { - clientIps_[clientId] = *details->connectionIp; - } else { - clientIps_.erase(clientId); - } - } - return details->connectionIp; - } - - Api::Result> - StandaloneClientInterface::getClientAvatarPath(uint64_t clientId) - { - std::lock_guard lock(mirrorMutex_); - const auto entry = avatarPaths_.find(clientId); - if (entry == avatarPaths_.end() || - !std::filesystem::exists(entry->second)) { - return std::optional{}; - } - return std::optional{entry->second}; - } - - Api::Result> - StandaloneClientInterface::getClientAvatarUrl(uint64_t clientId) - { - if (!client_ || !isConnected()) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "not connected"); - } - const auto id = checkedClientId(clientId); - if (!id) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID exceeds TeamSpeak protocol range"); - } - auto details = client_->clientDetails(*id); - if (!details) { - return std::unexpected(teamSpeakError(details.error())); - } - { - std::lock_guard lock{mirrorMutex_}; - clients_[clientId] = details->client; - if (details->avatarUrl) { - avatarUrls_[clientId] = *details->avatarUrl; - } else { - avatarUrls_.erase(clientId); - } - } - return details->avatarUrl; - } - - Api::Result> - StandaloneClientInterface::requestClientAvatar( - uint64_t clientId, const std::string& destDir) - { - if (!client_ || !isConnected()) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "not connected"); - } - const auto id = checkedClientId(clientId); - if (!id) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID exceeds TeamSpeak protocol range"); - } - auto details = client_->clientDetails(*id); - if (!details) { - return std::unexpected(teamSpeakError(details.error())); - } - const std::string hash = details->avatarHash.value_or(""); - { - std::lock_guard lock{mirrorMutex_}; - clients_[clientId] = details->client; - if (!hash.empty()) { - avatarHashes_[clientId] = hash; - } - if (details->avatarUrl) { - avatarUrls_[clientId] = *details->avatarUrl; - } - } - if (hash.empty()) { - return std::optional{}; - } - if (hash.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq" - "rstuvwxyz0123456789_-") != - std::string::npos) { - return Api::fail(Api::ErrorCode::ParseError, - "server returned an unsafe avatar hash"); - } - const auto directory = resolveAvatarCacheDirectory( - settings_.avatarCachePath, std::filesystem::path{destDir}); - if (!directory) { - return Api::fail(Api::ErrorCode::InvalidArgument, - directory.error()); - } - std::error_code directoryError; - std::filesystem::create_directories(*directory, directoryError); - if (directoryError) { - return Api::fail(Api::ErrorCode::PluginError, - "cannot create avatar cache directory"); - } - const auto destination = (*directory / ("avatar_" + hash)).string(); - if (!std::filesystem::exists(destination)) { - const auto result = - client_->download("/avatar_" + hash, destination); - if (!result) { - return std::unexpected(teamSpeakError(result.error())); - } - } - { - std::lock_guard lock(mirrorMutex_); - avatarPaths_[clientId] = destination; - } - return std::optional{destination}; - } - - Api::Result> - StandaloneClientInterface::getChannels() const - { - std::lock_guard lock(mirrorMutex_); - std::vector out; - out.reserve(channels_.size()); - for (const auto& [id, c] : channels_) { - const auto current = static_cast( - std::ranges::count_if(clients_, [&](const auto& entry) { - return !entry.second.isQuery() && - entry.second.channel.value == id; - })); - out.push_back(apiChannel(c, current)); - } - return out; - } - - Api::Result> - StandaloneClientInterface::getChannel(uint64_t channelId) const - { - std::lock_guard lock(mirrorMutex_); - auto it = channels_.find(channelId); - if (it == channels_.end()) { - return std::optional{}; - } - const auto current = static_cast( - std::ranges::count_if(clients_, [&](const auto& entry) { - return !entry.second.isQuery() && - entry.second.channel.value == channelId; - })); - return std::optional{apiChannel(it->second, current)}; - } - - Api::Result StandaloneClientInterface::moveClient(uint64_t clientId, - uint64_t channelId) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - const auto id = checkedClientId(clientId); - if (!id || channelId == 0) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "valid client and channel IDs are required"); - } - auto moved = commandResult( - client_->move(*id, Void::TeamSpeak::ChannelId{channelId})); - if (moved) { - std::lock_guard lock{mirrorMutex_}; - if (auto client = clients_.find(clientId); - client != clients_.end()) { - client->second.channel = Void::TeamSpeak::ChannelId{channelId}; - } - } - return moved; - } - - Api::Result - StandaloneClientInterface::kickClient(uint64_t clientId, - const std::string& reason) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - const auto id = checkedClientId(clientId); - if (!id) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID exceeds TeamSpeak protocol range"); - } - return commandResult( - client_->kick(*id, Void::TeamSpeak::KickScope::Server, reason)); - } - - Api::Result StandaloneClientInterface::kickClientFromChannel( - uint64_t clientId, const std::string& reason) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - const auto id = checkedClientId(clientId); - if (!id) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID exceeds TeamSpeak protocol range"); - } - return commandResult( - client_->kick(*id, Void::TeamSpeak::KickScope::Channel, reason)); - } - - Api::Result StandaloneClientInterface::banClient( - uint64_t clientId, uint64_t durationSeconds, const std::string& reason) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - const auto id = checkedClientId(clientId); - if (!id || durationSeconds > static_cast( - std::numeric_limits::max())) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID or ban duration is out of range"); - } - Void::TeamSpeak::BanOptions options; - options.reason = reason; - if (durationSeconds != 0) { - options.duration = - std::chrono::seconds{static_cast(durationSeconds)}; - } - auto result = client_->ban(*id, options); - return result ? Api::Result{} - : std::unexpected(teamSpeakError(result.error())); - } - - Api::Result> StandaloneClientInterface::getBans() - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - auto result = client_->bans(); - if (!result) { - return std::unexpected(teamSpeakError(result.error())); - } - std::vector bans; - bans.reserve(result->size()); - for (const auto& ban : *result) { - bans.push_back({ - .id = ban.id.value, - .uniqueIdentifier = - ban.uniqueId.empty() - ? std::nullopt - : std::optional{ban.uniqueId}, - .nickname = ban.lastNickname.empty() - ? std::nullopt - : std::optional{ban.lastNickname}, - .reason = ban.reason, - .createdAt = ban.createdAtUnixSeconds, - .durationSeconds = static_cast(ban.duration.count()), - }); - } - return bans; - } - - Api::Result StandaloneClientInterface::unban(uint64_t banId) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - if (banId == 0) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "ban ID is required"); - } - return commandResult(client_->unban(Void::TeamSpeak::BanId{banId})); - } - - Api::Result StandaloneClientInterface::createChannel( - const Api::ChannelCreateOptions& options) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - if (options.maxClients > - static_cast(std::numeric_limits::max())) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "channel capacity is out of range"); - } - Void::TeamSpeak::ChannelCreateOptions native; - native.name = options.name; - native.topic = options.topic.value_or(""); - native.description = options.description.value_or(""); - native.password = options.password.value_or(""); - native.lifetime = options.permanent - ? Void::TeamSpeak::ChannelLifetime::Permanent - : Void::TeamSpeak::ChannelLifetime::Temporary; - native.unlimitedClients = options.maxClients == 0; - if (options.parentId && *options.parentId != 0) { - native.parent = Void::TeamSpeak::ChannelId{*options.parentId}; - } - if (options.orderAfterId && *options.orderAfterId != 0) { - native.orderAfter = - Void::TeamSpeak::ChannelId{*options.orderAfterId}; - } - if (options.maxClients != 0) { - native.maxClients = static_cast(options.maxClients); - } - auto result = client_->createChannel(native); - if (!result) { - return std::unexpected(teamSpeakError(result.error())); - } - { - std::lock_guard lock{mirrorMutex_}; - Void::TeamSpeak::Channel created; - created.id = *result; - created.parent = native.parent; - created.orderAfter = - native.orderAfter.value_or(Void::TeamSpeak::ChannelId{}); - created.name = native.name; - created.topic = native.topic; - created.description = native.description; - created.maxClients = native.maxClients.value_or(0); - created.passwordProtected = !native.password.empty(); - created.permanent = - native.lifetime == Void::TeamSpeak::ChannelLifetime::Permanent; - created.semiPermanent = - native.lifetime == - Void::TeamSpeak::ChannelLifetime::SemiPermanent; - created.unlimitedClients = native.unlimitedClients; - channels_[result->value] = std::move(created); - } - return result->value; - } - - Api::Result StandaloneClientInterface::editChannel( - uint64_t channelId, const Api::ChannelEditOptions& options) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - if (channelId == 0 || - (options.maxClients && - *options.maxClients > - static_cast(std::numeric_limits::max()))) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "channel ID or capacity is out of range"); - } - Void::TeamSpeak::ChannelEditOptions native; - native.name = options.name; - native.topic = options.topic; - native.description = options.description; - native.password = options.password; - if (options.maxClients) { - native.unlimitedClients = *options.maxClients == 0; - if (*options.maxClients != 0) { - native.maxClients = static_cast(*options.maxClients); - } - } - if (options.permanent) { - native.lifetime = *options.permanent - ? Void::TeamSpeak::ChannelLifetime::Permanent - : Void::TeamSpeak::ChannelLifetime::Temporary; - } - auto edited = commandResult(client_->editChannel( - Void::TeamSpeak::ChannelId{channelId}, native)); - if (edited) { - std::lock_guard lock{mirrorMutex_}; - if (auto channel = channels_.find(channelId); - channel != channels_.end()) { - if (options.name) { - channel->second.name = *options.name; - } - if (options.topic) { - channel->second.topic = *options.topic; - } - if (options.description) { - channel->second.description = *options.description; - } - if (options.password) { - channel->second.passwordProtected = - !options.password->empty(); - } - if (options.maxClients) { - channel->second.unlimitedClients = *options.maxClients == 0; - channel->second.maxClients = - static_cast(*options.maxClients); - } - if (options.permanent) { - channel->second.permanent = *options.permanent; - channel->second.semiPermanent = false; - } - } - } - return edited; - } - - Api::Result StandaloneClientInterface::reorderChannel( - uint64_t channelId, uint64_t parentId, uint64_t orderAfterId) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - if (channelId == 0) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "channel ID is required"); - } - const auto parent = - parentId == 0 ? std::nullopt - : std::optional{Void::TeamSpeak::ChannelId{parentId}}; - const auto after = - orderAfterId == 0 - ? std::nullopt - : std::optional{Void::TeamSpeak::ChannelId{orderAfterId}}; - auto reordered = commandResult(client_->reorderChannel( - Void::TeamSpeak::ChannelId{channelId}, parent, after)); - if (reordered) { - std::lock_guard lock{mirrorMutex_}; - if (auto channel = channels_.find(channelId); - channel != channels_.end()) { - channel->second.parent = parent; - channel->second.orderAfter = - after.value_or(Void::TeamSpeak::ChannelId{}); - } - } - return reordered; - } - - Api::Result - StandaloneClientInterface::deleteChannel(uint64_t channelId, bool force) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - if (channelId == 0) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "channel ID is required"); - } - auto removed = commandResult(client_->deleteChannel( - Void::TeamSpeak::ChannelId{channelId}, force)); - if (removed) { - std::lock_guard lock{mirrorMutex_}; - channels_.erase(channelId); - } - return removed; - } - - Api::Result> - StandaloneClientInterface::getServerGroups() - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - auto result = client_->serverGroups(); - if (!result) { - return std::unexpected(teamSpeakError(result.error())); - } - uint64_t defaultGroup = 0; - { - std::lock_guard lock{mirrorMutex_}; - if (serverInfo_) { - defaultGroup = serverInfo_->defaultServerGroup.value; - } - } - std::vector groups; - groups.reserve(result->size()); - for (const auto& group : *result) { - groups.push_back({.id = group.id.value, - .name = group.name, - .isDefault = group.id.value == defaultGroup}); - } - return groups; - } - - Api::Result StandaloneClientInterface::addClientToServerGroup( - uint64_t groupId, uint64_t clientDatabaseId) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - auto added = commandResult(client_->addServerGroupMember( - Void::TeamSpeak::ServerGroupId{groupId}, - Void::TeamSpeak::ClientDatabaseId{clientDatabaseId})); - if (added) { - std::lock_guard lock{mirrorMutex_}; - for (auto& [id, remote] : clients_) { - (void)id; - if (remote.databaseId.value != clientDatabaseId) { - continue; - } - const auto group = Void::TeamSpeak::ServerGroupId{groupId}; - if (std::ranges::find(remote.serverGroups, group) == - remote.serverGroups.end()) { - remote.serverGroups.push_back(group); - } - break; - } - } - return added; - } - - Api::Result StandaloneClientInterface::removeClientFromServerGroup( - uint64_t groupId, uint64_t clientDatabaseId) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - auto removed = commandResult(client_->removeServerGroupMember( - Void::TeamSpeak::ServerGroupId{groupId}, - Void::TeamSpeak::ClientDatabaseId{clientDatabaseId})); - if (removed) { - std::lock_guard lock{mirrorMutex_}; - for (auto& [id, remote] : clients_) { - (void)id; - if (remote.databaseId.value != clientDatabaseId) { - continue; - } - const auto group = Void::TeamSpeak::ServerGroupId{groupId}; - if (const auto current = - std::ranges::find(remote.serverGroups, group); - current != remote.serverGroups.end()) { - remote.serverGroups.erase(current); - } - break; - } - } - return removed; - } - - Api::Result - StandaloneClientInterface::getTeamSpeakServerInfo() - { - std::lock_guard lock{mirrorMutex_}; - if (!serverInfo_) { - return Api::fail( - Api::ErrorCode::ServiceUnavailable, - "TeamSpeak server information is not available yet"); - } - return Api::ServerInfo{ - .id = serverInfo_->id.value, - .name = serverInfo_->name, - .welcomeMessage = serverInfo_->welcomeMessage, - .maxClients = static_cast(std::min( - serverInfo_->maxClients, std::numeric_limits::max())), - .currentClients = static_cast( - std::min(serverInfo_->clientCount, - std::numeric_limits::max())), - }; - } - - // ---- Messaging --------------------------------------------------------- - - Api::Result - StandaloneClientInterface::sendTextMessage(uint64_t targetId, - const std::string& message) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - const auto id = checkedClientId(targetId); - if (!id) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "client ID exceeds TeamSpeak protocol range"); - } - for (const auto& chunk : chunkMessage(message)) { - if (auto result = - commandResult(client_->sendPrivateMessage(*id, chunk)); - !result) { - Void::Log::warn( - LOG, "Failed to send help/reply chunk ({} bytes): {}", - chunk.size(), result.error().message); - return result; - } - } - return {}; - } - - Api::Result StandaloneClientInterface::sendChannelMessage( - uint64_t channelId, const std::string& message) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - return commandResult(client_->sendChannelMessage( - Void::TeamSpeak::ChannelId{channelId}, message)); - } - - Api::Result - StandaloneClientInterface::sendServerMessage(const std::string& message) - { - if (!client_) { - return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); - } - return commandResult(client_->sendServerMessage(message)); - } - - // ---- Audio ------------------------------------------------------------- - - Api::Result StandaloneClientInterface::sendAudioData( - const std::span& data) - { - if (!client_ || !encoder_ || - client_->state() != Void::TeamSpeak::ConnectionState::Connected) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "not connected"); - } - std::vector whisper; - { - std::lock_guard lock(mirrorMutex_); - whisper = whisperList_; - } - auto frames = encoder_->encode(data); - for (const auto& f : frames) { - if (whisper.empty()) { - if (auto sent = client_->sendVoice(f); !sent) { - return Api::fail(Api::ErrorCode::NetworkError, - sent.error().message); - } - } else { - Void::TeamSpeak::WhisperTargets targets; - targets.clients.reserve(whisper.size()); - for (uint64_t c : whisper) { - targets.clients.push_back( - Void::TeamSpeak::ClientId{static_cast(c)}); - } - if (auto sent = client_->sendWhisper(f, targets); !sent) { - return Api::fail(Api::ErrorCode::NetworkError, - sent.error().message); - } - } - } - return {}; - } - - Api::Result StandaloneClientInterface::setWhisperList( - const std::vector& clientIds) - { - if (std::ranges::any_of(clientIds, [](uint64_t clientId) { - return clientId > std::numeric_limits::max(); - })) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "whisper client ID exceeds protocol range"); - } - std::lock_guard lock(mirrorMutex_); - whisperList_ = clientIds; - return {}; - } - - // ---- Events ------------------------------------------------------------ - - void StandaloneClientInterface::registerEventCallback( - const Api::EventCallback& cb) - { - eventCallbacks_.add(cb); - } - - void StandaloneClientInterface::unregisterEventCallback( - const Api::EventCallback&) - { - // Callbacks are not individually comparable (std::function); the host - // registers a single Core callback for the process lifetime, so a full - // clear on unregister is sufficient and matches usage. - quiesceEventCallbacks(); - } - - Api::Result - StandaloneClientInterface::hostControl(const std::string& method, - const std::string& requestJson) - { - HostControlHandler handler; - { - std::lock_guard lock(hostControlMutex_); - handler = hostControlHandler_; - } - if (!handler) { - return Api::fail(Api::ErrorCode::ServiceUnavailable, - "host control plane is not ready"); - } - return handler(method, requestJson); - } - - void StandaloneClientInterface::setHostControlHandler( - HostControlHandler handler) - { - std::lock_guard lock(hostControlMutex_); - hostControlHandler_ = std::move(handler); - } - - void StandaloneClientInterface::quiesceEventCallbacks() - { - eventCallbacks_.quiesce(); - } - -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/UpdateService.cpp b/EchoionStandalone/src/UpdateService.cpp deleted file mode 100644 index 58f0a22..0000000 --- a/EchoionStandalone/src/UpdateService.cpp +++ /dev/null @@ -1,3431 +0,0 @@ -#include "echoion/standalone/UpdateService.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Standalone -{ - namespace - { - using Void::Json::Value; - - constexpr auto kMinimumCheckInterval = std::chrono::minutes{5}; - constexpr auto kMaximumCheckInterval = std::chrono::hours{24 * 30}; - constexpr auto kMaximumRuntimeDeferral = std::chrono::hours{24 * 7}; - constexpr auto kUnsignedConfirmationLifetime = std::chrono::minutes{10}; - constexpr std::uint64_t kMaximumArtifactBytes = - 2ULL * 1024 * 1024 * 1024; - - struct CandidateRecord { - Void::Update::Release release; - std::string id; - std::string source; - bool signedFeed = true; - std::chrono::system_clock::time_point discoveredAt; - std::string confirmationToken; - std::chrono::system_clock::time_point confirmationExpiresAt{}; - bool unsignedAuthorized = false; - bool applying = false; - }; - - struct FetchedFeed { - Void::Update::Feed feed; - bool signedFeed = true; - }; - - struct PluginInventoryEntry { - std::string id; - std::string name; - std::string version; - std::filesystem::path path; - bool managed = false; - }; - - struct PendingCoreAction { - std::string action; - std::string version; - std::string candidateId; - std::filesystem::path path; - std::optional previousVersion; - bool activationPending = true; - bool processing = false; - }; - - struct HistoryEntry { - std::chrono::system_clock::time_point timestamp; - std::string component; - std::string pluginId; - std::string action; - std::string version; - std::string result; - std::string message; - std::string actor; - }; - - [[nodiscard]] std::optional - parseVersion(std::string_view value) - { - if (value.empty()) { - return std::nullopt; - } - return Void::Semver::parse(value); - } - - [[nodiscard]] Void::Semver::Version - versionOrZero(std::string_view value) - { - return parseVersion(value).value_or(Void::Semver::Version{}); - } - - [[nodiscard]] std::string nativePlatform() - { -#if defined(__linux__) - return "linux"; -#elif defined(__APPLE__) - return "macos"; -#elif defined(_WIN32) - return "windows"; -#else - return "unknown"; -#endif - } - - [[nodiscard]] std::string nativeArchitecture() - { -#if defined(__x86_64__) || defined(_M_X64) - return "x86_64"; -#elif defined(__aarch64__) || defined(_M_ARM64) - return "aarch64"; -#elif defined(__i386__) || defined(_M_IX86) - return "x86"; -#else - return "unknown"; -#endif - } - - [[nodiscard]] std::int64_t - unixMilliseconds(std::chrono::system_clock::time_point value) - { - return std::chrono::duration_cast( - value.time_since_epoch()) - .count(); - } - - [[nodiscard]] std::string - candidateId(std::string_view source, - const Void::Update::Release& release) - { - const auto material = std::format( - "{}|{}|{}|{}|{}", source, release.component, release.artifactId, - release.version.to_string(), release.sha256); - auto digest = Void::Crypto::sha256(material); - if (!digest) { - return release.sha256; - } - return Void::Encoding::Hex::encode(*digest); - } - - [[nodiscard]] std::optional - decodePublicKey(std::string_view encoded) - { - std::optional decoded; - if (encoded.size() == Void::Crypto::Ed25519PublicKeySize * 2) { - decoded = Void::Encoding::Hex::decode(encoded); - } - if (!decoded) { - decoded = Void::Encoding::Base64::decode(encoded); - } - if (!decoded) { - decoded = Void::Encoding::Base64::decode_url(encoded); - } - if (!decoded || - decoded->size() != Void::Crypto::Ed25519PublicKeySize) { - return std::nullopt; - } - Void::Update::Ed25519PublicKey key{}; - std::memcpy(key.data(), decoded->data(), decoded->size()); - return key; - } - - [[nodiscard]] Api::Result parseJson(std::string_view json) - { - auto parsed = Void::Json::parse(json); - if (!parsed) { - return Api::fail(Api::ErrorCode::ParseError, - std::format("invalid JSON at {}:{}: {}", - parsed.error().line, - parsed.error().col, - parsed.error().message)); - } - return std::move(*parsed); - } - - [[nodiscard]] bool safeIdentifier(std::string_view value) - { - if (value.empty() || value.size() > 64 || value == "." || - value == "..") { - return false; - } - if (!std::isalnum(static_cast(value.front()))) { - return false; - } - return std::ranges::all_of(value, [](unsigned char character) { - return std::isalnum(character) || character == '.' || - character == '_' || character == '-'; - }); - } - - [[nodiscard]] Void::Result::Result - isRealRegularFile(const std::filesystem::path& path) - { - std::error_code error; - const auto status = std::filesystem::symlink_status(path, error); - if (error == std::errc::no_such_file_or_directory || - status.type() == std::filesystem::file_type::not_found) { - return false; - } - if (error) { - return Void::Result::fail( - std::format("cannot inspect rollback payload '{}': {}", - path.string(), error.message())); - } - return std::filesystem::is_regular_file(status) && - !std::filesystem::is_symlink(status); - } - - [[nodiscard]] - Void::Result::Result> - newestHealthyRollback( - const Void::Update::VersionStore& store, - std::span excludedVersions, - const std::filesystem::path& relativePayload) - { - auto healthy = store.healthyPublishedVersions(); - if (!healthy) { - return std::unexpected{healthy.error()}; - } - for (const auto& version : *healthy) { - if (std::ranges::find(excludedVersions, version) != - excludedVersions.end()) { - continue; - } - auto valid = isRealRegularFile(store.versionPath(version) / - relativePayload); - if (!valid) { - return std::unexpected{valid.error()}; - } - if (*valid) { - return std::optional{version}; - } - } - return std::optional{}; - } - - [[nodiscard]] bool safeEnvironmentName(std::string_view value) - { - if (value.empty()) { - return true; - } - if (!(std::isalpha(static_cast(value.front())) || - value.front() == '_')) { - return false; - } - return std::ranges::all_of( - value.substr(1), [](unsigned char character) { - return std::isalnum(character) || character == '_'; - }); - } - - [[nodiscard]] bool sameHex(std::string_view left, - std::string_view right) noexcept - { - return left.size() == right.size() && - std::ranges::equal( - left, right, [](unsigned char lhs, unsigned char rhs) { - return std::tolower(lhs) == std::tolower(rhs); - }); - } - - [[nodiscard]] bool hasUrlUserInfo(std::string_view value) - { - const auto scheme = value.find("://"); - if (scheme == std::string_view::npos) { - return false; - } - const auto authorityStart = scheme + 3; - const auto authorityEnd = - value.find_first_of("/?#", authorityStart); - return value.substr(authorityStart, authorityEnd - authorityStart) - .contains('@'); - } - - [[nodiscard]] bool pathIsWithin(const std::filesystem::path& candidate, - const std::filesystem::path& root) - { - std::error_code error; - const auto canonicalRoot = - std::filesystem::weakly_canonical(root, error); - if (error) { - return false; - } - const auto canonicalCandidate = - std::filesystem::weakly_canonical(candidate, error); - if (error) { - return false; - } - const auto [rootEnd, candidateEnd] = - std::ranges::mismatch(canonicalRoot, canonicalCandidate); - return rootEnd == canonicalRoot.end() && - canonicalRoot != canonicalCandidate && - candidateEnd != canonicalCandidate.begin(); - } - - [[nodiscard]] bool validMaintenanceStart(std::string_view value) - { - if (value.size() != 5 || value[2] != ':' || - !std::isdigit(static_cast(value[0])) || - !std::isdigit(static_cast(value[1])) || - !std::isdigit(static_cast(value[3])) || - !std::isdigit(static_cast(value[4]))) { - return false; - } - const int hour = (value[0] - '0') * 10 + value[1] - '0'; - const int minute = (value[3] - '0') * 10 + value[4] - '0'; - return hour < 24 && minute < 60; - } - - [[nodiscard]] bool - withinMaintenanceWindow(const Api::UpdateMaintenanceWindow& window, - std::chrono::system_clock::time_point now) - { - const auto time = std::chrono::system_clock::to_time_t(now); - std::tm utc{}; - if (::gmtime_r(&time, &utc) == nullptr) { - return false; - } - const int start = - (window.start[0] - '0') * 600 + (window.start[1] - '0') * 60 + - (window.start[3] - '0') * 10 + (window.start[4] - '0'); - const int current = utc.tm_hour * 60 + utc.tm_min; - const auto duration = - std::chrono::duration_cast( - window.duration) - .count(); - const int end = static_cast((start + duration) % (24 * 60)); - return duration >= 24 * 60 || - (start < end ? current >= start && current < end - : current >= start || current < end); - } - - [[nodiscard]] Api::Result - validateConfig(const Api::UpdatesConfig& config, - const std::filesystem::path& incoming) - { - if (config.checkInterval < kMinimumCheckInterval || - config.checkInterval > kMaximumCheckInterval) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "update checkInterval must be between 5m and 30d"); - } - if (config.jitter < std::chrono::milliseconds::zero() || - config.jitter > config.checkInterval) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "update jitter must be non-negative and no " - "longer than checkInterval"); - } - if (!validMaintenanceStart(config.maintenanceWindowUtc.start) || - config.maintenanceWindowUtc.duration < - std::chrono::minutes{1} || - config.maintenanceWindowUtc.duration > std::chrono::hours{24}) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "maintenanceWindowUtc requires HH:MM and a " - "duration from 1m to 24h"); - } - if (config.maxRuntimeDeferral < std::chrono::milliseconds::zero() || - config.maxRuntimeDeferral > kMaximumRuntimeDeferral) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "maxRuntimeDeferral must be between 0 and 7d"); - } - if (config.retainHealthyVersions < 1 || - config.retainHealthyVersions > 10) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "retainHealthyVersions must be between 1 and 10"); - } - - for (const auto& [id, source] : config.sources) { - if (!safeIdentifier(id)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format("invalid update source id '{}'", id)); - } - if (!safeEnvironmentName(source.bearerTokenEnv)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format("source '{}' has an invalid bearer token " - "environment name", - id)); - } - if (source.url.empty() && id != "official") { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format("source '{}' requires a feed URL", id)); - } - if (!source.url.empty()) { - if (hasUrlUserInfo(source.url)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format( - "source '{}' URL must not contain credentials", - id)); - } - if (source.url.starts_with("file://")) { - const auto path = - std::filesystem::path{source.url.substr(7)}; - if (!pathIsWithin(path, incoming)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format( - "source '{}' file URL must be under {}", id, - incoming.string())); - } - } else { - const auto url = Void::Net::Url::parse(source.url); - if (!url || url->scheme != "https" || - url->host.empty()) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format("source '{}' must use an HTTPS URL", - id)); - } - } - } - for (const auto& key : source.publicKeys) { - if (!safeIdentifier(key.id) || key.ed25519.empty()) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format( - "source '{}' contains an invalid public key", - id)); - } - } - } - - const auto validatePolicy = - [&config](std::string_view component, std::string_view source, - std::string_view channel) -> Api::Result { - if (!config.sources.contains(std::string(source))) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format("{} references unknown source '{}'", - component, source)); - } - if (!safeIdentifier(channel)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format("{} has an invalid channel", component)); - } - return {}; - }; - if (auto result = validatePolicy("runtime", config.runtime.source, - config.runtime.channel); - !result) { - return result; - } - if (auto result = validatePolicy("core", config.core.source, - config.core.channel); - !result) { - return result; - } - if (auto result = validatePolicy("plugins", config.plugins.source, - config.plugins.channel); - !result) { - return result; - } - for (const auto& [plugin, policy] : config.plugins.overrides) { - if (!safeIdentifier(plugin)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "plugin update override has an invalid id"); - } - if (auto result = - validatePolicy(std::format("plugin {}", plugin), - policy.source, policy.channel); - !result) { - return result; - } - } - return {}; - } - - void add(Value& object, std::string key, Value value) - { - object.as_object().emplace_back(std::move(key), std::move(value)); - } - - [[nodiscard]] const Value* payload(const Value& request, - std::string_view key) - { - if (!request.is_object()) { - return nullptr; - } - if (const auto* nested = request.find(key)) { - return nested; - } - return &request; - } - - [[nodiscard]] std::string stringField(const Value& object, - std::string_view key) - { - const auto* value = object.is_object() ? object.find(key) : nullptr; - return value && value->is_string() ? value->as_string() - : std::string{}; - } - - [[nodiscard]] bool boolField(const Value& object, std::string_view key, - bool fallback = false) - { - const auto* value = object.is_object() ? object.find(key) : nullptr; - return value && value->is_bool() ? value->as_bool() : fallback; - } - - template - [[nodiscard]] Api::Result - invokeHostHook(std::string_view operation, - Function&& function) noexcept - { - try { - return std::forward(function)(); - } catch (const std::exception& error) { - return Api::fail(Api::ErrorCode::UnknownError, - std::format("{} threw an exception: {}", - operation, error.what())); - } catch (...) { - return Api::fail( - Api::ErrorCode::UnknownError, - std::format("{} threw an unknown exception", operation)); - } - } - } // namespace - - class UpdateService::Impl final - { - public: - - Impl(Options options, Hooks hooks) - : options_(std::move(options)), hooks_(std::move(hooks)), - updateDirectory_(options_.stateDirectory / "updates"), - incomingDirectory_(options_.incomingDirectory.empty() - ? options_.stateDirectory / "incoming" - : options_.incomingDirectory) - { - } - - [[nodiscard]] Api::Result start() - { - std::error_code error; - std::filesystem::create_directories(incomingDirectory_, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot create updater directory '{}': {}", - incomingDirectory_.string(), - error.message())); - } - std::filesystem::create_directories( - updateDirectory_ / "downloads", error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot create updater directory '{}': {}", - (updateDirectory_ / "downloads").string(), - error.message())); - } - std::filesystem::create_directories(updateDirectory_ / "staged", - error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot create updater directory '{}': {}", - (updateDirectory_ / "staged").string(), - error.message())); - } - std::filesystem::create_directories( - updateDirectory_ / "extract", error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot create updater directory '{}': {}", - (updateDirectory_ / "extract").string(), - error.message())); - } - if (auto loaded = loadConfig(); !loaded) { - return loaded; - } - if (auto discovered = discoverRuntimeRollback(); !discovered) { - return discovered; - } - const auto sequencePath = updateDirectory_ / "sequences.json"; - error.clear(); - const auto sequenceStatus = - std::filesystem::symlink_status(sequencePath, error); - if (!error && sequenceStatus.type() != - std::filesystem::file_type::not_found) { - if (std::filesystem::is_symlink(sequenceStatus) || - !std::filesystem::is_regular_file(sequenceStatus)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "update replay-floor state must be a regular file"); - } - auto state = Void::FileSystem::read_file(sequencePath); - if (!state) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format( - "cannot read update replay-floor state: {}", - state.error().message())); - } - auto parsed = parseJson(*state); - if (!parsed) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format("invalid update replay-floor state: {}", - parsed.error().message)); - } - auto values = Void::Json::from_json< - std::map>(*parsed); - if (!values) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format( - "invalid update replay-floor state at '{}': {}", - values.error().field, values.error().message)); - } - std::lock_guard lock(mutex_); - sequences_ = std::move(*values); - } else if (error != std::errc::no_such_file_or_directory && - error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format( - "cannot inspect update replay-floor state: {}", - error.message())); - } - Void::Update::VersionStore coreStore(updateDirectory_ / - "components" / "core"); - if (auto initialized = coreStore.initialize(); !initialized) { - return Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } - auto interrupted = coreStore.pendingActivation(); - if (!interrupted) { - return Api::fail(Api::ErrorCode::UnknownError, - interrupted.error().message()); - } - if (auto reconciled = coreStore.reconcile(); !reconciled) { - return Api::fail(Api::ErrorCode::UnknownError, - reconciled.error().message()); - } - if (auto seeded = seedCoreStore(coreStore); !seeded) { - return seeded; - } - pruneStoreBestEffort(coreStore, "Core"); - if (auto discovered = discoverCoreRollback(coreStore); - !discovered) { - return discovered; - } - if (auto discovered = reconcileAndDiscoverManagedPlugins(); - !discovered) { - return discovered; - } - if (interrupted->has_value() && - (*interrupted)->previousVersion) { - const auto previous = *(*interrupted)->previousVersion; - std::lock_guard lock(mutex_); - pendingCoreAction_ = PendingCoreAction{ - .action = "reconcile", - .version = previous.to_string(), - .candidateId = {}, - .path = - coreStore.versionPath(previous) / coreFilename(), - .previousVersion = (*interrupted)->candidateVersion, - .activationPending = false}; - coreState_ = "pending-host-action"; - coreMessage_ = - "Restoring Core after an interrupted activation"; - } - { - std::lock_guard lock(mutex_); - if (worker_.joinable()) { - return {}; - } - nextCheck_ = - std::chrono::system_clock::now() + nextDelayLocked(); - worker_ = std::jthread( - [this](std::stop_token token) { scheduler(token); }); - } - return {}; - } - - void stop() noexcept - { - std::jthread worker; - { - std::lock_guard lock(mutex_); - if (!worker_.joinable()) { - return; - } - worker_.request_stop(); - condition_.notify_all(); - worker = std::move(worker_); - } - if (worker.joinable()) { - worker.join(); - } - } - - [[nodiscard]] Api::Result - handle(const std::string& method, - const std::string& requestJson) - { - if (method == "updates.getStatus") { - return statusJson(); - } - if (method == "updates.getConfig") { - return configJson(); - } - if (method == "updates.setConfig") { - return setConfig(requestJson); - } - if (method == "updates.check") { - return checkNow(true); - } - if (method == "updates.apply") { - return apply(requestJson); - } - if (method == "updates.rollback") { - return rollback(requestJson); - } - if (method == "updates.confirmUnsigned") { - return confirmUnsigned(requestJson); - } - return Api::fail( - Api::ErrorCode::NotFound, - std::format("unknown host control method '{}'", method)); - } - - void processPendingHostActions(); - - private: - - [[nodiscard]] std::filesystem::path coreFilename() const - { - return options_.currentCore.filename().empty() - ? std::filesystem::path{"Echoion.ts"} - : options_.currentCore.filename(); - } - - [[nodiscard]] std::size_t retainedPreviousVersions() const - { - std::lock_guard lock(mutex_); - return config_.retainHealthyVersions; - } - - void pruneStoreBestEffort(Void::Update::VersionStore& store, - std::string_view component) const - { - auto pruned = store.prune(retainedPreviousVersions()); - if (!pruned) { - Void::Log::warn("UpdateService", - "could not prune {} versions: {}", - component, pruned.error().message()); - } - } - - [[nodiscard]] Api::Result - seedStoreFromFile(Void::Update::VersionStore& store, - std::string_view versionText, - const std::filesystem::path& source, - const std::filesystem::path& filename); - [[nodiscard]] Api::Result - seedCoreStore(Void::Update::VersionStore& store); - [[nodiscard]] Api::Result - discoverCoreRollback(Void::Update::VersionStore& store); - [[nodiscard]] Api::Result discoverRuntimeRollback(); - [[nodiscard]] Api::Result - reconcileAndDiscoverManagedPlugins(); - [[nodiscard]] Api::Result - publishArtifact(Void::Update::VersionStore& store, - const Void::Semver::Version& version, - const std::filesystem::path& artifact, - const std::filesystem::path& filename, - std::string_view expectedSha256); - - [[nodiscard]] std::string - sourceUrl(std::string_view id, - const Api::UpdateSourceConfig& source) const - { - if (!source.url.empty()) { - return source.url; - } - return id == "official" ? options_.officialFeedUrl - : std::string{}; - } - - [[nodiscard]] std::string - replayFloorKey(std::string_view id, - const Api::UpdateSourceConfig& source) const - { - std::string identity; - auto append = [&identity](std::string_view field) { - identity += std::format("{}:{}|", field.size(), field); - }; - append(sourceUrl(id, source)); - append(source.allowUnsigned ? "unsigned" : "signed"); - for (const auto& key : source.publicKeys) { - append(key.id); - append(key.ed25519); - } - if (id == "official") { - append(options_.officialPublicKeysJson); - } - auto digest = Void::Crypto::sha256(identity); - return digest - ? std::format("{}@{}", id, - Void::Encoding::Hex::encode(*digest)) - : std::string{id}; - } - - [[nodiscard]] Api::Result - keyring(std::string_view sourceId, - const Api::UpdateSourceConfig& source) const - { - std::vector keys = source.publicKeys; - if (sourceId == "official" && - !options_.officialPublicKeysJson.empty()) { - auto defaults = parseJson(options_.officialPublicKeysJson); - if (!defaults) { - return std::unexpected(defaults.error()); - } - if (!defaults->is_array()) { - return Api::fail(Api::ErrorCode::ParseError, - "build-time official update keys must " - "be a JSON array"); - } - for (const auto& value : defaults->as_array()) { - const auto id = stringField(value, "id"); - const auto encoded = stringField(value, "ed25519"); - if (!id.empty() || !encoded.empty()) { - keys.push_back({.id = id, .ed25519 = encoded}); - } - } - } - - Void::Update::Keyring result; - for (const auto& key : keys) { - auto decoded = decodePublicKey(key.ed25519); - if (!safeIdentifier(key.id) || !decoded) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format( - "source '{}' has an invalid Ed25519 key '{}'", - sourceId, key.id)); - } - result.insert_or_assign(key.id, *decoded); - } - return result; - } - - [[nodiscard]] Api::Result - fetchBytes(std::string_view url, - const Api::UpdateSourceConfig& source, - std::uint64_t maximumBytes, - std::string_view credentialOrigin = {}) const - { - if (url.starts_with("file://")) { - auto path = std::filesystem::path{url.substr(7)}; - if (!pathIsWithin(path, incomingDirectory_)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "local update input must be under the " - "configured incoming directory"); - } - std::error_code error; - const auto size = std::filesystem::file_size(path, error); - if (error || size > maximumBytes) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "local update input is missing or " - "exceeds its size limit"); - } - auto bytes = Void::FileSystem::read_file(path); - if (!bytes) { - return Api::fail( - Api::ErrorCode::NotFound, - std::format("cannot read local update input: {}", - bytes.error().message())); - } - return std::move(*bytes); - } - const auto parsed = Void::Net::Url::parse(url); - if (!parsed || parsed->scheme != "https" || - parsed->host.empty() || hasUrlUserInfo(url)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "update downloads require a credential-free HTTPS URL"); - } - Void::Net::HttpClient client; - client.set_user_agent("Echoion-Updater/1"); - client.set_verify_tls(true); - client.set_max_redirects(0); - client.set_max_body_size(maximumBytes); - Void::Net::Request request; - request.method = Void::Net::Method::Get; - request.url = std::string(url); - request.timeout = std::chrono::seconds{60}; - const auto origin = Void::Net::Url::parse(credentialOrigin); - const bool sameCredentialOrigin = - origin && origin->scheme == parsed->scheme && - origin->host == parsed->host && - origin->port == parsed->port; - if (sameCredentialOrigin && !source.bearerTokenEnv.empty()) { - if (const char* token = - std::getenv(source.bearerTokenEnv.c_str()); - token && *token != '\0') { - request.headers.push_back( - {"Authorization", std::string{"Bearer "} + token}); - } - } - auto response = client.send(request); - if (!response) { - return Api::fail(Api::ErrorCode::NetworkError, - response.error().message()); - } - if (!response->ok()) { - return Api::fail( - Api::ErrorCode::NetworkError, - std::format("update server returned HTTP {}", - response->status)); - } - if (response->body.size() > maximumBytes) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "update response exceeded its size limit"); - } - return std::move(response->body); - } - - [[nodiscard]] Api::Result - fetchFeed(std::string_view id, - const Api::UpdateSourceConfig& source, - std::optional minimumSequence) const - { - const auto url = sourceUrl(id, source); - if (url.empty()) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - std::format("update source '{}' has no feed URL", id)); - } - auto bytes = fetchBytes(url, source, 5U * 1024U * 1024U, url); - if (!bytes) { - return std::unexpected(bytes.error()); - } - Void::Update::VerificationPolicy policy; - policy.minimumSequence = minimumSequence; - auto keys = keyring(id, source); - if (!keys) { - return std::unexpected(keys.error()); - } - if (!keys->empty()) { - auto verified = - Void::Update::verifyFeedEnvelope(*bytes, *keys, policy); - if (verified) { - return FetchedFeed{.feed = std::move(verified->feed), - .signedFeed = true}; - } - if (!source.allowUnsigned) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format( - "source '{}' signature verification failed: {}", - id, verified.error().message())); - } - } else if (!source.allowUnsigned) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("source '{}' has no trusted signing key", - id)); - } - - // Explicitly configured unsigned sources may present either a - // raw feed payload or an envelope whose payload field is the - // exact JSON text. - std::string payloadBytes = *bytes; - if (auto envelope = parseJson(*bytes); - envelope && envelope->is_object()) { - if (const auto* payloadValue = envelope->find("payload"); - payloadValue && payloadValue->is_string()) { - payloadBytes = payloadValue->as_string(); - } - } - auto parsed = - Void::Update::parseFeedPayload(payloadBytes, policy); - if (!parsed) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format("unsigned source '{}' feed rejected: {}", - id, parsed.error().message())); - } - return FetchedFeed{.feed = std::move(*parsed), - .signedFeed = false}; - } - - [[nodiscard]] Void::Update::Environment environment() const - { - const auto runtime = versionOrZero(options_.runtimeVersion); - const auto core = - versionOrZero(hooks_.coreVersion ? hooks_.coreVersion() - : options_.runtimeVersion); - Void::Update::Environment value; - value.platform = nativePlatform(); - value.architecture = nativeArchitecture(); - value.versionContracts.emplace("echoion.runtime", runtime); - value.versionContracts.emplace("echoion.core", core); - value.versionContracts.emplace( - "echoion.api", versionOrZero(options_.apiVersion)); - value.exactContracts.emplace( - "void.plugin.abi", - std::to_string(Void::Plugin::ABI_VERSION)); - value.exactContracts.emplace("cxx.toolchain.abi", - options_.toolchainAbi); - return value; - } - - [[nodiscard]] std::vector - queryPluginInventory() const - { - if (!hooks_.managePlugins) { - return {}; - } - auto response = - invokeHostHook("plugin inventory hook", [&] { - return hooks_.managePlugins( - R"({"schemaVersion":1,"action":"status"})"); - }); - if (!response) { - Void::Log::warn("UpdateService", "cannot query plugins: {}", - response.error().message); - return {}; - } - auto parsed = parseJson(*response); - if (!parsed) { - return {}; - } - const auto* entries = parsed->find("plugins"); - if (!entries || !entries->is_array()) { - return {}; - } - std::vector result; - for (const auto& entry : entries->as_array()) { - auto id = stringField(entry, "id"); - if (id.empty()) { - continue; - } - result.push_back({.id = std::move(id), - .name = stringField(entry, "name"), - .version = stringField(entry, "version"), - .path = stringField(entry, "path"), - .managed = boolField(entry, "managed")}); - } - return result; - } - - [[nodiscard]] Api::Result loadConfig() - { - auto contents = - Void::FileSystem::read_file(options_.configPath); - if (!contents) { - return Api::fail( - Api::ErrorCode::NotFound, - std::format("cannot read updater configuration: {}", - contents.error().message())); - } - auto root = parseJson(*contents); - if (!root) { - return std::unexpected(root.error()); - } - const auto* value = root->find("updates"); - Api::UpdatesConfig config; - if (value) { - auto parsed = - Void::Json::from_json(*value); - if (!parsed) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format( - "invalid updates configuration at '{}': {}", - parsed.error().field, parsed.error().message)); - } - config = std::move(*parsed); - } - if (!config.sources.contains("official")) { - config.sources.emplace("official", - Api::UpdateSourceConfig{}); - } - if (auto valid = validateConfig(config, incomingDirectory_); - !valid) { - return valid; - } - std::lock_guard lock(mutex_); - config_ = std::move(config); - return {}; - } - - [[nodiscard]] Api::Result configJson() const - { - Api::UpdatesConfig snapshot; - { - std::lock_guard lock(mutex_); - snapshot = config_; - } - auto value = Void::Json::to_json(snapshot); - if (auto* sources = value.find("sources"); - sources && sources->is_object()) { - for (auto& [id, source] : sources->as_object()) { - const auto configured = snapshot.sources.find(id); - if (configured == snapshot.sources.end() || - !source.is_object()) { - continue; - } - const auto& environment = - configured->second.bearerTokenEnv; - const bool present = - !environment.empty() && - std::getenv(environment.c_str()) != nullptr; - add(source, "bearerTokenPresent", Value{present}); - } - } - return Void::Json::serialize(value, {.pretty = true}); - } - - [[nodiscard]] Api::Result - setConfig(std::string_view requestJson) - { - auto request = - parseJson(requestJson.empty() ? "{}" : requestJson); - if (!request) { - return std::unexpected(request.error()); - } - const auto* value = payload(*request, "config"); - if (!value || !value->is_object()) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "setConfig requires a config object"); - } - auto parsed = Void::Json::from_json(*value); - if (!parsed) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format("invalid update config at '{}': {}", - parsed.error().field, - parsed.error().message)); - } - if (!parsed->sources.contains("official")) { - parsed->sources.emplace("official", - Api::UpdateSourceConfig{}); - } - if (auto valid = validateConfig(*parsed, incomingDirectory_); - !valid) { - return std::unexpected(valid.error()); - } - - auto contents = - Void::FileSystem::read_file(options_.configPath); - if (!contents) { - return Api::fail( - Api::ErrorCode::NotFound, - std::format("cannot read configuration: {}", - contents.error().message())); - } - auto root = parseJson(*contents); - if (!root) { - return std::unexpected(root.error()); - } - if (!root->is_object()) { - return Api::fail(Api::ErrorCode::ParseError, - "configuration root must be an object"); - } - bool replaced = false; - for (auto& [key, member] : root->as_object()) { - if (key == "updates") { - member = Void::Json::to_json(*parsed); - replaced = true; - break; - } - } - if (!replaced) { - add(*root, "updates", Void::Json::to_json(*parsed)); - } - const auto serialized = - Void::Json::serialize(*root, {.pretty = true}); - if (auto written = Void::FileSystem::atomic_write( - options_.configPath, serialized); - !written) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot persist update configuration: {}", - written.error().message())); - } - { - std::lock_guard lock(mutex_); - config_ = std::move(*parsed); - nextCheck_ = - std::chrono::system_clock::now() + nextDelayLocked(); - } - condition_.notify_all(); - return configJson(); - } - - [[nodiscard]] std::chrono::milliseconds nextDelayLocked() - { - auto delay = config_.checkInterval; - if (config_.jitter > std::chrono::milliseconds::zero()) { - std::uniform_int_distribution distribution( - 0, config_.jitter.count()); - delay += std::chrono::milliseconds{distribution(random_)}; - } - return delay; - } - - void scheduler(std::stop_token token) - { - std::unique_lock lock(mutex_); - while (!token.stop_requested()) { - if (!config_.enabled) { - condition_.wait(lock, token, - [this] { return config_.enabled; }); - continue; - } - const auto scheduledCheck = nextCheck_; - auto deadline = scheduledCheck; - if (runtimeState_ == "waiting-for-idle" && - runtimeCandidate_) { - deadline = std::min(deadline, - std::chrono::system_clock::now() + - std::chrono::minutes{1}); - } - if (condition_.wait_until( - lock, token, deadline, [this, scheduledCheck] { - return nextCheck_ != scheduledCheck; - })) { - continue; - } - if (token.stop_requested()) { - break; - } - const auto now = std::chrono::system_clock::now(); - if (runtimeState_ == "waiting-for-idle" && - runtimeCandidate_) { - const bool idle = - !hooks_.playbackActive || !hooks_.playbackActive(); - const bool deferred = - now - runtimeCandidate_->discoveredAt >= - config_.maxRuntimeDeferral; - const bool forcedWindow = - deferred && withinMaintenanceWindow( - config_.maintenanceWindowUtc, now); - if (idle || forcedWindow) { - const auto candidate = *runtimeCandidate_; - lock.unlock(); - Value request = Void::Json::object(); - add(request, "component", Value{"runtime"}); - add(request, "candidateId", Value{candidate.id}); - add(request, "version", - Value{candidate.release.version.to_string()}); - if (!candidate.confirmationToken.empty()) { - add(request, "confirmationToken", - Value{candidate.confirmationToken}); - } - if (auto result = - apply(Void::Json::serialize(request)); - !result) { - Void::Log::warn( - "UpdateService", - "deferred runtime apply failed: {}", - result.error().message); - } - lock.lock(); - continue; - } - } - if (now < nextCheck_) { - continue; - } - lock.unlock(); - auto result = checkNow(false); - if (!result) { - Void::Log::warn("UpdateService", - "scheduled check failed: {}", - result.error().message); - } - lock.lock(); - nextCheck_ = - std::chrono::system_clock::now() + nextDelayLocked(); - } - } - - [[nodiscard]] Api::Result statusJson() const; - [[nodiscard]] Api::Result checkNow(bool manual); - [[nodiscard]] Api::Result - downloadArtifact(const CandidateRecord& candidate); - [[nodiscard]] Api::Result - activateCore(const CandidateRecord& candidate); - [[nodiscard]] Api::Result - activatePlugin(std::string_view pluginId, - const CandidateRecord& candidate); - [[nodiscard]] Api::Result - activateRuntime(const CandidateRecord& candidate); - void recordHistory(HistoryEntry entry); - [[nodiscard]] Api::Result - apply(std::string_view requestJson); - [[nodiscard]] Api::Result - rollback(std::string_view requestJson); - [[nodiscard]] Api::Result - confirmUnsigned(std::string_view requestJson); - - Options options_; - Hooks hooks_; - std::filesystem::path updateDirectory_; - std::filesystem::path incomingDirectory_; - mutable std::mutex mutex_; - std::condition_variable_any condition_; - Api::UpdatesConfig config_; - std::jthread worker_; - std::chrono::system_clock::time_point lastCheck_{}; - std::chrono::system_clock::time_point nextCheck_{}; - bool checking_ = false; - std::string message_; - std::optional runtimeCandidate_; - std::optional coreCandidate_; - std::unordered_map pluginCandidates_; - std::vector pluginInventory_; - std::vector history_; - std::map sequences_; - std::string runtimeState_ = "current"; - std::string coreState_ = "current"; - std::string pluginsState_ = "current"; - std::string runtimeMessage_; - std::string coreMessage_; - std::string pluginsMessage_; - std::string runtimeRollbackVersion_; - std::string coreRollbackVersion_; - std::unordered_map - pluginRollbackVersions_; - std::optional pendingCoreAction_; - std::mt19937_64 random_{std::random_device{}()}; - }; - - Api::Result UpdateService::Impl::seedStoreFromFile( - Void::Update::VersionStore& store, std::string_view versionText, - const std::filesystem::path& source, - const std::filesystem::path& filename) - { - auto current = store.currentVersion(); - if (!current) { - return Api::fail(Api::ErrorCode::UnknownError, - current.error().message()); - } - if (current->has_value()) { - return {}; - } - - const auto version = Void::Semver::parse_strict(versionText); - if (!version) { - return Api::fail( - Api::ErrorCode::IncompatibleVersion, - std::format( - "cannot seed update store from non-SemVer version '{}'", - versionText)); - } - std::error_code error; - if (!std::filesystem::is_regular_file(source, error) || error) { - return Api::fail( - Api::ErrorCode::NotFound, - std::format( - "cannot seed update store: '{}' is not a regular file", - source.string())); - } - - const auto publishedFile = store.versionPath(*version) / filename; - const bool versionDirectoryExists = - std::filesystem::exists(store.versionPath(*version), error); - if (error) { - return Api::fail(Api::ErrorCode::PermissionDenied, - std::format("cannot inspect update store seed: {}", - error.message())); - } - if (versionDirectoryExists) { - if (!std::filesystem::is_regular_file(publishedFile, error) || - error) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format("update store version '{}' is missing '{}'", - version->to_string(), filename.string())); - } - } else { - auto staging = store.prepare(*version); - if (!staging) { - return Api::fail(Api::ErrorCode::UnknownError, - staging.error().message()); - } - std::filesystem::copy_file( - source, *staging / filename, - std::filesystem::copy_options::overwrite_existing, error); - if (error) { - std::error_code ignored; - std::filesystem::remove_all(*staging, ignored); - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format( - "cannot copy initial version into update store: {}", - error.message())); - } - if (auto published = store.publish(*version, *staging); - !published) { - std::error_code ignored; - std::filesystem::remove_all(*staging, ignored); - return Api::fail(Api::ErrorCode::UnknownError, - published.error().message()); - } - } - if (auto activated = store.activate(*version); !activated) { - return Api::fail(Api::ErrorCode::UnknownError, - activated.error().message()); - } - if (auto committed = store.commit(); !committed) { - std::ignore = store.rollback(); - return Api::fail(Api::ErrorCode::UnknownError, - committed.error().message()); - } - return {}; - } - - Api::Result - UpdateService::Impl::seedCoreStore(Void::Update::VersionStore& store) - { - const auto version = - hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; - return seedStoreFromFile(store, version, options_.currentCore, - coreFilename()); - } - - Api::Result UpdateService::Impl::discoverCoreRollback( - Void::Update::VersionStore& store) - { - auto current = store.currentVersion(); - if (!current) { - return Api::fail(Api::ErrorCode::UnknownError, - current.error().message()); - } - std::vector excluded; - if (*current) { - excluded.push_back(**current); - } - auto rollback = newestHealthyRollback(store, excluded, coreFilename()); - if (!rollback) { - return Api::fail( - Api::ErrorCode::UnknownError, - std::format("cannot discover Core rollback version: {}", - rollback.error().message())); - } - std::lock_guard lock(mutex_); - coreRollbackVersion_ = - *rollback ? (*rollback)->to_string() : std::string{}; - return {}; - } - - Api::Result UpdateService::Impl::discoverRuntimeRollback() - { - const auto clearRollback = [this] { - std::lock_guard lock(mutex_); - runtimeRollbackVersion_.clear(); - }; - const auto versionsRoot = options_.installRoot / "versions"; - std::error_code error; - const auto status = - std::filesystem::symlink_status(versionsRoot, error); - if (error == std::errc::no_such_file_or_directory || - status.type() == std::filesystem::file_type::not_found) { - clearRollback(); - return {}; - } - if (error || !std::filesystem::is_directory(status) || - std::filesystem::is_symlink(status)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "runtime VersionStore versions root is not a real directory"); - } - for (const auto& metadata : {options_.installRoot / ".update.lock", - options_.installRoot / "health.log"}) { - error.clear(); - const auto metadataStatus = - std::filesystem::symlink_status(metadata, error); - if (error == std::errc::no_such_file_or_directory || - metadataStatus.type() == - std::filesystem::file_type::not_found) { - clearRollback(); - return {}; - } - if (error || !std::filesystem::is_regular_file(metadataStatus) || - std::filesystem::is_symlink(metadataStatus)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("runtime VersionStore metadata '{}' is unsafe", - metadata.string())); - } - std::ifstream readable{metadata, std::ios::binary}; - if (!readable) { - Void::Log::warn( - "UpdateService", - "runtime rollback metadata '{}' is not readable; " - "rollback discovery is disabled until a privileged updater " - "migrates it", - metadata.string()); - clearRollback(); - return {}; - } - } - - Void::Update::VersionStore store(options_.installRoot); - auto current = store.currentVersion(); - if (!current) { - return Api::fail( - Api::ErrorCode::UnknownError, - std::format("cannot inspect the runtime VersionStore: {}", - current.error().message())); - } - std::vector excluded; - if (*current) { - excluded.push_back(**current); - } - if (auto running = parseVersion(options_.runtimeVersion); running) { - excluded.push_back(*running); - } - const auto executable = options_.runningExecutable.filename().empty() - ? std::filesystem::path{"echoiond"} - : options_.runningExecutable.filename(); - auto rollback = newestHealthyRollback( - store, excluded, std::filesystem::path{"bin"} / executable); - if (!rollback) { - return Api::fail( - Api::ErrorCode::UnknownError, - std::format("cannot discover runtime rollback version: {}", - rollback.error().message())); - } - std::lock_guard lock(mutex_); - runtimeRollbackVersion_ = - *rollback ? (*rollback)->to_string() : std::string{}; - return {}; - } - - Api::Result UpdateService::Impl::reconcileAndDiscoverManagedPlugins() - { - std::unordered_map rollbacks; - const auto managed = options_.stateDirectory / "plugins" / ".managed"; - std::error_code error; - const auto status = std::filesystem::symlink_status(managed, error); - if (error == std::errc::no_such_file_or_directory || - status.type() == std::filesystem::file_type::not_found) { - auto inventory = queryPluginInventory(); - std::lock_guard lock(mutex_); - pluginInventory_ = std::move(inventory); - pluginRollbackVersions_.clear(); - return {}; - } - if (error || !std::filesystem::is_directory(status) || - std::filesystem::is_symlink(status)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "managed plugin update root is not a real directory"); - } - - std::filesystem::directory_iterator iterator{managed, error}; - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot enumerate managed plugin stores: {}", - error.message())); - } - for (const std::filesystem::directory_iterator end; iterator != end; - iterator.increment(error)) { - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot enumerate managed plugin stores: {}", - error.message())); - } - const auto id = iterator->path().filename().string(); - const auto entryStatus = iterator->symlink_status(error); - if (error || !safeIdentifier(id) || - !std::filesystem::is_directory(entryStatus) || - std::filesystem::is_symlink(entryStatus)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("managed plugin update store '{}' is unsafe", - id)); - } - - Void::Update::VersionStore store(iterator->path()); - if (auto initialized = store.initialize(); !initialized) { - return Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } - if (auto reconciled = store.reconcile(); !reconciled) { - return Api::fail(Api::ErrorCode::UnknownError, - reconciled.error().message()); - } - pruneStoreBestEffort(store, std::format("plugin '{}'", id)); - auto current = store.currentVersion(); - if (!current) { - return Api::fail(Api::ErrorCode::UnknownError, - current.error().message()); - } - std::vector excluded; - if (*current) { - excluded.push_back(**current); - } - auto rollback = newestHealthyRollback( - store, excluded, std::filesystem::path{id + ".so"}); - if (!rollback) { - return Api::fail( - Api::ErrorCode::UnknownError, - std::format( - "cannot discover rollback version for plugin '{}': {}", - id, rollback.error().message())); - } - if (*rollback) { - rollbacks.emplace(id, (*rollback)->to_string()); - } - } - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot enumerate managed plugin stores: {}", - error.message())); - } - - auto inventory = queryPluginInventory(); - std::lock_guard lock(mutex_); - pluginInventory_ = std::move(inventory); - pluginRollbackVersions_ = std::move(rollbacks); - return {}; - } - - Api::Result UpdateService::Impl::publishArtifact( - Void::Update::VersionStore& store, const Void::Semver::Version& version, - const std::filesystem::path& artifact, - const std::filesystem::path& filename, std::string_view expectedSha256) - { - const auto destination = store.versionPath(version) / filename; - std::error_code error; - const bool published = - std::filesystem::exists(store.versionPath(version), error); - if (error) { - return Api::fail(Api::ErrorCode::PermissionDenied, - std::format("cannot inspect published update: {}", - error.message())); - } - if (published) { - if (!std::filesystem::is_regular_file(destination, error) || - error) { - return Api::fail(Api::ErrorCode::ParseError, - "published update version is incomplete"); - } - auto digest = Void::Crypto::sha256File(destination); - if (!digest || !sameHex(Void::Encoding::Hex::encode(*digest), - expectedSha256)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "published update version does not match the " - "signed artifact"); - } - return destination; - } - - auto staging = store.prepare(version); - if (!staging) { - return Api::fail(Api::ErrorCode::AlreadyExists, - staging.error().message()); - } - std::filesystem::copy_file( - artifact, *staging / filename, - std::filesystem::copy_options::overwrite_existing, error); - if (error) { - std::error_code ignored; - std::filesystem::remove_all(*staging, ignored); - return Api::fail(Api::ErrorCode::PermissionDenied, - std::format("cannot stage update artifact: {}", - error.message())); - } - if (auto result = store.publish(version, *staging); !result) { - std::error_code ignored; - std::filesystem::remove_all(*staging, ignored); - return Api::fail(Api::ErrorCode::UnknownError, - result.error().message()); - } - return destination; - } - - void UpdateService::Impl::processPendingHostActions() - { - PendingCoreAction action; - { - std::lock_guard lock(mutex_); - if (!pendingCoreAction_ || pendingCoreAction_->processing) { - return; - } - pendingCoreAction_->processing = true; - action = *pendingCoreAction_; - coreState_ = "activating"; - coreMessage_ = - action.action == "rollback" - ? "Activating the selected previous Core version" - : "Activating the staged Core outside the RPC callback"; - } - - Api::Result result = - hooks_.replaceCore - ? invokeHostHook( - "Core replacement hook", - [&] { return hooks_.replaceCore(action.path); }) - : Api::fail(Api::ErrorCode::NotSupported, - "this host cannot replace Core"); - Void::Update::VersionStore store(updateDirectory_ / "components" / - "core"); - if (result && action.activationPending) { - if (auto committed = store.commit(); !committed) { - result = Api::fail(Api::ErrorCode::UnknownError, - std::format("Core loaded but its activation " - "could not be committed: {}", - committed.error().message())); - if (auto rolledBack = store.rollback(); !rolledBack) { - result.error().message += - std::format("; store rollback also failed: {}", - rolledBack.error().message()); - } else if (action.previousVersion && hooks_.replaceCore) { - const auto restored = - invokeHostHook("Core restoration hook", [&] { - return hooks_.replaceCore( - store.versionPath(*action.previousVersion) / - coreFilename()); - }); - if (!restored) { - result.error().message += std::format( - "; restoring the previous Core also failed: {}", - restored.error().message); - } - } - } - } else if (!result && action.activationPending) { - if (auto rolledBack = store.rollback(); !rolledBack) { - result.error().message += - std::format("; store rollback also failed: {}", - rolledBack.error().message()); - } - } - pruneStoreBestEffort(store, "Core"); - - const auto now = std::chrono::system_clock::now(); - const auto message = result ? std::string{} : result.error().message; - { - std::lock_guard lock(mutex_); - pendingCoreAction_.reset(); - if (result) { - coreRollbackVersion_ = action.previousVersion - ? action.previousVersion->to_string() - : std::string{}; - coreState_ = "healthy"; - coreMessage_ = - action.action == "rollback" - ? "Previous Core version activated" - : "Core activated without restarting the daemon"; - if (!action.candidateId.empty() && coreCandidate_ && - coreCandidate_->id == action.candidateId) { - coreCandidate_.reset(); - } - } else { - if (coreCandidate_ && - coreCandidate_->id == action.candidateId) { - coreCandidate_->applying = false; - if (!coreCandidate_->signedFeed) { - coreCandidate_->unsignedAuthorized = false; - coreCandidate_->confirmationToken.clear(); - coreCandidate_->confirmationExpiresAt = {}; - } - } - coreState_ = "failed"; - coreMessage_ = message; - } - history_.push_back( - {.timestamp = now, - .component = "core", - .pluginId = {}, - .action = action.action, - .version = action.version, - .result = result ? "success" : "failed", - .message = message, - .actor = action.action == "reconcile" ? "host" : "admin"}); - if (history_.size() > 100) { - history_.erase(history_.begin()); - } - } - } - - Api::Result UpdateService::Impl::statusJson() const - { - const auto coreVersion = - hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; - std::lock_guard lock(mutex_); - auto candidateValue = [](const CandidateRecord& record, - std::string_view current) { - Value value = Void::Json::object(); - add(value, "id", Value{record.id}); - add(value, "version", Value{record.release.version.to_string()}); - add(value, "channel", Value{record.release.channel}); - add(value, "source", Value{record.source}); - add(value, "signed", Value{record.signedFeed}); - add(value, "compatible", Value{true}); - const auto installed = parseVersion(current); - add(value, "downgrade", - Value{installed && record.release.version < *installed}); - add(value, "requiresRestart", - Value{record.release.component == "runtime" || - record.release.component == "executable"}); - if (!record.release.cohort.empty()) { - add(value, "cohort", Value{record.release.cohort}); - } - return value; - }; - - auto componentValue = - [&](std::string_view component, std::string_view current, - std::string_view state, std::string_view message, - std::string_view source, std::string_view channel, - const std::optional& candidate, - std::string_view rollbackVersion) { - Value value = Void::Json::object(); - add(value, "component", Value{std::string(component)}); - add(value, "currentVersion", Value{std::string(current)}); - add(value, "state", Value{std::string(state)}); - add(value, "source", Value{std::string(source)}); - add(value, "channel", Value{std::string(channel)}); - if (!message.empty()) { - add(value, "message", Value{std::string(message)}); - } - if (candidate) { - add(value, "candidate", - candidateValue(*candidate, current)); - } - if (!rollbackVersion.empty()) { - add(value, "rollbackVersion", - Value{std::string(rollbackVersion)}); - } - return value; - }; - - Value root = Void::Json::object(); - add(root, "enabled", Value{config_.enabled}); - add(root, "checking", Value{checking_}); - if (lastCheck_ != std::chrono::system_clock::time_point{}) { - add(root, "lastCheckAt", - Value{static_cast(unixMilliseconds(lastCheck_))}); - } - if (nextCheck_ != std::chrono::system_clock::time_point{}) { - add(root, "nextCheckAt", - Value{static_cast(unixMilliseconds(nextCheck_))}); - } - if (!message_.empty()) { - add(root, "message", Value{message_}); - } - - Value components = Void::Json::object(); - add(components, "runtime", - componentValue("runtime", options_.runtimeVersion, runtimeState_, - runtimeMessage_, config_.runtime.source, - config_.runtime.channel, runtimeCandidate_, - runtimeRollbackVersion_)); - add(components, "core", - componentValue("core", coreVersion, coreState_, coreMessage_, - config_.core.source, config_.core.channel, - coreCandidate_, coreRollbackVersion_)); - std::optional anyPlugin; - if (!pluginCandidates_.empty()) { - anyPlugin = pluginCandidates_.begin()->second; - } - add(components, "plugins", - componentValue("plugins", "", pluginsState_, pluginsMessage_, - config_.plugins.source, config_.plugins.channel, - anyPlugin, "")); - add(root, "components", std::move(components)); - - Value plugins = Void::Json::array(); - for (const auto& plugin : pluginInventory_) { - Value item = Void::Json::object(); - add(item, "id", Value{plugin.id}); - add(item, "name", - Value{plugin.name.empty() ? plugin.id : plugin.name}); - add(item, "managed", Value{plugin.managed}); - add(item, "currentVersion", Value{plugin.version}); - const auto override = config_.plugins.overrides.find(plugin.id); - const auto source = override == config_.plugins.overrides.end() - ? config_.plugins.source - : override->second.source; - const auto channel = override == config_.plugins.overrides.end() - ? config_.plugins.channel - : override->second.channel; - add(item, "source", Value{source}); - add(item, "channel", Value{channel}); - const auto candidate = pluginCandidates_.find(plugin.id); - add(item, "state", - Value{candidate == pluginCandidates_.end() - ? std::string{"current"} - : std::string{"available"}}); - if (candidate != pluginCandidates_.end()) { - add(item, "candidate", - candidateValue(candidate->second, plugin.version)); - } - if (const auto previous = pluginRollbackVersions_.find(plugin.id); - previous != pluginRollbackVersions_.end()) { - add(item, "rollbackVersion", Value{previous->second}); - } - plugins.as_array().push_back(std::move(item)); - } - add(root, "plugins", std::move(plugins)); - - Value history = Void::Json::array(); - for (const auto& entry : history_) { - Value item = Void::Json::object(); - add(item, "timestamp", - Value{ - static_cast(unixMilliseconds(entry.timestamp))}); - if (!entry.component.empty()) { - add(item, "component", Value{entry.component}); - } - if (!entry.pluginId.empty()) { - add(item, "pluginId", Value{entry.pluginId}); - } - if (!entry.action.empty()) { - add(item, "action", Value{entry.action}); - } - if (!entry.version.empty()) { - add(item, "version", Value{entry.version}); - } - if (!entry.result.empty()) { - add(item, "result", Value{entry.result}); - } - if (!entry.message.empty()) { - add(item, "message", Value{entry.message}); - } - if (!entry.actor.empty()) { - add(item, "actor", Value{entry.actor}); - } - history.as_array().push_back(std::move(item)); - } - add(root, "history", std::move(history)); - return Void::Json::serialize(root, {.pretty = true}); - } - - Api::Result UpdateService::Impl::checkNow(bool manual) - { - Api::UpdatesConfig config; - std::map sequences; - { - std::lock_guard lock(mutex_); - if (checking_) { - return Api::fail(Api::ErrorCode::AlreadyExists, - "an update check is already running"); - } - checking_ = true; - message_ = "Checking update feeds"; - config = config_; - sequences = sequences_; - } - - struct CheckGuard { - Impl& service; - bool active = true; - void finish() - { - if (!active) { - return; - } - std::lock_guard lock(service.mutex_); - service.checking_ = false; - service.lastCheck_ = std::chrono::system_clock::now(); - service.nextCheck_ = - service.lastCheck_ + service.nextDelayLocked(); - service.condition_.notify_all(); - active = false; - } - ~CheckGuard() { finish(); } - } guard{*this}; - - const auto inventory = queryPluginInventory(); - std::unordered_map feeds; - std::unordered_map feedErrors; - std::vector sourceIds; - auto addSource = [&](std::string_view source) { - if (std::ranges::find(sourceIds, source) == sourceIds.end()) { - sourceIds.emplace_back(source); - } - }; - if (config.runtime.enabled) { - addSource(config.runtime.source); - } - if (config.core.enabled) { - addSource(config.core.source); - } - if (config.plugins.enabled) { - addSource(config.plugins.source); - for (const auto& [id, policy] : config.plugins.overrides) { - (void)id; - addSource(policy.source); - } - } - - for (const auto& id : sourceIds) { - const auto source = config.sources.find(id); - if (source == config.sources.end()) { - feedErrors.emplace(id, "source is not configured"); - continue; - } - const auto floorKey = replayFloorKey(id, source->second); - std::optional minimum; - auto saved = sequences.find(floorKey); - if (saved == sequences.end()) { - // Migrate the pre-source-identity state format on the first - // successful check. The legacy floor remains fail-closed for - // the source identity configured at startup. - saved = sequences.find(id); - } - if (saved != sequences.end()) { - // Routine polling must accept the same immutable feed again - // while still rejecting a sequence rollback. Void's replay - // floor is exclusive, so use the predecessor to admit equality. - if (saved->second > 0) { - minimum = saved->second - 1; - } - } - auto fetched = fetchFeed(id, source->second, minimum); - if (!fetched) { - feedErrors.emplace(id, fetched.error().message); - continue; - } - const auto existing = sequences.find(floorKey); - const auto previous = existing == sequences.end() - ? std::uint64_t{} - : existing->second; - sequences[floorKey] = std::max(previous, fetched->feed.sequence); - if (floorKey != id) { - sequences.erase(id); - } - feeds.emplace(id, std::move(*fetched)); - } - - const auto installedEnvironment = environment(); - auto select = - [&](std::string_view sourceId, std::string_view component, - std::string_view alternateComponent, - std::string_view artifactId, std::string_view channel, - std::string_view current) -> std::optional { - const auto feed = feeds.find(std::string(sourceId)); - if (feed == feeds.end()) { - return std::nullopt; - } - Void::Update::SelectionRequest request; - request.component = std::string(component); - request.artifactId = std::string(artifactId); - request.channel = std::string(channel); - request.environment = installedEnvironment; - request.currentVersion = parseVersion(current); - request.allowDowngrade = true; - auto release = - Void::Update::selectRelease(feed->second.feed, request); - if (!release && !alternateComponent.empty()) { - request.component = std::string(alternateComponent); - release = - Void::Update::selectRelease(feed->second.feed, request); - } - if (!release) { - return std::nullopt; - } - const auto id = candidateId(sourceId, *release); - return CandidateRecord{.release = std::move(*release), - .id = id, - .source = std::string(sourceId), - .signedFeed = feed->second.signedFeed, - .discoveredAt = - std::chrono::system_clock::now(), - .confirmationToken = {}, - .confirmationExpiresAt = {}, - .unsignedAuthorized = false, - .applying = false}; - }; - - const auto coreVersion = - hooks_.coreVersion ? hooks_.coreVersion() : options_.runtimeVersion; - auto runtimeCandidate = - config.runtime.enabled - ? select(config.runtime.source, "runtime", "executable", "", - config.runtime.channel, options_.runtimeVersion) - : std::nullopt; - auto coreCandidate = config.core.enabled - ? select(config.core.source, "core", "", "", - config.core.channel, coreVersion) - : std::nullopt; - std::unordered_map pluginCandidates; - if (config.plugins.enabled) { - for (const auto& plugin : inventory) { - if (config.plugins.managedOnly && !plugin.managed) { - continue; - } - const auto override = config.plugins.overrides.find(plugin.id); - const auto& source = override == config.plugins.overrides.end() - ? config.plugins.source - : override->second.source; - const auto& channel = override == config.plugins.overrides.end() - ? config.plugins.channel - : override->second.channel; - if (auto candidate = - select(source, "plugin", "plugins", plugin.id, channel, - plugin.version)) { - pluginCandidates.emplace(plugin.id, std::move(*candidate)); - } - } - } - if (auto saved = Void::FileSystem::atomic_write( - updateDirectory_ / "sequences.json", - Void::Json::serialize(Void::Json::to_json(sequences), - {.pretty = true})); - !saved) { - const auto message = std::format( - "Update feeds were verified, but the replay floor could not be " - "persisted: {}", - saved.error().message()); - { - std::lock_guard lock(mutex_); - message_ = message; - history_.push_back( - {.timestamp = std::chrono::system_clock::now(), - .component = {}, - .pluginId = {}, - .action = "check", - .version = {}, - .result = "failed", - .message = message, - .actor = manual ? "admin" : "scheduler"}); - if (history_.size() > 100) { - history_.erase(history_.begin()); - } - } - return Api::fail(Api::ErrorCode::PermissionDenied, message); - } - - { - std::lock_guard lock(mutex_); - runtimeCandidate_ = std::move(runtimeCandidate); - coreCandidate_ = std::move(coreCandidate); - pluginCandidates_ = std::move(pluginCandidates); - pluginInventory_ = inventory; - sequences_ = std::move(sequences); - runtimeState_ = runtimeCandidate_ ? "available" : "current"; - coreState_ = coreCandidate_ ? "available" : "current"; - pluginsState_ = pluginCandidates_.empty() ? "current" : "available"; - auto sourceMessage = [&](std::string_view id) { - const auto error = feedErrors.find(std::string(id)); - return error == feedErrors.end() ? std::string{} - : error->second; - }; - runtimeMessage_ = sourceMessage(config.runtime.source); - coreMessage_ = sourceMessage(config.core.source); - pluginsMessage_ = sourceMessage(config.plugins.source); - if (feedErrors.empty()) { - message_ = "Update check completed"; - } else { - message_ = std::format( - "Update check completed with {} source error(s)", - feedErrors.size()); - } - history_.push_back( - {.timestamp = std::chrono::system_clock::now(), - .component = {}, - .pluginId = {}, - .action = "check", - .version = {}, - .result = feedErrors.empty() ? "success" : "partial", - .message = message_, - .actor = manual ? "admin" : "scheduler"}); - if (history_.size() > 100) { - history_.erase(history_.begin()); - } - } - // Auto-activation is intentionally attempted only for signed upgrades. - // Unsigned candidates always require the per-candidate confirmation - // RPC. - if (!manual) { - std::vector> - automatic; - { - std::lock_guard lock(mutex_); - auto collect = - [&](std::string component, std::string plugin, - const std::optional& candidate, - bool enabled) { - if (!enabled || !candidate || !candidate->signedFeed) { - return; - } - const auto current = - component == "runtime" ? options_.runtimeVersion - : component == "core" - ? coreVersion - : [&] { - const auto found = std::ranges::find( - pluginInventory_, plugin, - &PluginInventoryEntry::id); - return found == pluginInventory_.end() - ? std::string{} - : found->version; - }(); - const auto installed = parseVersion(current); - if (installed && - candidate->release.version <= *installed) { - return; - } - automatic.emplace_back(std::move(component), - std::move(plugin), - candidate->id); - }; - collect("runtime", "", runtimeCandidate_, - config.runtime.autoApply); - collect("core", "", coreCandidate_, config.core.autoApply); - for (const auto& [id, candidate] : pluginCandidates_) { - const auto override = config.plugins.overrides.find(id); - const bool autoApply = - override == config.plugins.overrides.end() - ? config.plugins.autoApply - : override->second.autoApply; - collect("plugins", id, std::optional{candidate}, autoApply); - } - } - for (const auto& [component, plugin, id] : automatic) { - Value request = Void::Json::object(); - add(request, "component", Value{component}); - if (!plugin.empty()) { - add(request, "pluginId", Value{plugin}); - } - add(request, "candidateId", Value{id}); - if (auto result = apply(Void::Json::serialize(request)); - !result) { - Void::Log::warn("UpdateService", "auto-apply {} failed: {}", - component, result.error().message); - } - } - } - - guard.finish(); - return statusJson(); - } - - void UpdateService::Impl::recordHistory(HistoryEntry entry) - { - std::lock_guard lock(mutex_); - history_.push_back(std::move(entry)); - if (history_.size() > 100) { - history_.erase(history_.begin()); - } - } - - Api::Result - UpdateService::Impl::downloadArtifact(const CandidateRecord& candidate) - { - if (candidate.release.size == 0 || - candidate.release.size > kMaximumArtifactBytes) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "candidate has an invalid artifact size"); - } - const auto source = [&]() -> std::optional { - std::lock_guard lock(mutex_); - const auto found = config_.sources.find(candidate.source); - return found == config_.sources.end() - ? std::nullopt - : std::optional{found->second}; - }(); - if (!source) { - return Api::fail(Api::ErrorCode::NotFound, - "candidate source is no longer configured"); - } - auto bytes = fetchBytes(candidate.release.url, *source, - candidate.release.size + 1, - sourceUrl(candidate.source, *source)); - if (!bytes) { - return std::unexpected(bytes.error()); - } - if (bytes->size() != candidate.release.size) { - return Api::fail( - Api::ErrorCode::ParseError, - std::format("artifact size mismatch: expected {}, received {}", - candidate.release.size, bytes->size())); - } - auto digest = Void::Crypto::sha256(*bytes); - if (!digest) { - return Api::fail(Api::ErrorCode::UnknownError, - digest.error().message()); - } - if (!sameHex(Void::Encoding::Hex::encode(*digest), - candidate.release.sha256)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "artifact SHA-256 does not match the signed feed"); - } - const auto destination = - updateDirectory_ / "downloads" / (candidate.id + ".artifact"); - if (auto written = Void::FileSystem::atomic_write(destination, *bytes); - !written) { - return Api::fail(Api::ErrorCode::PermissionDenied, - std::format("cannot store downloaded artifact: {}", - written.error().message())); - } - return destination; - } - - Api::Result - UpdateService::Impl::activateCore(const CandidateRecord& candidate) - { - if (!hooks_.replaceCore) { - return Api::fail(Api::ErrorCode::NotSupported, - "this host cannot replace Core"); - } - if (candidate.release.packageType != "shared-library" && - candidate.release.packageType != "file") { - return Api::fail(Api::ErrorCode::InvalidArgument, - "Core updates require packageType shared-library"); - } - { - std::lock_guard lock(mutex_); - if (pendingCoreAction_) { - return Api::fail(Api::ErrorCode::AlreadyExists, - "another Core host action is pending"); - } - } - auto artifact = downloadArtifact(candidate); - if (!artifact) { - return std::unexpected(artifact.error()); - } - Void::Update::VersionStore store(updateDirectory_ / "components" / - "core"); - if (auto initialized = store.initialize(); !initialized) { - return Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } - if (auto seeded = seedCoreStore(store); !seeded) { - return seeded; - } - auto previous = store.currentVersion(); - if (!previous) { - return Api::fail(Api::ErrorCode::UnknownError, - previous.error().message()); - } - const auto filename = coreFilename(); - auto corePath = - publishArtifact(store, candidate.release.version, *artifact, - filename, candidate.release.sha256); - if (!corePath) { - return std::unexpected(corePath.error()); - } - if (auto activated = store.activate(candidate.release.version); - !activated) { - return Api::fail(Api::ErrorCode::UnknownError, - activated.error().message()); - } - { - std::lock_guard lock(mutex_); - pendingCoreAction_ = PendingCoreAction{ - .action = "apply", - .version = candidate.release.version.to_string(), - .candidateId = candidate.id, - .path = *corePath, - .previousVersion = *previous}; - coreState_ = "pending-host-action"; - coreMessage_ = - "Core is staged and will activate after this RPC returns"; - } - return {}; - } - - Api::Result - UpdateService::Impl::activatePlugin(std::string_view pluginId, - const CandidateRecord& candidate) - { - if (!hooks_.managePlugins) { - return Api::fail(Api::ErrorCode::NotSupported, - "this Core cannot manage extension plugins"); - } - if (!safeIdentifier(pluginId) || - candidate.release.artifactId != pluginId) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "candidate does not belong to the requested plugin"); - } - if (candidate.release.packageType != "shared-library" && - candidate.release.packageType != "file") { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "plugin updates require packageType shared-library"); - } - auto artifact = downloadArtifact(candidate); - if (!artifact) { - return std::unexpected(artifact.error()); - } - Void::Update::VersionStore store(options_.stateDirectory / "plugins" / - ".managed" / std::string(pluginId)); - if (auto initialized = store.initialize(); !initialized) { - return Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } - const auto filename = std::string(pluginId) + ".so"; - PluginInventoryEntry installed; - { - std::lock_guard lock(mutex_); - const auto found = std::ranges::find(pluginInventory_, pluginId, - &PluginInventoryEntry::id); - if (found != pluginInventory_.end()) { - installed = *found; - } - } - if (auto seeded = seedStoreFromFile(store, installed.version, - installed.path, filename); - !seeded) { - return Api::fail( - seeded.error().code, - std::format("cannot preserve plugin '{}' for rollback: {}", - pluginId, seeded.error().message)); - } - auto previous = store.currentVersion(); - if (!previous) { - return Api::fail(Api::ErrorCode::UnknownError, - previous.error().message()); - } - auto pluginPath = - publishArtifact(store, candidate.release.version, *artifact, - filename, candidate.release.sha256); - if (!pluginPath) { - return std::unexpected(pluginPath.error()); - } - if (auto activated = store.activate(candidate.release.version); - !activated) { - return Api::fail(Api::ErrorCode::UnknownError, - activated.error().message()); - } - Value request = Void::Json::object(); - add(request, "schemaVersion", Value{1}); - add(request, "action", Value{"replace"}); - add(request, "pluginId", Value{std::string(pluginId)}); - add(request, "version", Value{candidate.release.version.to_string()}); - add(request, "path", Value{pluginPath->string()}); - auto replaced = - invokeHostHook("plugin replacement hook", [&] { - return hooks_.managePlugins(Void::Json::serialize(request)); - }); - if (!replaced) { - auto failure = replaced.error(); - if (auto rolledBack = store.rollback(); !rolledBack) { - failure.message += - std::format("; store rollback also failed: {}", - rolledBack.error().message()); - } - pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); - return std::unexpected(std::move(failure)); - } - if (auto committed = store.commit(); !committed) { - std::string message = std::format( - "plugin loaded but its activation could not be committed: {}", - committed.error().message()); - if (auto rolledBack = store.rollback(); !rolledBack) { - message += std::format("; store rollback also failed: {}", - rolledBack.error().message()); - } else if (previous->has_value()) { - Value restore = Void::Json::object(); - add(restore, "schemaVersion", Value{1}); - add(restore, "action", Value{"replace"}); - add(restore, "pluginId", Value{std::string(pluginId)}); - add(restore, "version", Value{previous->value().to_string()}); - add(restore, "path", - Value{(store.versionPath(previous->value()) / filename) - .string()}); - auto restored = - invokeHostHook("plugin restoration hook", [&] { - return hooks_.managePlugins( - Void::Json::serialize(restore)); - }); - if (!restored) { - message += std::format( - "; restoring the previous plugin also failed: {}", - restored.error().message); - } - } - pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); - return Api::fail(Api::ErrorCode::UnknownError, message); - } - pruneStoreBestEffort(store, std::format("plugin '{}'", pluginId)); - { - std::lock_guard lock(mutex_); - if (previous->has_value()) { - pluginRollbackVersions_[std::string(pluginId)] = - previous->value().to_string(); - } - pluginCandidates_.erase(std::string(pluginId)); - for (auto& plugin : pluginInventory_) { - if (plugin.id == pluginId) { - plugin.version = candidate.release.version.to_string(); - plugin.managed = true; - } - } - pluginsState_ = pluginCandidates_.empty() ? "healthy" : "available"; - pluginsMessage_ = "Managed plugin activated transactionally"; - } - return {}; - } - - Api::Result - UpdateService::Impl::activateRuntime(const CandidateRecord& candidate) - { - if (!hooks_.manageRuntime) { - return Api::fail( - Api::ErrorCode::NotSupported, - "this installation has no runtime activation helper"); - } - if (candidate.release.packageType != "tar.zst") { - return Api::fail(Api::ErrorCode::InvalidArgument, - "runtime updates require packageType tar.zst"); - } - if (candidate.release.releaseManifestSha256.empty()) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "runtime candidate has no release-manifest digest"); - } - auto artifact = downloadArtifact(candidate); - if (!artifact) { - return std::unexpected(artifact.error()); - } - - const auto extractionRoot = updateDirectory_ / "extract" / candidate.id; - const auto stagedRoot = updateDirectory_ / "staged"; - const auto staged = stagedRoot / candidate.id; - std::error_code error; - std::filesystem::remove_all(extractionRoot, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot clear runtime extraction '{}': {}", - extractionRoot.string(), error.message())); - } - std::filesystem::remove_all(staged, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot clear runtime staging '{}': {}", - staged.string(), error.message())); - } - std::filesystem::create_directories(extractionRoot, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot create runtime extraction '{}': {}", - extractionRoot.string(), error.message())); - } - std::filesystem::create_directories(stagedRoot, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot create runtime staging root '{}': {}", - stagedRoot.string(), error.message())); - } - Void::Archive::ExtractionOptions limits; - limits.maxEntries = 50'000; - limits.maxFileBytes = 1024ULL * 1024 * 1024; - limits.maxTotalBytes = kMaximumArtifactBytes; - auto extracted = - Void::Archive::extract(*artifact, extractionRoot, limits); - if (!extracted) { - return Api::fail(Api::ErrorCode::ParseError, - std::format("runtime archive rejected: {}", - extracted.error().message())); - } - std::vector roots; - for (const auto& entry : - std::filesystem::directory_iterator(extractionRoot, error)) { - if (!error) { - roots.push_back(entry.path()); - } - } - if (error || roots.size() != 1 || - !std::filesystem::is_directory(roots.front())) { - return Api::fail( - Api::ErrorCode::ParseError, - "runtime archive must contain exactly one top-level directory"); - } - std::filesystem::rename(roots.front(), staged, error); - if (error) { - return Api::fail(Api::ErrorCode::PermissionDenied, - std::format("cannot publish runtime staging: {}", - error.message())); - } - std::filesystem::remove_all(extractionRoot, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot remove runtime extraction '{}': {}", - extractionRoot.string(), error.message())); - } - - const auto manifest = staged / "manifest.json"; - auto digest = Void::Crypto::sha256File(manifest); - if (!digest || !sameHex(Void::Encoding::Hex::encode(*digest), - candidate.release.releaseManifestSha256)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "runtime manifest SHA-256 does not match the signed feed"); - } - Value operation = Void::Json::object(); - add(operation, "action", Value{"activate"}); - add(operation, "stagingId", Value{candidate.id}); - add(operation, "version", Value{candidate.release.version.to_string()}); - add(operation, "manifestSha256", - Value{candidate.release.releaseManifestSha256}); - std::uint32_t retainHealthyVersions{}; - { - std::lock_guard lock(mutex_); - retainHealthyVersions = config_.retainHealthyVersions; - } - add(operation, "retainHealthyVersions", - Value{static_cast(retainHealthyVersions)}); - auto managed = - invokeHostHook("runtime activation hook", [&] { - return hooks_.manageRuntime(Void::Json::serialize(operation)); - }); - if (!managed) { - return std::unexpected(managed.error()); - } - { - std::lock_guard lock(mutex_); - runtimeRollbackVersion_ = options_.runtimeVersion; - runtimeState_ = "pending-restart"; - runtimeMessage_ = - "Runtime activation is queued for the local helper"; - runtimeCandidate_.reset(); - } - return {}; - } - - Api::Result - UpdateService::Impl::apply(std::string_view requestJson) - { - auto request = parseJson(requestJson.empty() ? "{}" : requestJson); - if (!request) { - return std::unexpected(request.error()); - } - const auto component = stringField(*request, "component"); - const auto pluginId = stringField(*request, "pluginId"); - const auto id = stringField(*request, "candidateId"); - const auto requestedVersion = stringField(*request, "version"); - const auto confirmation = stringField(*request, "confirmationToken"); - CandidateRecord candidate; - { - std::lock_guard lock(mutex_); - CandidateRecord* selected = nullptr; - if (component == "runtime" && runtimeCandidate_) { - selected = &*runtimeCandidate_; - } else if (component == "core" && coreCandidate_) { - selected = &*coreCandidate_; - } else if ((component == "plugins" || component == "plugin") && - !pluginId.empty()) { - const auto found = pluginCandidates_.find(pluginId); - if (found != pluginCandidates_.end()) { - selected = &found->second; - } - } - if (!selected) { - return Api::fail( - Api::ErrorCode::NotFound, - "no candidate is available for the requested component"); - } - if (selected->applying) { - return Api::fail( - Api::ErrorCode::AlreadyExists, - "this update candidate is already being applied"); - } - if (id.empty() || selected->id != id || - (!requestedVersion.empty() && - selected->release.version.to_string() != requestedVersion)) { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "candidate id/version no longer matches the checked feed"); - } - if (!selected->signedFeed) { - if (!selected->unsignedAuthorized && - (selected->confirmationToken.empty() || - selected->confirmationToken != confirmation || - std::chrono::system_clock::now() >= - selected->confirmationExpiresAt)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "this unsigned candidate requires a " - "fresh, unexpired confirmation token"); - } - selected->unsignedAuthorized = true; - selected->confirmationToken.clear(); - selected->confirmationExpiresAt = {}; - } - selected->applying = true; - candidate = *selected; - if (component == "runtime") { - runtimeState_ = "staging"; - } else if (component == "core") { - coreState_ = "staging"; - } else { - pluginsState_ = "staging"; - } - } - - Api::Result activated; - if (component == "runtime") { - if (hooks_.playbackActive && hooks_.playbackActive()) { - { - std::lock_guard lock(mutex_); - if (runtimeCandidate_ && - runtimeCandidate_->id == candidate.id) { - runtimeCandidate_->applying = false; - } - runtimeState_ = "waiting-for-idle"; - runtimeMessage_ = - "Runtime update is queued until playback is idle"; - } - return statusJson(); - } - activated = activateRuntime(candidate); - } else if (component == "core") { - activated = activateCore(candidate); - } else if (component == "plugins" || component == "plugin") { - activated = activatePlugin(pluginId, candidate); - } else { - return Api::fail(Api::ErrorCode::InvalidArgument, - "component must be runtime, core, or plugins"); - } - - if (!activated) { - { - std::lock_guard lock(mutex_); - CandidateRecord* selected = nullptr; - if (component == "runtime" && runtimeCandidate_) { - selected = &*runtimeCandidate_; - } else if (component == "core" && coreCandidate_) { - selected = &*coreCandidate_; - } else if (component == "plugins" || component == "plugin") { - const auto found = pluginCandidates_.find(pluginId); - if (found != pluginCandidates_.end()) { - selected = &found->second; - } - } - if (selected && selected->id == candidate.id) { - selected->applying = false; - if (!selected->signedFeed) { - selected->unsignedAuthorized = false; - selected->confirmationToken.clear(); - selected->confirmationExpiresAt = {}; - } - } - if (component == "runtime") { - runtimeState_ = "failed"; - runtimeMessage_ = activated.error().message; - } else if (component == "core") { - coreState_ = "failed"; - coreMessage_ = activated.error().message; - } else { - pluginsState_ = "failed"; - pluginsMessage_ = activated.error().message; - } - } - recordHistory({.timestamp = std::chrono::system_clock::now(), - .component = component, - .pluginId = pluginId, - .action = "apply", - .version = candidate.release.version.to_string(), - .result = "failed", - .message = activated.error().message, - .actor = "admin"}); - return std::unexpected(activated.error()); - } - if (component == "core") { - // Final success/failure is recorded by processPendingHostActions(), - // after the Core-originated RPC has fully unwound. - return statusJson(); - } - recordHistory({.timestamp = std::chrono::system_clock::now(), - .component = component, - .pluginId = pluginId, - .action = "apply", - .version = candidate.release.version.to_string(), - .result = "success", - .message = {}, - .actor = "admin"}); - return statusJson(); - } - - Api::Result - UpdateService::Impl::confirmUnsigned(std::string_view requestJson) - { - auto request = parseJson(requestJson.empty() ? "{}" : requestJson); - if (!request) { - return std::unexpected(request.error()); - } - const auto component = stringField(*request, "component"); - const auto pluginId = stringField(*request, "pluginId"); - const auto id = stringField(*request, "candidateId"); - const auto version = stringField(*request, "version"); - const auto phrase = stringField(*request, "confirmation"); - std::string token; - { - std::lock_guard lock(mutex_); - CandidateRecord* candidate = nullptr; - if (component == "runtime" && runtimeCandidate_) { - candidate = &*runtimeCandidate_; - } else if (component == "core" && coreCandidate_) { - candidate = &*coreCandidate_; - } else if ((component == "plugins" || component == "plugin") && - !pluginId.empty()) { - const auto found = pluginCandidates_.find(pluginId); - if (found != pluginCandidates_.end()) { - candidate = &found->second; - } - } - if (!candidate || candidate->signedFeed || candidate->id != id || - candidate->release.version.to_string() != version) { - return Api::fail( - Api::ErrorCode::NotFound, - "unsigned candidate is missing or has changed"); - } - const auto source = config_.sources.find(candidate->source); - if (source == config_.sources.end() || - !source->second.allowUnsigned) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "unsigned staging is no longer enabled for this source"); - } - if (phrase != std::format("UNSIGNED {}", version)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "unsigned confirmation phrase does not match this version"); - } - const auto material = - std::format("{}|{}|{}|{}", id, - unixMilliseconds(std::chrono::system_clock::now()), - random_(), random_()); - auto digest = Void::Crypto::sha256(material); - if (!digest) { - return Api::fail(Api::ErrorCode::UnknownError, - digest.error().message()); - } - token = Void::Encoding::Hex::encode(*digest); - candidate->confirmationToken = token; - candidate->confirmationExpiresAt = - std::chrono::system_clock::now() + - kUnsignedConfirmationLifetime; - candidate->unsignedAuthorized = false; - } - Value response = Void::Json::object(); - add(response, "confirmationToken", Value{token}); - return Void::Json::serialize(response); - } - - Api::Result - UpdateService::Impl::rollback(std::string_view requestJson) - { - auto request = parseJson(requestJson.empty() ? "{}" : requestJson); - if (!request) { - return std::unexpected(request.error()); - } - const auto component = stringField(*request, "component"); - const auto pluginId = stringField(*request, "pluginId"); - const auto versionText = stringField(*request, "version"); - const auto version = parseVersion(versionText); - if (!version) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "rollback requires a semantic version"); - } - if (component != "runtime" && component != "core" && - component != "plugins" && component != "plugin") { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "rollback component must be runtime, core, or a plugin id"); - } - if ((component == "plugins" || component == "plugin") && - !safeIdentifier(pluginId)) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "rollback requires a safe managed plugin id"); - } - - std::string advertisedRollback; - { - std::lock_guard lock(mutex_); - if (component == "runtime") { - advertisedRollback = runtimeRollbackVersion_; - } else if (component == "core") { - advertisedRollback = coreRollbackVersion_; - } else if (component == "plugins" || component == "plugin") { - if (const auto found = pluginRollbackVersions_.find(pluginId); - found != pluginRollbackVersions_.end()) { - advertisedRollback = found->second; - } - } - } - if (advertisedRollback.empty() || advertisedRollback != versionText) { - return Api::fail( - Api::ErrorCode::NotFound, - "requested version is not the advertised healthy rollback"); - } - - Api::Result result; - std::string rollbackPreviousVersion; - if (component == "runtime") { - if (!hooks_.manageRuntime) { - return Api::fail(Api::ErrorCode::NotSupported, - "runtime rollback is unavailable"); - } - Value operation = Void::Json::object(); - add(operation, "action", Value{"rollback"}); - add(operation, "version", Value{versionText}); - std::uint32_t retainHealthyVersions{}; - { - std::lock_guard lock(mutex_); - retainHealthyVersions = config_.retainHealthyVersions; - } - add(operation, "retainHealthyVersions", - Value{static_cast(retainHealthyVersions)}); - auto managed = - invokeHostHook("runtime rollback hook", [&] { - return hooks_.manageRuntime( - Void::Json::serialize(operation)); - }); - if (!managed) { - result = std::unexpected(managed.error()); - } else { - result = {}; - } - } else if (component == "core") { - Void::Update::VersionStore store(updateDirectory_ / "components" / - "core"); - bool pending = false; - { - std::lock_guard lock(mutex_); - pending = pendingCoreAction_.has_value(); - } - if (pending) { - result = Api::fail(Api::ErrorCode::AlreadyExists, - "another Core host action is pending"); - } else if (!hooks_.replaceCore) { - result = Api::fail(Api::ErrorCode::NotSupported, - "Core rollback is unavailable"); - } else if (auto initialized = store.initialize(); !initialized) { - result = Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } else if (auto seeded = seedCoreStore(store); !seeded) { - result = seeded; - } else if (auto activated = store.activate(*version); !activated) { - result = Api::fail(Api::ErrorCode::NotFound, - activated.error().message()); - } else { - auto activation = store.pendingActivation(); - if (!activation || !activation->has_value()) { - std::ignore = store.rollback(); - result = Api::fail( - Api::ErrorCode::UnknownError, - activation ? "Core activation journal is missing" - : activation.error().message()); - } else { - std::lock_guard lock(mutex_); - pendingCoreAction_ = PendingCoreAction{ - .action = "rollback", - .version = versionText, - .candidateId = {}, - .path = store.versionPath(*version) / coreFilename(), - .previousVersion = (*activation)->previousVersion}; - coreState_ = "pending-host-action"; - coreMessage_ = - "Core rollback will activate after this RPC returns"; - result = {}; - } - } - } else if ((component == "plugins" || component == "plugin") && - !pluginId.empty()) { - Void::Update::VersionStore store(options_.stateDirectory / - "plugins" / ".managed" / pluginId); - const auto pluginComponent = std::format("plugin '{}'", pluginId); - if (auto initialized = store.initialize(); !initialized) { - result = Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } else if (auto activated = store.activate(*version); !activated) { - result = Api::fail(Api::ErrorCode::NotFound, - activated.error().message()); - } else { - result = [&]() -> Api::Result { - auto activation = store.pendingActivation(); - if (!activation || !activation->has_value()) { - std::ignore = store.rollback(); - pruneStoreBestEffort(store, pluginComponent); - return Api::fail( - Api::ErrorCode::UnknownError, - activation ? "plugin activation journal is missing" - : activation.error().message()); - } - if ((*activation)->previousVersion) { - rollbackPreviousVersion = - (*activation)->previousVersion->to_string(); - } - Value operation = Void::Json::object(); - add(operation, "schemaVersion", Value{1}); - add(operation, "action", Value{"replace"}); - add(operation, "pluginId", Value{pluginId}); - add(operation, "version", Value{versionText}); - add(operation, "path", - Value{(store.versionPath(*version) / (pluginId + ".so")) - .string()}); - auto managed = - hooks_.managePlugins - ? invokeHostHook( - "plugin rollback hook", - [&] { - return hooks_.managePlugins( - Void::Json::serialize(operation)); - }) - : Api::fail(Api::ErrorCode::NotSupported, - "plugin rollback is unavailable"); - if (!managed) { - auto failure = managed.error(); - if (auto rolledBack = store.rollback(); !rolledBack) { - failure.message += - std::format("; store rollback also failed: {}", - rolledBack.error().message()); - } - pruneStoreBestEffort(store, pluginComponent); - return std::unexpected(std::move(failure)); - } - auto committed = store.commit(); - if (committed) { - pruneStoreBestEffort(store, pluginComponent); - return {}; - } - - std::string message = std::format( - "plugin loaded but rollback could not be committed: {}", - committed.error().message()); - if (auto rolledBack = store.rollback(); !rolledBack) { - message += - std::format("; store rollback also failed: {}", - rolledBack.error().message()); - } else if ((*activation)->previousVersion && - hooks_.managePlugins) { - Value restore = Void::Json::object(); - add(restore, "schemaVersion", Value{1}); - add(restore, "action", Value{"replace"}); - add(restore, "pluginId", Value{pluginId}); - add(restore, "version", - Value{(*activation)->previousVersion->to_string()}); - add(restore, "path", - Value{(store.versionPath( - *(*activation)->previousVersion) / - (pluginId + ".so")) - .string()}); - auto restored = invokeHostHook( - "plugin restoration hook", [&] { - return hooks_.managePlugins( - Void::Json::serialize(restore)); - }); - if (!restored) { - message += std::format("; restoring the previous " - "plugin also failed: {}", - restored.error().message); - } - } - pruneStoreBestEffort(store, pluginComponent); - return Api::fail(Api::ErrorCode::UnknownError, message); - }(); - } - } else { - return Api::fail( - Api::ErrorCode::InvalidArgument, - "rollback component must be runtime, core, or a plugin id"); - } - - if (!result) { - recordHistory({.timestamp = std::chrono::system_clock::now(), - .component = component, - .pluginId = pluginId, - .action = "rollback", - .version = versionText, - .result = "failed", - .message = result.error().message, - .actor = "admin"}); - return std::unexpected(result.error()); - } - if (component == "core") { - return statusJson(); - } - if (component == "plugins" || component == "plugin") { - std::lock_guard lock(mutex_); - for (auto& plugin : pluginInventory_) { - if (plugin.id == pluginId) { - plugin.version = versionText; - plugin.managed = true; - plugin.path = options_.stateDirectory / "plugins" / - ".managed" / pluginId / "versions" / - versionText / (pluginId + ".so"); - break; - } - } - if (!rollbackPreviousVersion.empty()) { - pluginRollbackVersions_[pluginId] = rollbackPreviousVersion; - } - pluginsState_ = "healthy"; - pluginsMessage_ = "Managed plugin rollback activated"; - } - recordHistory({.timestamp = std::chrono::system_clock::now(), - .component = component, - .pluginId = pluginId, - .action = "rollback", - .version = versionText, - .result = "success", - .message = {}, - .actor = "admin"}); - return statusJson(); - } - - UpdateService::UpdateService(Options options, Hooks hooks) - : impl_(std::make_unique(std::move(options), std::move(hooks))) - { - } - - UpdateService::~UpdateService() { stop(); } - UpdateService::UpdateService(UpdateService&&) noexcept = default; - UpdateService& UpdateService::operator=(UpdateService&&) noexcept = default; - - Api::Result UpdateService::start() { return impl_->start(); } - void UpdateService::stop() noexcept { impl_->stop(); } - void UpdateService::processPendingHostActions() - { - impl_->processPendingHostActions(); - } - - Api::Result - UpdateService::handle(const std::string& method, - const std::string& requestJson) - { - return impl_->handle(method, requestJson); - } - - UpdateControlHandler bindUpdateService(std::shared_ptr service) - { - return [service = std::move(service)]( - const std::string& method, - const std::string& requestJson) { - return service->handle(method, requestJson); - }; - } - - Api::Result - selectManagedCoreForStartup(const std::filesystem::path& stateDirectory, - const std::filesystem::path& bundledCore, - const std::optional - installedRuntimeVersion) - { - const auto components = stateDirectory / "updates" / "components"; - const auto storeRoot = components / "core"; - const auto markerPath = components / "core-runtime-version"; - - const auto selectCurrent = - [&]() -> Api::Result { - Void::Update::VersionStore store(storeRoot); - if (auto initialized = store.initialize(); !initialized) { - return Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } - if (auto reconciled = store.reconcile(); !reconciled) { - return Api::fail(Api::ErrorCode::UnknownError, - reconciled.error().message()); - } - auto current = store.currentVersion(); - if (!current) { - return Api::fail(Api::ErrorCode::UnknownError, - current.error().message()); - } - if (!*current) { - return ManagedCoreStartupSelection{ - .corePath = bundledCore, - .archivedStore = std::nullopt, - .runtimeBaselineChanged = false}; - } - const auto managed = - store.versionPath(**current) / bundledCore.filename(); - std::error_code error; - const auto status = std::filesystem::symlink_status(managed, error); - if (!error && std::filesystem::is_regular_file(status) && - !std::filesystem::is_symlink(status)) { - return ManagedCoreStartupSelection{ - .corePath = managed, - .archivedStore = std::nullopt, - .runtimeBaselineChanged = false}; - } - if (error != std::errc::no_such_file_or_directory && error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot inspect managed Core '{}': {}", - managed.string(), error.message())); - } - return ManagedCoreStartupSelection{.corePath = bundledCore, - .archivedStore = std::nullopt, - .runtimeBaselineChanged = false}; - }; - - // Development trees do not have a release manifest and retain the - // historical behavior: the current managed Core, if any, wins. - if (!installedRuntimeVersion) { - return selectCurrent(); - } - if (installedRuntimeVersion->empty() || - !safeIdentifier(*installedRuntimeVersion)) { - return Api::fail(Api::ErrorCode::InvalidArgument, - "installed runtime version is not a safe " - "identifier"); - } - - std::error_code error; - std::filesystem::create_directories(components, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot prepare managed Core directory '{}': {}", - components.string(), error.message())); - } - - std::optional recordedRuntime; - const auto markerStatus = - std::filesystem::symlink_status(markerPath, error); - if (!error && - markerStatus.type() != std::filesystem::file_type::not_found) { - if (!std::filesystem::is_regular_file(markerStatus) || - std::filesystem::is_symlink(markerStatus)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "managed Core runtime marker must be a regular file"); - } - auto marker = Void::FileSystem::read_file(markerPath); - if (!marker) { - return Api::fail(Api::ErrorCode::PermissionDenied, - marker.error().message()); - } - while (!marker->empty() && - (marker->back() == '\n' || marker->back() == '\r')) { - marker->pop_back(); - } - if (!marker->empty() && !safeIdentifier(*marker)) { - return Api::fail(Api::ErrorCode::ParseError, - "managed Core runtime marker is invalid"); - } - recordedRuntime = std::move(*marker); - } else if (error != std::errc::no_such_file_or_directory && error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot inspect managed Core runtime marker: {}", - error.message())); - } - - if (recordedRuntime && *recordedRuntime == *installedRuntimeVersion) { - return selectCurrent(); - } - - std::optional archivedStore; - error.clear(); - const auto storeStatus = - std::filesystem::symlink_status(storeRoot, error); - if (!error && - storeStatus.type() != std::filesystem::file_type::not_found) { - if (!std::filesystem::is_directory(storeStatus) || - std::filesystem::is_symlink(storeStatus)) { - return Api::fail(Api::ErrorCode::PermissionDenied, - "managed Core store must be a real directory"); - } - const auto archiveRoot = components / "core-archives"; - std::filesystem::create_directories(archiveRoot, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot prepare managed Core archive: {}", - error.message())); - } - const auto archiveStatus = - std::filesystem::symlink_status(archiveRoot, error); - if (error || !std::filesystem::is_directory(archiveStatus) || - std::filesystem::is_symlink(archiveStatus)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "managed Core archive root must be a real directory"); - } - - const auto label = - recordedRuntime && safeIdentifier(*recordedRuntime) - ? *recordedRuntime - : std::string{"legacy"}; - for (std::uint32_t suffix = 0; suffix < 10000; ++suffix) { - auto candidate = - archiveRoot / - (suffix == 0 ? label : std::format("{}.{}", label, suffix)); - error.clear(); - const auto candidateStatus = - std::filesystem::symlink_status(candidate, error); - if (error == std::errc::no_such_file_or_directory || - candidateStatus.type() == - std::filesystem::file_type::not_found) { - error.clear(); - std::filesystem::rename(storeRoot, candidate, error); - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format( - "cannot archive the previous managed Core " - "store: {}", - error.message())); - } - archivedStore = std::move(candidate); - break; - } - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot inspect managed Core archive: {}", - error.message())); - } - } - if (!archivedStore) { - return Api::fail(Api::ErrorCode::AlreadyExists, - "managed Core archive namespace is exhausted"); - } - } else if (error != std::errc::no_such_file_or_directory && error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot inspect managed Core store: {}", - error.message())); - } - - Void::Update::VersionStore freshStore(storeRoot); - if (auto initialized = freshStore.initialize(); !initialized) { - return Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } - if (auto written = Void::FileSystem::atomic_write( - markerPath, std::string{*installedRuntimeVersion}); - !written) { - return Api::fail(Api::ErrorCode::PermissionDenied, - written.error().message()); - } - return ManagedCoreStartupSelection{.corePath = bundledCore, - .archivedStore = - std::move(archivedStore), - .runtimeBaselineChanged = true}; - } - - Api::Result reconcileManagedPluginUpdates( - const std::filesystem::path& stateDirectory) - { - const auto managed = stateDirectory / "plugins" / ".managed"; - std::error_code error; - const auto status = std::filesystem::symlink_status(managed, error); - if (error == std::errc::no_such_file_or_directory || - status.type() == std::filesystem::file_type::not_found) { - return {}; - } - if (error || !std::filesystem::is_directory(status) || - std::filesystem::is_symlink(status)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - "managed plugin update root is not a real directory"); - } - for (const auto& entry : - std::filesystem::directory_iterator(managed, error)) { - if (error) { - break; - } - const auto id = entry.path().filename().string(); - const auto entryStatus = entry.symlink_status(error); - if (error || !safeIdentifier(id) || - !std::filesystem::is_directory(entryStatus) || - std::filesystem::is_symlink(entryStatus)) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("managed plugin update store '{}' is unsafe", - id)); - } - Void::Update::VersionStore store(entry.path()); - if (auto initialized = store.initialize(); !initialized) { - return Api::fail(Api::ErrorCode::UnknownError, - initialized.error().message()); - } - auto pending = store.pendingActivation(); - if (!pending) { - return Api::fail(Api::ErrorCode::ParseError, - pending.error().message()); - } - if (pending->has_value()) { - if (auto reconciled = store.reconcile(); !reconciled) { - return Api::fail(Api::ErrorCode::UnknownError, - reconciled.error().message()); - } - } - } - if (error) { - return Api::fail( - Api::ErrorCode::PermissionDenied, - std::format("cannot enumerate managed plugin stores: {}", - error.message())); - } - return {}; - } -} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/main.cpp b/EchoionStandalone/src/main.cpp deleted file mode 100644 index 724c0ba..0000000 --- a/EchoionStandalone/src/main.cpp +++ /dev/null @@ -1,1001 +0,0 @@ -// Standalone Echoion host. It loads the hot-reloadable Core through CoreLoader -// and adapts Echoion's host contract to VoidTeamspeak's typed client API. - -#include "echoion/host/CoreLoader.hpp" -#include "echoion/standalone/ReleaseManifest.hpp" -#include "echoion/standalone/RuntimePaths.hpp" -#include "echoion/standalone/StandaloneClientInterface.hpp" -#include "echoion/standalone/UpdateBuildDefaults.hpp" -#include "echoion/standalone/UpdateService.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef _WIN32 -#include -#endif - -namespace -{ - std::atomic g_updateRequested{false}; - - void requestUpdate() { g_updateRequested = true; } - - std::optional argumentValue(int argc, char** argv, - std::string_view name) - { - for (int index = 1; index + 1 < argc; ++index) { - if (std::string_view{argv[index]} == name) { - return argv[index + 1]; - } - } - return std::nullopt; - } - - bool hasArgument(int argc, char** argv, std::string_view name) - { - for (int index = 1; index < argc; ++index) { - if (std::string_view{argv[index]} == name) { - return true; - } - } - return false; - } - - std::optional - optionalArgumentPath(int argc, char** argv, std::string_view name) - { - for (int index = 1; index < argc; ++index) { - if (std::string_view{argv[index]} != name) { - continue; - } - if (index + 1 < argc && - !std::string_view{argv[index + 1]}.starts_with("--")) { - return std::filesystem::path{argv[index + 1]}; - } - return std::nullopt; - } - return std::nullopt; - } - - std::optional environmentPath(const char* name) - { - const char* value = std::getenv(name); - if (!value || std::string_view{value}.empty()) { - return std::nullopt; - } - return std::filesystem::path{value}; - } - - std::filesystem::path absolutePath(const std::filesystem::path& path) - { - std::error_code error; - auto absolute = std::filesystem::absolute(path, error); - return (error ? path : absolute).lexically_normal(); - } - - struct RuntimeHandoff { - std::filesystem::path manifestPath; - std::string state; - std::string version; - std::string previousVersion; - std::uint32_t retainHealthyVersions = 2; - }; - - [[nodiscard]] std::optional - retainHealthyVersions(const Void::Json::Value& object) - { - const auto* value = object.find("retainHealthyVersions"); - if (value == nullptr) { - return 2U; - } - if (!value->is_number()) { - return std::nullopt; - } - const double number = value->as_number(); - if (!std::isfinite(number) || std::trunc(number) != number || - number < 1.0 || number > 10.0) { - return std::nullopt; - } - return static_cast(number); - } - - [[nodiscard]] bool pathWithin(const std::filesystem::path& path, - const std::filesystem::path& root) - { - auto pathIterator = path.begin(); - for (auto rootIterator = root.begin(); rootIterator != root.end(); - ++rootIterator, ++pathIterator) { - if (pathIterator == path.end() || *pathIterator != *rootIterator) { - return false; - } - } - return true; - } - - std::optional - readRuntimeHandoff(const std::filesystem::path& handoff, - const std::filesystem::path& installationPrefix) - { - auto contents = Void::FileSystem::read_file(handoff); - if (!contents) { - return std::nullopt; - } - auto parsed = Void::Json::parse(*contents); - if (!parsed || !parsed->is_object()) { - return std::nullopt; - } - const auto stringField = [&parsed](std::string_view name) { - const auto* value = parsed->find(name); - return value && value->is_string() ? value->as_string() - : std::string{}; - }; - const auto manifestValue = stringField("manifestPath"); - const auto state = stringField("state"); - const auto version = stringField("version"); - const auto retention = retainHealthyVersions(*parsed); - if (manifestValue.empty() || state.empty() || version.empty() || - !retention.has_value()) { - return std::nullopt; - } - const std::filesystem::path relativeManifest{manifestValue}; - if (relativeManifest.is_absolute()) { - return std::nullopt; - } - std::error_code error; - const auto manifest = std::filesystem::canonical( - installationPrefix / relativeManifest, error); - if (error) { - return std::nullopt; - } - const auto versions = - std::filesystem::canonical(installationPrefix / "versions", error); - if (error || !std::filesystem::is_regular_file(manifest)) { - return std::nullopt; - } - if (!pathWithin(manifest, versions)) { - return std::nullopt; - } - return RuntimeHandoff{.manifestPath = manifest, - .state = state, - .version = version, - .previousVersion = stringField("previousVersion"), - .retainHealthyVersions = *retention}; - } - - [[nodiscard]] std::filesystem::path - installationPrefix(const std::filesystem::path& installRoot) - { - std::error_code error; - if (installRoot.filename() == "current" && - std::filesystem::is_symlink( - std::filesystem::symlink_status(installRoot, error))) { - return installRoot.parent_path(); - } - return installRoot; - } - - [[nodiscard]] std::filesystem::path - updaterIncomingDirectory(const std::filesystem::path& root, - const std::filesystem::path& stateDirectory) - { - if (const auto configured = environmentPath("ECHOION_INCOMING_DIR")) { - return absolutePath(*configured); - } - if (auto record = - Void::FileSystem::read_file(root / ".echoion-install")) { - constexpr std::string_view prefix{"incoming_dir="}; - std::string_view contents{*record}; - while (!contents.empty()) { - const auto end = contents.find('\n'); - const auto line = contents.substr(0, end); - if (line.starts_with(prefix) && line.size() > prefix.size()) { - std::filesystem::path path{line.substr(prefix.size())}; - return absolutePath(path.is_absolute() ? path - : root / path); - } - if (end == std::string_view::npos) { - break; - } - contents.remove_prefix(end + 1); - } - } - return stateDirectory / "incoming"; - } - - [[nodiscard]] std::optional - runningReleaseManifest(const std::filesystem::path& executable, - const std::filesystem::path& installRoot) - { - const std::array candidates{executable.parent_path().parent_path() / - "manifest.json", - installRoot / "manifest.json"}; - for (const auto& candidate : candidates) { - if (auto manifest = - Echoion::Standalone::ReleaseManifest::load(candidate)) { - return std::move(*manifest); - } - } - return std::nullopt; - } - - [[nodiscard]] Echoion::Api::Result - invokeRuntimeHelper(const std::filesystem::path& helper, - const std::filesystem::path& root, - std::string_view operationJson) - { - auto operation = Void::Json::parse(operationJson); - if (!operation || !operation->is_object()) { - return Echoion::Api::fail( - Echoion::Api::ErrorCode::ParseError, - "runtime update operation must be a JSON object"); - } - const auto field = [&operation](std::string_view name) { - const auto* value = operation->find(name); - return value && value->is_string() ? value->as_string() - : std::string{}; - }; - const auto action = field("action"); - const auto version = field("version"); - const auto retention = retainHealthyVersions(*operation); - if (!retention.has_value()) { - return Echoion::Api::fail( - Echoion::Api::ErrorCode::InvalidArgument, - "retainHealthyVersions must be an integer from 1 to 10"); - } - std::string command; - std::vector options; - if (action == "activate") { - command = "activate-runtime"; - options = {"--staging", field("stagingId"), - "--version", version, - "--manifest-sha256", field("manifestSha256")}; - } else if (action == "rollback") { - command = "rollback-runtime"; - options = {"--version", version}; - } else if (action == "commit") { - command = "commit-runtime"; - options = {"--version", version}; - } else { - return Echoion::Api::fail(Echoion::Api::ErrorCode::InvalidArgument, - "unknown runtime update operation"); - } - if (version.empty() || - std::ranges::any_of( - options, [](const auto& value) { return value.empty(); })) { - return Echoion::Api::fail( - Echoion::Api::ErrorCode::InvalidArgument, - "runtime update operation is missing required fields"); - } - options.insert(options.end(), {"--retain", std::to_string(*retention)}); - - bool direct = false; -#ifndef _WIN32 - direct = ::access((root / "versions").c_str(), W_OK) == 0; -#endif - std::vector arguments{"--root", root.string()}; - if (!direct) { - arguments.insert(arguments.end(), {"request", command}); - } else { - arguments.push_back(command); - } - arguments.insert(arguments.end(), options.begin(), options.end()); - if (!direct) { - arguments.insert(arguments.end(), {"--origin", "daemon"}); - } - auto result = - Void::Process::run(helper, arguments, {}, std::chrono::seconds{30}); - if (!result) { - return Echoion::Api::fail( - Echoion::Api::ErrorCode::ServiceUnavailable, - result.error().message()); - } - if (result->exit_code != 0) { - return Echoion::Api::fail( - Echoion::Api::ErrorCode::ServiceUnavailable, - result->err.empty() ? "runtime update helper failed" - : result->err); - } - return result->out.empty() ? std::string{"{}"} : std::move(result->out); - } - - std::filesystem::path configDir() - { - if (const char* x = std::getenv("XDG_CONFIG_HOME")) { - return std::filesystem::path(x) / "echoion"; - } - if (const char* h = std::getenv("HOME")) { - return std::filesystem::path(h) / ".config" / "echoion"; - } - return std::filesystem::path(".") / "echoion"; - } - - bool prepareStateDirectory(const std::filesystem::path& stateDirectory, - bool explicitlySelected) - { - std::error_code error; - std::filesystem::create_directories(stateDirectory, error); - if (error) { - std::cerr << "Cannot create state directory " << stateDirectory - << ": " << error.message() << '\n'; - return false; - } - - const auto setPath = [](const char* name, - const std::filesystem::path& path, - bool overwrite) { - const auto value = path.string(); - return ::setenv(name, value.c_str(), overwrite ? 1 : 0) == 0; - }; - const auto temporaryDirectory = stateDirectory / "tmp"; - std::filesystem::create_directories(temporaryDirectory, error); - if (error) { - std::cerr << "Cannot create temporary directory " - << temporaryDirectory << ": " << error.message() << '\n'; - return false; - } - if (!setPath("ECHOION_STATE_DIR", stateDirectory, true) || - !setPath("XDG_CACHE_HOME", stateDirectory / "cache", - explicitlySelected) || - !setPath("XDG_STATE_HOME", stateDirectory / "state", - explicitlySelected) || - !setPath("XDG_DATA_HOME", stateDirectory / "data", - explicitlySelected) || - !setPath("TMPDIR", temporaryDirectory, explicitlySelected)) { - std::cerr << "Cannot export runtime state paths\n"; - return false; - } - return true; - } - - int validateInstall(const std::filesystem::path& installRoot) - { - auto manifest = Echoion::Standalone::ReleaseManifest::load( - installRoot / "manifest.json"); - if (!manifest) { - std::cerr << manifest.error().message << '\n'; - return 2; - } - if (auto result = manifest->validateInstallLayout(); !result) { - std::cerr << result.error().message << '\n'; - return 2; - } - std::cout << "Echoion installation is valid: " << installRoot << '\n'; - return 0; - } - - void recordInterruptedRelease(const std::filesystem::path& directory) - { - const auto transaction = directory / "release-transaction"; - if (!std::filesystem::exists(transaction) || - std::getenv("ECHOION_REEXEC_VERSION")) { - return; - } - auto version = Void::FileSystem::read_file(transaction); - if (version && !version->empty()) { - std::ignore = Void::FileSystem::atomic_write( - directory / "failed-release", *version); - Void::Log::error("main", - "Release {} failed its startup health check; " - "stable service restored", - *version); - } - std::ignore = Void::FileSystem::remove_path(transaction); - } - - std::string envOr(const char* key, const std::string& fallback) - { - const char* v = std::getenv(key); - return v ? std::string(v) : fallback; - } - - int envInt(const char* key, int fallback) - { - const char* v = std::getenv(key); - if (!v) { - return fallback; - } - try { - return std::stoi(v); - } catch (...) { - return fallback; - } - } - - int importIdentity(int argc, char** argv, - const std::filesystem::path& defaultIdentityPath) - { - std::optional source; - auto destination = defaultIdentityPath; - bool force = false; - bool importRequested = false; - for (int i = 1; i < argc; ++i) { - const std::string_view argument{argv[i]}; - if (argument == "--help") { - std::cout - << "Usage: echoiond [--config PATH] [--state-dir PATH]\n" - " echoiond --import-identity EXPORT.ini " - "[--identity-path PATH] [--force]\n" - " echoiond --validate-install [ROOT]\n"; - return 0; - } - if (argument == "--import-identity") { - importRequested = true; - if (i + 1 < argc && - !std::string_view{argv[i + 1]}.starts_with("--")) { - source = argv[++i]; - } - } else if (argument == "--identity-path" && i + 1 < argc) { - destination = argv[++i]; - } else if (argument == "--force") { - force = true; - } - } - if (!importRequested) { - return -1; - } - if (!source) { - std::cerr << "--import-identity requires an exported INI path.\n"; - return 2; - } - try { - if (std::filesystem::exists(destination) && !force) { - std::cerr << "Identity already exists at " << destination - << "; pass --force to replace it.\n"; - return 2; - } - const auto identity = - Void::TeamSpeak::Identity::importTeamSpeakIni(source->string()); - if (const auto parent = destination.parent_path(); - !parent.empty()) { - std::filesystem::create_directories(parent); - } - identity.save(destination.string()); - std::cout << "Imported TeamSpeak identity " << identity.uid() - << " to " << destination << '\n'; - return 0; - } catch (const std::exception& error) { - std::cerr << "Identity import failed: " << error.what() << '\n'; - return 2; - } - } -} // namespace - -int main(int argc, char** argv) -{ - std::set_terminate([] { - const auto frames = Void::Stacktrace::capture_stacktrace(); - std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n'; - std::abort(); - }); - - if (hasArgument(argc, argv, "--validate-release")) { - const auto validationPath = - argumentValue(argc, argv, "--validate-release"); - if (!validationPath || validationPath->starts_with("--")) { - std::cerr << "--validate-release requires a manifest path\n"; - return 2; - } - auto manifest = - Echoion::Standalone::ReleaseManifest::load(*validationPath); - if (!manifest) { - std::cerr << manifest.error().message << '\n'; - return 2; - } - if (auto result = manifest->validate(); !result) { - std::cerr << result.error().message << '\n'; - return 2; - } - return 0; - } - - const auto runningExecutable = Echoion::Standalone::runningExecutablePath(); - if (!runningExecutable) { - std::cerr << runningExecutable.error() << '\n'; - return 2; - } - const auto installRoot = Echoion::Standalone::deriveInstallRoot( - *runningExecutable, environmentPath("ECHOION_HOME")); - const auto updateRoot = installationPrefix(installRoot); - if (hasArgument(argc, argv, "--validate-install")) { - const auto requestedRoot = - optionalArgumentPath(argc, argv, "--validate-install"); - return validateInstall(requestedRoot ? absolutePath(*requestedRoot) - : installRoot); - } - const auto installRootString = installRoot.string(); - if (::setenv("ECHOION_HOME", installRootString.c_str(), 1) != 0) { - std::cerr << "Cannot export ECHOION_HOME\n"; - return 2; - } - if (!environmentPath("SSL_CERT_FILE")) { - if (const auto certificateBundle = - Echoion::Standalone::bundledCertificateBundle(installRoot)) { - const auto bundleString = certificateBundle->string(); - if (::setenv("SSL_CERT_FILE", bundleString.c_str(), 0) != 0) { - std::cerr << "Cannot export bundled TLS certificate store\n"; - return 2; - } - } - } - for (const std::string_view requiredValue : {"--config", "--state-dir"}) { - if (hasArgument(argc, argv, requiredValue) && - !optionalArgumentPath(argc, argv, requiredValue)) { - std::cerr << requiredValue << " requires a path\n"; - return 2; - } - } - - const auto cfgDir = absolutePath(configDir()); - std::filesystem::path cfgPath = cfgDir / "config.json"; - if (const auto requestedConfig = - optionalArgumentPath(argc, argv, "--config")) { - cfgPath = absolutePath(*requestedConfig); - } - const auto commandLineState = - optionalArgumentPath(argc, argv, "--state-dir"); - const auto environmentState = environmentPath("ECHOION_STATE_DIR"); - const auto stateDirectory = Echoion::Standalone::resolveStateDirectory( - commandLineState, environmentState, environmentPath("XDG_STATE_HOME"), - environmentPath("HOME"), cfgDir); - if (!prepareStateDirectory(stateDirectory, - commandLineState.has_value() || - environmentState.has_value())) { - return 2; - } - auto signalWatcherResult = Void::Process::SignalWatcher::create(); - if (!signalWatcherResult) { - std::cerr << "Cannot install signal watcher: " - << signalWatcherResult.error().message() << '\n'; - return 2; - } - auto signalWatcher = std::move(*signalWatcherResult); - recordInterruptedRelease(stateDirectory); - - const auto identityPath = absolutePath(std::filesystem::path(envOr( - "ECHOION_IDENTITY_PATH", (stateDirectory / "identity.txt").string()))); - if (const auto importResult = importIdentity(argc, argv, identityPath); - importResult >= 0) { - return importResult; - } - const auto requestedRestore = - optionalArgumentPath(argc, argv, "--restore-state"); - const std::optional restorePath = - requestedRestore ? std::optional{absolutePath(*requestedRestore)} - : std::nullopt; - const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST"); - const auto activationHandoff = - stateDirectory / "updates" / "activated-runtime.json"; - const auto releaseTriggerPath = requestedManifest - ? absolutePath(*requestedManifest) - : activationHandoff; - const bool releaseTriggerIsHandoff = !requestedManifest.has_value(); - const auto runningManifest = - runningReleaseManifest(*runningExecutable, installRoot); - const auto runtimeVersion = - runningManifest - ? runningManifest->version - : std::string{ - Echoion::Standalone::UpdateBuildDefaults::RuntimeVersion}; - if (auto recovered = - Echoion::Standalone::reconcileManagedPluginUpdates(stateDirectory); - !recovered) { - Void::Log::error("main", "cannot recover managed plugin updates: {}", - recovered.error().message); - return 1; - } - - Echoion::Standalone::StandaloneSettings settings; - settings.identityPath = identityPath.string(); - settings.avatarCachePath = (stateDirectory / "avatars").string(); - settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8); - settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000); - - auto interface = - std::make_shared( - settings); - if (auto r = interface->initialize(); !r) { - Void::Log::error("main", "interface init failed: {}", - r.error().message); - return 1; - } - - Echoion::Host::CoreLoader loader; - loader.setConfigPath(cfgPath); - - const auto executableDirectory = runningExecutable->parent_path(); - const auto configuredCoreOverride = environmentPath("ECHOION_CORE_PATH"); - const auto configuredCorePath = Echoion::Standalone::resolveCorePath( - installRoot, executableDirectory, configuredCoreOverride); - const bool customCoreOverride = - configuredCoreOverride && - absolutePath(*configuredCoreOverride) != - absolutePath(installRoot / "lib" / "Echoion.ts"); - auto corePathResolved = configuredCorePath; - if (!customCoreOverride) { - const auto installedRuntimeVersion = - runningManifest ? std::optional{runtimeVersion} - : std::nullopt; - auto selection = Echoion::Standalone::selectManagedCoreForStartup( - stateDirectory, configuredCorePath, installedRuntimeVersion); - if (!selection) { - Void::Log::warn( - "main", - "Cannot reconcile managed Core startup state; using the " - "bundled Core: {}", - selection.error().message); - } else { - corePathResolved = selection->corePath; - if (selection->runtimeBaselineChanged) { - if (selection->archivedStore) { - Void::Log::info( - "main", - "Runtime {} selected its bundled Core and archived " - "the previous managed Core store at {}", - runtimeVersion, - selection->archivedStore->string()); - } else { - Void::Log::info( - "main", - "Runtime {} selected its bundled Core baseline", - runtimeVersion); - } - } - } - } - if (const auto workingDirectory = - Echoion::Standalone::runtimeWorkingDirectory(installRoot, - executableDirectory)) { - std::error_code error; - std::filesystem::current_path(*workingDirectory, error); - if (error) { - Void::Log::error("main", - "cannot select runtime asset directory {}: {}", - workingDirectory->string(), error.message()); - return 1; - } - } - Void::Log::info("main", "Loading Core from {}", corePathResolved.string()); - if (auto r = loader.load(corePathResolved); !r) { - Void::Log::error("main", "failed to load Core: {}", r.error().message); - return 1; - } - if (restorePath) { - if (auto result = loader.restoreCheckpoint(*restorePath); !result) { - Void::Log::error("main", "failed to restore restart checkpoint: {}", - result.error().message); - return 1; - } - } - - auto core = loader.getCore(); - if (!core) { - Void::Log::error("main", "Core not available after load"); - return 1; - } - - core->setPluginInterface(interface); - interface->registerEventCallback( - [core](const Echoion::Api::PluginEvent& ev) { - std::ignore = core->onPluginEvent(ev); - }); - loader.setHotReloadPrepareCallback( - [interface] { interface->quiesceEventCallbacks(); }); - // Re-register the Core callback after each hot reload (new Core instance). - loader.setHotReloadCallback([&loader, interface] { - if (auto c = loader.getCore()) { - c->setPluginInterface(interface); - interface->registerEventCallback( - [c](const Echoion::Api::PluginEvent& ev) { - std::ignore = c->onPluginEvent(ev); - }); - c->triggerAutoConnect(); - } - }); - - const auto updaterExecutable = - runningExecutable->parent_path() / "echoion-updater"; - auto updateService = std::make_shared( - Echoion::Standalone::UpdateService::Options{ - .configPath = cfgPath, - .stateDirectory = stateDirectory, - .installRoot = updateRoot, - .runningExecutable = *runningExecutable, - .currentCore = corePathResolved, - .releaseManifestPath = runningManifest - ? runningManifest->root / "manifest.json" - : std::filesystem::path{}, - .officialFeedUrl = - std::string{Echoion::Standalone::UpdateBuildDefaults::FeedUrl}, - .officialPublicKeysJson = - std::string{ - Echoion::Standalone::UpdateBuildDefaults::PublicKeysJson}, - .runtimeVersion = runtimeVersion, - .apiVersion = Echoion::Api::VERSION_STRING, - .toolchainAbi = - std::string{ - Echoion::Standalone::UpdateBuildDefaults::ToolchainAbi}, - .incomingDirectory = - updaterIncomingDirectory(updateRoot, stateDirectory)}, - Echoion::Standalone::UpdateService::Hooks{ - .replaceCore = - [&loader](const std::filesystem::path& path) { - return loader.hotReload(path); - }, - .managePlugins = [&loader](const std::string& request) - -> Echoion::Api::Result { - if (auto loadedCore = loader.getCore()) { - return loadedCore->managePluginsJson(request); - } - return Echoion::Api::fail( - Echoion::Api::ErrorCode::ServiceUnavailable, - "Core is not available"); - }, - .manageRuntime = - [updaterExecutable, updateRoot](const std::string& request) { - return invokeRuntimeHelper(updaterExecutable, updateRoot, - request); - }, - .playbackActive = - [&loader] { - auto loadedCore = loader.getCore(); - if (!loadedCore) { - return false; - } - auto playback = loadedCore->getPlaybackSummary(); - return playback && playback->isPlaying && - playback->currentTrack.has_value(); - }, - .coreVersion = - [&loader] { - if (auto loadedCore = loader.getCore()) { - return loadedCore->getVersion(); - } - return std::string{}; - }}); - if (auto started = updateService->start(); !started) { - Void::Log::error("main", "Updater disabled: {}", - started.error().message); - updateService.reset(); - } else { - interface->setHostControlHandler( - Echoion::Standalone::bindUpdateService(updateService)); - } - - core->triggerAutoConnect(); - core.reset(); - auto releaseWatcher = std::make_unique(); - releaseWatcher->watch( - releaseTriggerPath, - [](const Void::FileSystem::FileWatcher::Event& event) { - if (event.exists) { - requestUpdate(); - } - }); - Void::Log::info("main", "Watching runtime update trigger {}", - releaseTriggerPath.string()); - if (std::filesystem::is_regular_file(releaseTriggerPath)) { - requestUpdate(); - } - - if (!std::filesystem::is_regular_file(installRoot / "manifest.json")) { - // Compatibility mode for development. Production release bundles use - // transactional daemon re-exec instead of replacing Core in isolation. - loader.enableAutoReload(); - } else { - Void::Log::info( - "main", "{}", - "Core auto-reload is disabled for an installed release payload"); - } - - Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop."); - std::optional healthVersion; - if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) { - healthVersion = version; - Void::Log::info("main", "Release {} entered its 30 second health check", - *healthVersion); - } - auto healthDeadline = - std::chrono::steady_clock::now() + std::chrono::seconds{30}; - - std::optional pendingRelease; - std::filesystem::path checkpointPath; - bool stopRequested = false; - while (!stopRequested && !pendingRelease) { - if (updateService) { - updateService->processPendingHostActions(); - } - - if (healthVersion && - std::chrono::steady_clock::now() >= healthDeadline) { - bool committed = true; - const auto handoff = - readRuntimeHandoff(activationHandoff, updateRoot); - if (handoff && handoff->state == "pending" && - handoff->version == *healthVersion) { - Void::Json::Value operation = Void::Json::object(); - operation.as_object().emplace_back("action", - Void::Json::Value{"commit"}); - operation.as_object().emplace_back( - "version", Void::Json::Value{*healthVersion}); - operation.as_object().emplace_back( - "retainHealthyVersions", - Void::Json::Value{static_cast( - handoff->retainHealthyVersions)}); - auto result = - invokeRuntimeHelper(updaterExecutable, updateRoot, - Void::Json::serialize(operation)); - if (!result) { - committed = false; - Void::Log::error("main", - "Cannot confirm runtime {} health: {}", - *healthVersion, result.error().message); - } - } - if (committed) { - std::ignore = Void::FileSystem::atomic_write( - stateDirectory / "release-health", *healthVersion); - std::ignore = Void::FileSystem::remove_path( - stateDirectory / "release-transaction"); - std::ignore = Void::FileSystem::remove_path(stateDirectory / - "failed-release"); - Void::Log::info("main", "Release {} passed its health check", - *healthVersion); - healthVersion.reset(); - ::unsetenv("ECHOION_REEXEC_VERSION"); - } else { - healthDeadline = - std::chrono::steady_clock::now() + std::chrono::seconds{5}; - } - } - - if (g_updateRequested.exchange(false)) { - auto manifestPath = releaseTriggerPath; - if (releaseTriggerIsHandoff) { - auto handoff = - readRuntimeHandoff(releaseTriggerPath, updateRoot); - if (!handoff) { - Void::Log::error("main", - "runtime activation handoff is invalid"); - continue; - } - if (handoff->version == runtimeVersion) { - continue; - } - manifestPath = handoff->manifestPath; - } - auto manifest = - Echoion::Standalone::ReleaseManifest::load(manifestPath); - if (!manifest) { - Void::Log::error("main", "release rejected: {}", - manifest.error().message); - continue; - } - if (manifest->version == runtimeVersion) { - continue; - } - if (auto failed = Void::FileSystem::read_file(stateDirectory / - "failed-release"); - failed && *failed == manifest->version) { - Void::Log::error( - "main", - "Release {} was previously rolled back; publish a new " - "version to retry", - manifest->version); - continue; - } - auto validation = Void::Process::run( - *runningExecutable, - {"--validate-release", manifestPath.string()}, {}, - std::chrono::seconds{30}); - if (!validation || validation->exit_code != 0) { - Void::Log::error("main", "release validation failed: {}", - validation ? validation->err - : validation.error().message()); - continue; - } - checkpointPath = stateDirectory / "restart-state.bin"; - if (auto checkpoint = loader.checkpoint(checkpointPath); - !checkpoint) { - Void::Log::error("main", "release checkpoint failed: {}", - checkpoint.error().message); - continue; - } - pendingRelease = std::move(*manifest); - continue; - } - - auto observedSignal = - signalWatcher.wait(std::chrono::milliseconds{250}); - if (!observedSignal) { - Void::Log::error("main", "signal watcher failed: {}", - observedSignal.error().message()); - stopRequested = true; - } else if (observedSignal->has_value()) { - stopRequested = true; - } - } - - releaseWatcher.reset(); - Void::Log::info("main", "{}", - pendingRelease ? "Applying validated release..." - : "Shutting down..."); - interface->setHostControlHandler({}); - if (updateService) { - updateService->stop(); - } - updateService.reset(); - loader.disableAutoReload(); - (void)interface->disconnectFromServer(); - interface->quiesceEventCallbacks(); - (void)loader.unload(); - (void)interface->shutdown(); - if (pendingRelease) { - if (auto transaction = Void::FileSystem::atomic_write( - stateDirectory / "release-transaction", - pendingRelease->version); - !transaction) { - Void::Log::error("main", "cannot record release transaction: {}", - transaction.error().message()); - return 1; - } - const auto pendingRoot = - Echoion::Standalone::deriveInstallRoot(pendingRelease->executable); - const auto pendingHome = - releaseTriggerIsHandoff ? updateRoot / "current" : pendingRoot; - const auto pendingRootString = pendingHome.string(); - const auto pendingCoreString = pendingRelease->core.string(); - if (::setenv("ECHOION_HOME", pendingRootString.c_str(), 1) != 0 || - ::setenv("ECHOION_CORE_PATH", pendingCoreString.c_str(), 1) != 0 || - ::setenv("ECHOION_REEXEC_VERSION", pendingRelease->version.c_str(), - 1) != 0) { - Void::Log::error("main", "cannot export pending release paths"); - return 1; - } - std::vector arguments; - arguments.reserve(static_cast(argc) + 2); - for (int index = 1; index < argc; ++index) { - const std::string_view argument{argv[index]}; - if (argument == "--restore-state") { - ++index; - continue; - } - arguments.emplace_back(argument); - } - arguments.emplace_back("--restore-state"); - arguments.push_back(checkpointPath.string()); - if (auto result = - Void::Process::reexec(pendingRelease->executable, arguments); - !result) { - Void::Log::error("main", "release re-exec failed: {}", - result.error().message()); - return 1; - } - } - return 0; -} diff --git a/EchoionStandalone/tests/test_core_loader_reload.cpp b/EchoionStandalone/tests/test_core_loader_reload.cpp deleted file mode 100644 index 03b73e3..0000000 --- a/EchoionStandalone/tests/test_core_loader_reload.cpp +++ /dev/null @@ -1,160 +0,0 @@ -#include "echoion/host/CoreLoader.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace -{ - int fail(const char* message) - { - std::cerr << message << '\n'; - return 1; - } -} // namespace - -int main() -{ - const auto root = std::filesystem::temp_directory_path() / - ("echoion-core-reload-" + std::to_string(::getpid())); - std::filesystem::create_directories(root); - const auto cleanup = [&root] { - std::error_code ec; - std::filesystem::permissions(root / "immutable-lib", - std::filesystem::perms::owner_all, - std::filesystem::perm_options::add, ec); - std::filesystem::remove_all(root, ec); - }; - - ::setenv("XDG_CONFIG_HOME", root.c_str(), 1); - ::setenv("XDG_CACHE_HOME", root.c_str(), 1); - ::setenv("HOME", root.c_str(), 1); - const auto stateDirectory = root / "runtime-state"; - ::setenv("ECHOION_STATE_DIR", stateDirectory.c_str(), 1); - const auto dataDirectory = stateDirectory / "data"; - ::setenv("XDG_DATA_HOME", dataDirectory.c_str(), 1); - const auto ytDlp = dataDirectory / "echoion" / "yt-dlp" / "yt-dlp"; - std::filesystem::create_directories(ytDlp.parent_path()); - { - std::ofstream output{ytDlp}; - output << "#!/bin/sh\necho 9999.01.01\n"; - } - { - std::ofstream output{ytDlp.parent_path() / ".last_update"}; - output << std::time(nullptr); - } - std::filesystem::permissions(ytDlp, - std::filesystem::perms::owner_read | - std::filesystem::perms::owner_write | - std::filesystem::perms::owner_exec); - const auto config = root / "config.json"; - { - std::ofstream output{config}; - output << R"({ - "network": {"rpcEnabled": false}, - "web": {"enabled": false}, - "features": {"enableAutoUpdateCheck": false}, - "advanced": {"cacheEnabled": false} - })"; - } - - const auto coreDirectory = root / "immutable-lib"; - std::filesystem::create_directories(coreDirectory); - const auto corePath = coreDirectory / "Echoion.ts"; - std::filesystem::copy_file(ECHOION_TEST_CORE_PATH, corePath); - const auto directoryEntries = [&coreDirectory] { - std::set entries; - for (const auto& entry : - std::filesystem::directory_iterator{coreDirectory}) { - entries.insert(entry.path().filename()); - } - return entries; - }; - const auto entriesBeforeLoad = directoryEntries(); - std::filesystem::permissions(coreDirectory, - std::filesystem::perms::owner_read | - std::filesystem::perms::owner_exec | - std::filesystem::perms::group_read | - std::filesystem::perms::group_exec | - std::filesystem::perms::others_read | - std::filesystem::perms::others_exec, - std::filesystem::perm_options::replace); - - Echoion::Host::CoreLoader loader; - loader.setConfigPath(config); - if (auto result = loader.load(corePath); !result) { - cleanup(); - return fail(result.error().message.c_str()); - } - if (directoryEntries() != entriesBeforeLoad) { - cleanup(); - return fail( - "initial Core load wrote into the immutable library directory"); - } - loader.enableAutoReload(); - if (loader.isAutoReloadEnabled()) { - cleanup(); - return fail("auto-reload was enabled for a read-only Core directory"); - } - std::filesystem::permissions(coreDirectory, - std::filesystem::perms::owner_all | - std::filesystem::perms::group_read | - std::filesystem::perms::group_exec | - std::filesystem::perms::others_read | - std::filesystem::perms::others_exec, - std::filesystem::perm_options::replace); - loader.enableAutoReload(); - if (!loader.isAutoReloadEnabled()) { - cleanup(); - return fail( - "auto-reload was not enabled for a writable development Core"); - } - loader.disableAutoReload(); - const auto before = loader.getCore(); - if (!before) { - cleanup(); - return fail("Core missing after initial load"); - } - if (!std::filesystem::is_regular_file(stateDirectory / "echoion.db") || - std::filesystem::exists(root / "echoion.db") || - !std::filesystem::is_directory(stateDirectory / "logs")) { - cleanup(); - return fail("Core mutable files did not use ECHOION_STATE_DIR"); - } - if (auto result = loader.hotReload(corePath); !result) { - cleanup(); - return fail(result.error().message.c_str()); - } - const auto after = loader.getCore(); - if (!after || after.get() == before.get()) { - cleanup(); - return fail("Core instance was not transactionally replaced"); - } - - const auto invalid = root / "Echoion.invalid"; - { - std::ofstream output{invalid, std::ios::binary}; - output << "not a shared library"; - } - std::filesystem::rename(invalid, corePath); - if (auto result = loader.hotReload(corePath); result) { - cleanup(); - return fail("invalid replacement unexpectedly activated"); - } - const auto retained = loader.getCore(); - if (!retained || retained.get() != after.get() || - !retained->isInitialized()) { - cleanup(); - return fail("running Core was not retained after failed activation"); - } - if (auto result = loader.unload(); !result) { - cleanup(); - return fail(result.error().message.c_str()); - } - cleanup(); - return 0; -} diff --git a/EchoionStandalone/tests/test_event_callback_gate.cpp b/EchoionStandalone/tests/test_event_callback_gate.cpp deleted file mode 100644 index 6bedd97..0000000 --- a/EchoionStandalone/tests/test_event_callback_gate.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "echoion/standalone/EventCallbackGate.hpp" - -#include -#include -#include -#include -#include -#include -#include - -int main() -{ - Echoion::Standalone::EventCallbackGate gate; - std::mutex mutex; - std::condition_variable enteredCv; - std::condition_variable releaseCv; - bool entered = false; - bool release = false; - std::atomic calls{0}; - auto lifetime = std::make_shared(42); - std::weak_ptr observedLifetime = lifetime; - - gate.add([&, lifetime](const Echoion::Api::PluginEvent&) { - ++calls; - std::unique_lock lock(mutex); - entered = true; - enteredCv.notify_all(); - releaseCv.wait(lock, [&] { return release; }); - }); - lifetime.reset(); - - Echoion::Api::PluginEvent event; - auto dispatch = std::async(std::launch::async, [&] { gate.dispatch(event); }); - { - std::unique_lock lock(mutex); - enteredCv.wait(lock, [&] { return entered; }); - } - - auto quiesce = std::async(std::launch::async, [&] { gate.quiesce(); }); - assert(quiesce.wait_for(std::chrono::milliseconds{30}) == - std::future_status::timeout); - assert(!observedLifetime.expired()); - - { - std::lock_guard lock(mutex); - release = true; - } - releaseCv.notify_all(); - dispatch.get(); - quiesce.get(); - assert(observedLifetime.expired()); - - gate.dispatch(event); - assert(calls == 1); - - gate.add([&](const Echoion::Api::PluginEvent&) { ++calls; }); - gate.dispatch(event); - assert(calls == 2); -} diff --git a/EchoionStandalone/tests/test_message_chunker.cpp b/EchoionStandalone/tests/test_message_chunker.cpp deleted file mode 100644 index c880af1..0000000 --- a/EchoionStandalone/tests/test_message_chunker.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "echoion/standalone/MessageChunker.hpp" - -#include -#include - -namespace -{ - bool check(bool condition, const char* message) - { - if (!condition) { - std::cerr << "FAILED: " << message << '\n'; - } - return condition; - } -} - -int main() -{ - using Echoion::Standalone::chunkMessage; - bool passed = true; - - const std::string header = "# Help\n\n> [!TIP] Prefix is `!`\n\n"; - const std::string details = - ":::details ▶ Play — commands\n\n" + std::string(1100, 'x') + - "\n\n`!play` query\n> description\n:::\n\n"; - const auto helpChunks = chunkMessage(header + details, 900); - passed &= check(helpChunks.size() == 2, - "help header and details block should be separate messages"); - passed &= check(helpChunks.size() > 1 && - helpChunks[1] == details.substr(0, details.size() - 1), - "details container must remain complete even above the limit"); - - const std::string utf8Line = std::string(899, 'a') + "я" + "tail"; - const auto utf8Chunks = chunkMessage(utf8Line, 900); - passed &= check(utf8Chunks.size() == 2, - "long ordinary line should be split"); - passed &= check(!utf8Chunks.empty() && utf8Chunks.front().size() == 899, - "UTF-8 sequence should not be split in the middle"); - - return passed ? 0 : 1; -} diff --git a/EchoionStandalone/tests/test_release_manifest.cpp b/EchoionStandalone/tests/test_release_manifest.cpp deleted file mode 100644 index 43de15c..0000000 --- a/EchoionStandalone/tests/test_release_manifest.cpp +++ /dev/null @@ -1,289 +0,0 @@ -#include "echoion/standalone/ReleaseManifest.hpp" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace -{ - constexpr std::string_view kAbcSha256 = - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; - - std::string fileEntry(std::string_view path, std::uintmax_t size, - std::string_view mode, - std::string_view sha256 = kAbcSha256) - { - return "{\"path\":\"" + std::string(path) + - "\",\"type\":\"file\",\"size\":" + std::to_string(size) + - ",\"mode\":\"" + std::string(mode) + "\",\"sha256\":\"" + - std::string(sha256) + "\"}"; - } - - std::string symlinkEntry(std::string_view path, std::string_view target) - { - return "{\"path\":\"" + std::string(path) + - "\",\"type\":\"symlink\",\"target\":\"" + std::string(target) + - "\"}"; - } - - std::string manifest(std::vector entries, - std::string_view executable = "bin/echoiond", - std::string_view core = "lib/Echoion.ts") - { - std::string files; - for (const auto& entry : entries) { - if (!files.empty()) { - files += ','; - } - files += entry; - } - return "{\"schemaVersion\":2,\"version\":\"1.2.3\"," - "\"executable\":\"" + - std::string(executable) + "\",\"core\":\"" + std::string(core) + - "\",\"files\":[" + files + "]}"; - } - - bool writeFile(const std::filesystem::path& path, std::string_view contents, - std::filesystem::perms permissions) - { - std::filesystem::create_directories(path.parent_path()); - if (auto result = Void::FileSystem::atomic_write(path, contents); - !result) { - std::cerr << result.error().message() << '\n'; - return false; - } - std::error_code error; - std::filesystem::permissions( - path, permissions, std::filesystem::perm_options::replace, error); - if (error) { - std::cerr << error.message() << '\n'; - return false; - } - return true; - } -} // namespace - -int main() -{ - int failures{}; - const auto check = [&failures](bool condition, std::string_view message) { - if (!condition) { - std::cerr << message << '\n'; - ++failures; - } - }; - - auto directory = Void::FileSystem::TempDir::open("echoion-manifest-test"); - if (!directory) { - std::cerr << directory.error().message() << '\n'; - return 1; - } - const auto root = directory->path(); - const auto manifestPath = root / "manifest.json"; - const auto executablePath = root / "bin" / "echoiond"; - const auto corePath = root / "lib" / "Echoion.ts"; - const auto webPath = root / "share" / "echoion" / "web" / "index.html"; - const auto servicePath = root / "service" / "echoion.service.in"; - const auto aliasPath = root / "lib" / "libEchoionCore.so"; - const auto otherPath = root / "lib" / "Other.so"; - const auto executableMode = std::filesystem::perms::owner_read | - std::filesystem::perms::owner_write | - std::filesystem::perms::owner_exec | - std::filesystem::perms::group_read | - std::filesystem::perms::group_exec | - std::filesystem::perms::others_read | - std::filesystem::perms::others_exec; - const auto regularMode = std::filesystem::perms::owner_read | - std::filesystem::perms::owner_write | - std::filesystem::perms::group_read | - std::filesystem::perms::others_read; - - if (!writeFile(executablePath, "abc", executableMode) || - !writeFile(corePath, "abc", regularMode) || - !writeFile(webPath, "abc", regularMode) || - !writeFile(servicePath, "abc", regularMode) || - !writeFile(otherPath, "abc", regularMode)) { - return 1; - } - std::error_code error; - std::filesystem::create_symlink("Echoion.ts", aliasPath, error); - if (error) { - std::cerr << error.message() << '\n'; - return 1; - } - - const auto validManifest = manifest({ - fileEntry("bin/echoiond", 3, "0755"), - fileEntry("lib/Echoion.ts", 3, "0644"), - fileEntry("lib/Other.so", 3, "0644"), - fileEntry("service/echoion.service.in", 3, "0644"), - fileEntry("share/echoion/web/index.html", 3, "0644"), - symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"), - }); - check( - Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(), - "failed to write valid manifest"); - auto loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath); - check(loaded.has_value(), "valid v2 manifest was rejected while loading"); - if (loaded) { - check(loaded->validate().has_value(), - "valid v2 manifest payload was rejected"); - check(loaded->validateInstallLayout().has_value(), - "valid canonical install layout was rejected"); - - const auto undeclaredFile = root / "lib" / "undeclared.so"; - check(writeFile(undeclaredFile, "abc", regularMode), - "failed to create undeclared regular-file fixture"); - check(!loaded->validate(), - "undeclared regular file in immutable payload was accepted"); - std::filesystem::remove(undeclaredFile, error); - - const auto undeclaredLink = root / "lib" / "undeclared-link.so"; - std::filesystem::create_symlink("Echoion.ts", undeclaredLink, error); - check(!error, "failed to create undeclared symbolic-link fixture"); - check(!loaded->validate(), - "undeclared symbolic link in immutable payload was accepted"); - std::filesystem::remove(undeclaredLink, error); - - const auto specialFile = root / "lib" / "unexpected.fifo"; - check(::mkfifo(specialFile.c_str(), 0600) == 0, - "failed to create special-file fixture"); - check(!loaded->validate(), - "special file in immutable payload was accepted"); - std::filesystem::remove(specialFile, error); - - check(writeFile(root / "data" / "mutable-state", "abc", regularMode), - "failed to create mutable-root fixture"); - check(loaded->validate().has_value(), - "mutable file outside immutable payload roots was rejected"); - - std::filesystem::permissions(root / "lib", std::filesystem::perms::all, - std::filesystem::perm_options::replace, - error); - check(!error, "failed to make immutable directory writable"); - check(!loaded->validate(), - "world-writable immutable directory was accepted"); - std::filesystem::permissions(root / "lib", - std::filesystem::perms::owner_all | - std::filesystem::perms::group_read | - std::filesystem::perms::group_exec | - std::filesystem::perms::others_read | - std::filesystem::perms::others_exec, - std::filesystem::perm_options::replace, - error); - check(!error, "failed to restore immutable directory mode"); - } - - const auto expectLoadFailure = [&](const std::string& contents, - std::string_view message) { - check( - Void::FileSystem::atomic_write(manifestPath, contents).has_value(), - "failed to write invalid manifest fixture"); - check(!Echoion::Standalone::ReleaseManifest::load(manifestPath), - message); - }; - expectLoadFailure(manifest({fileEntry("../echoiond", 3, "0755"), - fileEntry("lib/Echoion.ts", 3, "0644")}, - "../echoiond"), - "path traversal manifest was accepted"); - expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"), - fileEntry("bin/echoiond", 3, "0755"), - fileEntry("lib/Echoion.ts", 3, "0644")}), - "duplicate payload path was accepted"); - expectLoadFailure( - manifest({fileEntry("bin/echoiond", 3, "0755"), - fileEntry("lib/Echoion.ts", 3, "0644"), - symlinkEntry("lib/escape.so", "../outside.so")}), - "traversing symbolic link target was accepted"); - expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0777"), - fileEntry("lib/Echoion.ts", 3, "0644")}), - "world-writable executable metadata was accepted"); - expectLoadFailure(manifest({fileEntry("bin/echoiond", 3, "0755"), - fileEntry("lib/Echoion.ts", 3, "0666")}), - "world-writable non-executable metadata was accepted"); - check(writeFile(root / "outside.dat", "abc", regularMode), - "failed to create outside-root manifest fixture"); - const auto outsideManifest = manifest({ - fileEntry("bin/echoiond", 3, "0755"), - fileEntry("lib/Echoion.ts", 3, "0644"), - fileEntry("lib/Other.so", 3, "0644"), - fileEntry("service/echoion.service.in", 3, "0644"), - fileEntry("share/echoion/web/index.html", 3, "0644"), - symlinkEntry("lib/libEchoionCore.so", "Echoion.ts"), - fileEntry("outside.dat", 3, "0644"), - }); - check(Void::FileSystem::atomic_write(manifestPath, outsideManifest) - .has_value(), - "failed to write outside-root manifest"); - const auto outside = - Echoion::Standalone::ReleaseManifest::load(manifestPath); - check(outside.has_value() && !outside->validate(), - "manifest entry outside immutable roots was accepted"); - expectLoadFailure("{\"schemaVersion\":3,\"version\":\"future\"}", - "unsupported schema version was accepted"); - - check( - Void::FileSystem::atomic_write(manifestPath, validManifest).has_value(), - "failed to restore valid manifest"); - loaded = Echoion::Standalone::ReleaseManifest::load(manifestPath); - if (!loaded) { - std::cerr << "could not reload valid manifest\n"; - return 1; - } - { - std::ofstream output(corePath, std::ios::trunc); - output << "xyz"; - } - check(!loaded->validate(), "tampered payload hash was accepted"); - check(writeFile(corePath, "abc", regularMode), - "failed to restore Core fixture"); - - std::filesystem::permissions(corePath, std::filesystem::perms::owner_read, - std::filesystem::perm_options::replace, error); - check(!error, "failed to modify Core permissions fixture"); - check(!loaded->validate(), "payload mode mismatch was accepted"); - std::filesystem::permissions(corePath, regularMode, - std::filesystem::perm_options::replace, error); - - std::filesystem::remove(aliasPath, error); - std::filesystem::create_symlink("Other.so", aliasPath, error); - check(!error, "failed to replace symbolic link fixture"); - check(!loaded->validate(), "symbolic link target mismatch was accepted"); - std::filesystem::remove(aliasPath, error); - check(writeFile(aliasPath, "abc", regularMode), - "failed to create wrong-type fixture"); - check(!loaded->validate(), "unexpected regular-file type was accepted"); - std::filesystem::remove(aliasPath, error); - std::filesystem::create_symlink("Echoion.ts", aliasPath, error); - - std::filesystem::remove(webPath, error); - check(!loaded->validate(), "missing payload entry was accepted"); - check(writeFile(webPath, "abc", regularMode), - "failed to restore web fixture"); - - const std::string legacyManifest = - "{\"version\":\"legacy\",\"executable\":\"bin/echoiond\"," - "\"core\":\"lib/Echoion.ts\",\"sha256\":{\"executable\":\"" + - std::string(kAbcSha256) + "\",\"core\":\"" + std::string(kAbcSha256) + - "\"}}"; - check(Void::FileSystem::atomic_write(manifestPath, legacyManifest) - .has_value(), - "failed to write legacy manifest"); - auto legacy = Echoion::Standalone::ReleaseManifest::load(manifestPath); - check(legacy.has_value(), "legacy release manifest was rejected"); - if (legacy) { - check(legacy->validate().has_value(), - "legacy release payload was rejected"); - check(!legacy->validateInstallLayout(), - "legacy manifest was accepted for full install validation"); - } - - return failures == 0 ? 0 : 1; -} diff --git a/EchoionStandalone/tests/test_runtime_paths.cpp b/EchoionStandalone/tests/test_runtime_paths.cpp deleted file mode 100644 index 7059d0a..0000000 --- a/EchoionStandalone/tests/test_runtime_paths.cpp +++ /dev/null @@ -1,152 +0,0 @@ -#include "echoion/standalone/RuntimePaths.hpp" - -#include -#include -#include -#include -#include - -namespace -{ - class TemporaryTree - { - public: - - TemporaryTree() - { - std::random_device random; - path_ = - std::filesystem::temp_directory_path() / - ("echoion-runtime-paths-" + - std::to_string(static_cast(random()))); - std::filesystem::create_directories(path_); - } - - ~TemporaryTree() - { - std::error_code error; - std::filesystem::remove_all(path_, error); - } - - TemporaryTree(const TemporaryTree&) = delete; - TemporaryTree& operator=(const TemporaryTree&) = delete; - - [[nodiscard]] const std::filesystem::path& path() const noexcept - { - return path_; - } - - private: - - std::filesystem::path path_; - }; - - bool writeFile(const std::filesystem::path& path) - { - std::filesystem::create_directories(path.parent_path()); - std::ofstream output(path); - output << "test\n"; - return output.good(); - } -} // namespace - -int main() -{ - int failures{}; - const auto check = [&failures](bool condition, const std::string& message) { - if (!condition) { - std::cerr << message << '\n'; - ++failures; - } - }; - - TemporaryTree tree; - const auto installRoot = tree.path() / "echoion"; - const auto executable = installRoot / "bin" / "echoiond"; - const auto executableDirectory = executable.parent_path(); - check(Echoion::Standalone::deriveInstallRoot(executable) == installRoot, - "bin/echoiond did not resolve to its installation root"); - check(Echoion::Standalone::deriveInstallRoot( - executable, tree.path() / "override") == tree.path() / "override", - "ECHOION_HOME-style override was not preferred"); - - const auto state = Echoion::Standalone::resolveStateDirectory( - tree.path() / "cli-state", tree.path() / "environment-state", - tree.path() / "xdg-state", tree.path() / "home", - tree.path() / "fallback"); - check(state == tree.path() / "cli-state", - "command-line state directory did not win precedence"); - check(Echoion::Standalone::resolveStateDirectory( - std::nullopt, tree.path() / "environment-state", - tree.path() / "xdg-state", tree.path() / "home", - tree.path() / "fallback") == tree.path() / "environment-state", - "environment state directory did not win precedence"); - check(Echoion::Standalone::resolveStateDirectory( - std::nullopt, std::nullopt, tree.path() / "xdg-state", - tree.path() / "home", tree.path() / "fallback") == - tree.path() / "xdg-state" / "echoion", - "XDG state directory fallback is incorrect"); - - const auto packagedCore = installRoot / "lib" / "Echoion.ts"; - check(writeFile(packagedCore), "failed to create packaged Core fixture"); - check(Echoion::Standalone::resolveCorePath( - installRoot, executableDirectory) == packagedCore, - "packaged Core was not resolved from install-root/lib"); - check(Echoion::Standalone::resolveCorePath( - installRoot, executableDirectory, - std::filesystem::path{"custom/Echoion.ts"}) == - installRoot / "custom" / "Echoion.ts", - "relative Core override was not anchored at the install root"); - - const auto packagedIndex = - installRoot / "share" / "echoion" / "web" / "index.html"; - check(writeFile(packagedIndex), "failed to create packaged web fixture"); - check(Echoion::Standalone::runtimeWorkingDirectory( - installRoot, executableDirectory) == installRoot, - "packaged web root did not select the installation root as working " - "directory"); - const auto bundledCertificates = - installRoot / "share" / "echoion" / "certs" / "ca-certificates.crt"; - check(!Echoion::Standalone::bundledCertificateBundle(installRoot), - "missing bundled certificate store was accepted"); - check(writeFile(bundledCertificates), - "failed to create bundled certificate store fixture"); - check(Echoion::Standalone::bundledCertificateBundle(installRoot) == - bundledCertificates, - "bundled certificate store was not resolved from the install root"); - std::filesystem::remove_all(installRoot / "share"); - const auto developmentIndex = executableDirectory / "web" / "index.html"; - check(writeFile(developmentIndex), - "failed to create development web fixture"); - check(Echoion::Standalone::runtimeWorkingDirectory( - installRoot, executableDirectory) == executableDirectory, - "development web root did not select the executable directory"); - - const auto avatarCache = tree.path() / "state" / "avatars"; - std::filesystem::create_directories(avatarCache); - check(Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache) == - avatarCache, - "empty avatar directory request did not select the state cache"); - check(Echoion::Standalone::resolveAvatarCacheDirectory( - avatarCache, "legacy") == avatarCache / "legacy", - "relative avatar directory was not rooted below state"); - check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache, - "../escape"), - "traversing avatar directory was accepted"); - check(!Echoion::Standalone::resolveAvatarCacheDirectory( - avatarCache, tree.path() / "outside"), - "absolute avatar directory outside state was accepted"); - const auto avatarEscape = avatarCache / "escape"; - std::error_code avatarError; - std::filesystem::create_symlink(tree.path(), avatarEscape, avatarError); - check(!avatarError, "failed to create avatar symlink escape fixture"); - check(!Echoion::Standalone::resolveAvatarCacheDirectory(avatarCache, - "escape/cache"), - "avatar directory escaped state through a symbolic link"); - - const auto runningExecutable = Echoion::Standalone::runningExecutablePath(); - check(runningExecutable.has_value() && - std::filesystem::is_regular_file(*runningExecutable), - "running executable could not be resolved through /proc/self/exe"); - return failures == 0 ? 0 : 1; -} diff --git a/EchoionStandalone/tests/test_stage_release.sh b/EchoionStandalone/tests/test_stage_release.sh deleted file mode 100755 index 3433bb4..0000000 --- a/EchoionStandalone/tests/test_stage_release.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -stage_script=$1 -updater=$2 -service_templates=$3 -generator=$(dirname -- "$stage_script")/generate-release-manifest.py -manifest_validator=$(dirname -- "$stage_script")/validate-release-manifest.py -root=$(mktemp -d) -trap 'rm -rf -- "$root"' EXIT - -bundle=$root/bundle -mkdir -p -- \ - "$bundle/bin" \ - "$bundle/lib" \ - "$bundle/service" \ - "$bundle/share/echoion/certs" \ - "$bundle/share/echoion/tools" \ - "$bundle/share/echoion/web" -printf '#!/bin/sh\necho "echoiond must not run during release staging" >&2\nexit 97\n' \ - > "$bundle/bin/echoiond" -chmod 0755 "$bundle/bin/echoiond" -install -m 0755 -- "$updater" "$bundle/bin/echoion-updater" -printf 'test core\n' > "$bundle/lib/Echoion.ts" -install -m 0644 -- \ - "$service_templates/echoion.service.in" \ - "$service_templates/echoion-updater.service.in" \ - "$service_templates/echoion-updater.timer.in" \ - "$bundle/service/" -printf '{"webRoot":"./web"}\n' > "$bundle/share/echoion/config.example.json" -printf 'test trust bundle\n' > "$bundle/share/echoion/certs/ca-certificates.crt" -install -m 0755 -- "$manifest_validator" \ - "$bundle/share/echoion/tools/validate-release-manifest.py" -printf '\n' > "$bundle/share/echoion/web/index.html" -ln -s -- Echoion.ts "$bundle/lib/libEchoionCore.so" - -python3 "$generator" --root "$bundle" --version 1.2.3 -python3 "$manifest_validator" --root "$bundle" --version 1.2.3 - -bash "$stage_script" "$root/releases" 1.2.3 "$bundle" - -manifest=$root/releases/pending-release.json -test -x "$root/releases/1.2.3/bin/echoiond" -test -x "$root/releases/1.2.3/bin/echoion-updater" -test -f "$root/releases/1.2.3/lib/Echoion.ts" -test -L "$root/releases/1.2.3/lib/libEchoionCore.so" -grep -q '"version": "1.2.3"' "$manifest" -grep -q '"executable": "1.2.3/bin/echoiond"' "$manifest" -grep -q '"updater": "1.2.3/bin/echoion-updater"' "$manifest" -grep -q '"path": "1.2.3/share/echoion/web/index.html"' "$manifest" -python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 - -printf 'tampered\n' >> "$root/releases/1.2.3/lib/Echoion.ts" -if python3 "$manifest_validator" --root "$root/releases/1.2.3" --version 1.2.3 \ - >/dev/null 2>&1; then - echo "tampered Core artifact was accepted" >&2 - exit 1 -fi - -if bash "$stage_script" "$root/releases" '../unsafe' "$bundle" \ - >/dev/null 2>&1; then - echo "unsafe version was accepted" >&2 - exit 1 -fi diff --git a/EchoionStandalone/tests/test_update_build_defaults.cpp b/EchoionStandalone/tests/test_update_build_defaults.cpp deleted file mode 100644 index 79aaaf7..0000000 --- a/EchoionStandalone/tests/test_update_build_defaults.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "echoion/standalone/UpdateBuildDefaults.hpp" - -#include -#include - -#ifndef ECHOION_EXPECTED_RUNTIME_VERSION -#error "ECHOION_EXPECTED_RUNTIME_VERSION must be defined by CMake" -#endif - -namespace -{ - bool check(bool condition, std::string_view message) - { - if (!condition) { - std::cerr << "FAILED: " << message << '\n'; - } - return condition; - } -} // namespace - -int main() -{ - namespace Defaults = Echoion::Standalone::UpdateBuildDefaults; - - bool passed = true; - passed &= - check(Defaults::RuntimeVersion == ECHOION_EXPECTED_RUNTIME_VERSION, - "generated runtime version does not match the configured release " - "version"); - passed &= - check(!Defaults::ApiVersion.empty(), "generated API version is empty"); - passed &= check(!Defaults::ToolchainAbi.empty(), - "generated toolchain ABI is empty"); - passed &= - check(Defaults::PublicKeysJson.size() >= 2 && - Defaults::PublicKeysJson.front() == '[' && - Defaults::PublicKeysJson.back() == ']', - "generated update public-key configuration is not a JSON array"); - - return passed ? 0 : 1; -} diff --git a/EchoionStandalone/tests/test_update_service.cpp b/EchoionStandalone/tests/test_update_service.cpp deleted file mode 100644 index 567ddc9..0000000 --- a/EchoionStandalone/tests/test_update_service.cpp +++ /dev/null @@ -1,761 +0,0 @@ -#include "echoion/standalone/UpdateService.hpp" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace -{ - class TemporaryTree - { - public: - - TemporaryTree() - { - std::random_device random; - path_ = - std::filesystem::temp_directory_path() / - ("echoion-update-service-" + - std::to_string(static_cast(random()))); - std::filesystem::create_directories(path_); - } - - ~TemporaryTree() - { - std::error_code error; - std::filesystem::remove_all(path_, error); - } - - TemporaryTree(const TemporaryTree&) = delete; - TemporaryTree& operator=(const TemporaryTree&) = delete; - - [[nodiscard]] const std::filesystem::path& path() const noexcept - { - return path_; - } - - private: - - std::filesystem::path path_; - }; - - bool writeFile(const std::filesystem::path& path, std::string_view contents) - { - std::filesystem::create_directories(path.parent_path()); - std::ofstream output(path, std::ios::binary); - output.write(contents.data(), - static_cast(contents.size())); - return output.good(); - } - - std::string readFile(const std::filesystem::path& path) - { - std::ifstream input(path, std::ios::binary); - return {std::istreambuf_iterator{input}, - std::istreambuf_iterator{}}; - } - - bool publishHistoricalVersion(const std::filesystem::path& root, - std::string_view versionText, - const std::filesystem::path& filename, - std::string_view contents) - { - const auto version = Void::Semver::parse_strict(versionText); - if (!version) { - return false; - } - Void::Update::VersionStore store(root); - if (auto initialized = store.initialize(); !initialized) { - return false; - } - auto staging = store.prepare(*version); - if (!staging || !writeFile(*staging / filename, contents)) { - return false; - } - if (auto published = store.publish(*version, *staging); !published) { - return false; - } - return store.recordHealthy(*version).has_value(); - } - - bool activatePublishedVersion(const std::filesystem::path& root, - std::string_view versionText) - { - const auto version = Void::Semver::parse_strict(versionText); - if (!version) { - return false; - } - Void::Update::VersionStore store(root); - if (auto initialized = store.initialize(); !initialized) { - return false; - } - if (auto activated = store.activate(*version); !activated) { - return false; - } - return store.commit().has_value(); - } - - std::string sha256(std::string_view contents) - { - auto digest = Void::Crypto::sha256(contents); - return digest ? Void::Encoding::Hex::encode(*digest) : std::string{}; - } - - std::string architecture() - { -#if defined(__x86_64__) || defined(_M_X64) - return "x86_64"; -#elif defined(__aarch64__) || defined(_M_ARM64) - return "aarch64"; -#elif defined(__i386__) || defined(_M_IX86) - return "x86"; -#else - return "unknown"; -#endif - } - - std::string configDocument(const std::filesystem::path& feed) - { - return R"json({"updates":{"enabled":false,"retainHealthyVersions":1,"sources":{"official":{"url":"file://)json" + - feed.string() + - R"json(","publicKeys":[],"allowUnsigned":true,"bearerTokenEnv":""}},"runtime":{"enabled":false,"source":"official","channel":"stable","autoApply":false},"core":{"enabled":true,"source":"official","channel":"stable","autoApply":false},"plugins":{"enabled":true,"source":"official","channel":"stable","autoApply":false,"managedOnly":true,"overrides":{}}}})json"; - } - - std::string release(std::string_view component, std::string_view artifactId, - std::string_view version, - const std::filesystem::path& artifact, - std::string_view contents) - { - return std::format( - R"json({{"component":"{}","artifactId":"{}","channel":"stable","version":"{}","cohort":"test","platform":"linux","arch":"{}","url":"file://{}","size":{},"sha256":"{}","packageType":"file","compatibility":{{"versionContracts":{{}},"exactContracts":{{}}}},"releaseManifestSha256":"0000000000000000000000000000000000000000000000000000000000000000"}})json", - component, artifactId, version, architecture(), artifact.string(), - contents.size(), sha256(contents)); - } - - std::string feedDocument(const std::filesystem::path& coreArtifact, - std::string_view coreContents, - const std::filesystem::path& pluginArtifact, - std::string_view pluginContents, - std::uint64_t sequence = 1) - { - return std::format( - R"json({{"schemaVersion":1,"feedId":"test","sequence":{},"generatedAt":"2026-01-01T00:00:00Z","expiresAt":"2099-01-01T00:00:00Z","releases":[{},{}]}})json", - sequence, - release("core", "", "2.0.0", coreArtifact, coreContents), - release("plugin", "fixture", "4.0.0", pluginArtifact, - pluginContents)); - } - - const Void::Json::Value* - parseResponse(const Echoion::Api::Result& response, - std::optional& storage) - { - if (!response) { - return nullptr; - } - auto parsed = Void::Json::parse(*response); - if (!parsed) { - return nullptr; - } - storage = std::move(*parsed); - return &*storage; - } - - std::string coreCandidateId(const Void::Json::Value& status) - { - const auto* components = status.find("components"); - const auto* core = components ? components->find("core") : nullptr; - const auto* candidate = core ? core->find("candidate") : nullptr; - const auto* id = candidate ? candidate->find("id") : nullptr; - return id && id->is_string() ? id->as_string() : std::string{}; - } - - std::string pluginCandidateId(const Void::Json::Value& status) - { - const auto* plugins = status.find("plugins"); - if (!plugins || !plugins->is_array()) { - return {}; - } - for (const auto& plugin : plugins->as_array()) { - if (plugin.get_str("id") != "fixture") { - continue; - } - const auto* candidate = plugin.find("candidate"); - const auto* id = candidate ? candidate->find("id") : nullptr; - return id && id->is_string() ? id->as_string() : std::string{}; - } - return {}; - } - - std::string componentRollbackVersion(const Void::Json::Value& status, - std::string_view componentId) - { - const auto* components = status.find("components"); - const auto* component = - components ? components->find(componentId) : nullptr; - return component ? component->get_str("rollbackVersion") - : std::string{}; - } - - std::string pluginRollbackVersion(const Void::Json::Value& status, - std::string_view pluginId) - { - const auto* plugins = status.find("plugins"); - if (!plugins || !plugins->is_array()) { - return {}; - } - for (const auto& plugin : plugins->as_array()) { - if (plugin.get_str("id") == pluginId) { - return plugin.get_str("rollbackVersion"); - } - } - return {}; - } - - std::string confirmationToken(Echoion::Standalone::UpdateService& service, - std::string_view component, - std::string_view pluginId, - std::string_view candidateId, - std::string_view version) - { - const auto request = std::format( - R"json({{"component":"{}","pluginId":"{}","candidateId":"{}","version":"{}","confirmation":"UNSIGNED {}"}})json", - component, pluginId, candidateId, version, version); - auto response = service.handle("updates.confirmUnsigned", request); - if (!response) { - return {}; - } - auto parsed = Void::Json::parse(*response); - return parsed ? parsed->get_str("confirmationToken") : std::string{}; - } -} // namespace - -int main() -{ - int failures{}; - const auto check = [&failures](bool condition, std::string_view message) { - if (!condition) { - std::cerr << message << '\n'; - ++failures; - } - }; - - TemporaryTree tree; - { - auto ownedService = - std::make_shared( - Echoion::Standalone::UpdateService::Options{}, - Echoion::Standalone::UpdateService::Hooks{}); - std::weak_ptr observedService = - ownedService; - auto handler = - Echoion::Standalone::bindUpdateService(ownedService); - ownedService.reset(); - check(!observedService.expired(), - "host control handler did not retain UpdateService"); - check(handler("updates.getStatus", "{}").has_value(), - "retained UpdateService handler could not serve status"); - handler = {}; - check(observedService.expired(), - "cleared host control handler retained UpdateService"); - } - - const auto startupState = tree.path() / "startup-state"; - const auto bundledStartupCore = - tree.path() / "startup-runtime" / "lib" / "Echoion.ts"; - check(writeFile(bundledStartupCore, "runtime-core"), - "failed to write startup Core fixture"); - const auto startupStore = startupState / "updates" / "components" / "core"; - check(publishHistoricalVersion(startupStore, "1.1.0", "Echoion.ts", - "stale-managed-core"), - "failed to publish stale managed Core fixture"); - check(activatePublishedVersion(startupStore, "1.1.0"), - "failed to activate stale managed Core fixture"); - - auto firstRuntimeSelection = - Echoion::Standalone::selectManagedCoreForStartup( - startupState, bundledStartupCore, std::string_view{"2.0.0"}); - check(firstRuntimeSelection.has_value(), - "runtime Core baseline selection failed"); - if (firstRuntimeSelection) { - check(firstRuntimeSelection->corePath == bundledStartupCore, - "new runtime did not prefer its bundled Core"); - check(firstRuntimeSelection->runtimeBaselineChanged, - "new runtime did not report a Core baseline change"); - check(firstRuntimeSelection->archivedStore.has_value() && - std::filesystem::is_regular_file( - *firstRuntimeSelection->archivedStore / "versions" / - "1.1.0" / "Echoion.ts"), - "stale managed Core store was not archived"); - } - - check(publishHistoricalVersion(startupStore, "1.1.0", "Echoion.ts", - "runtime-core"), - "failed to seed the new runtime Core store"); - check(activatePublishedVersion(startupStore, "1.1.0"), - "failed to activate the new runtime Core baseline"); - auto sameRuntimeSelection = - Echoion::Standalone::selectManagedCoreForStartup( - startupState, bundledStartupCore, std::string_view{"2.0.0"}); - check(sameRuntimeSelection.has_value() && - sameRuntimeSelection->corePath == - startupStore / "versions" / "1.1.0" / "Echoion.ts" && - !sameRuntimeSelection->runtimeBaselineChanged, - "same runtime did not retain its managed Core selection"); - - auto nextRuntimeSelection = - Echoion::Standalone::selectManagedCoreForStartup( - startupState, bundledStartupCore, std::string_view{"2.1.0"}); - check(nextRuntimeSelection.has_value() && - nextRuntimeSelection->corePath == bundledStartupCore && - nextRuntimeSelection->runtimeBaselineChanged, - "next runtime did not invalidate the prior managed Core baseline"); - - const auto state = tree.path() / "state"; - const auto incoming = tree.path() / "incoming"; - const auto currentCore = tree.path() / "installed" / "Echoion.ts"; - const auto currentPlugin = tree.path() / "installed" / "fixture.so"; - const auto installRoot = tree.path() / "runtime"; - const auto runningExecutable = installRoot / "bin" / "echoiond"; - const auto coreArtifact = incoming / "Echoion-2.0.0.ts"; - const auto pluginArtifact = incoming / "fixture-4.0.0.so"; - const auto feed = incoming / "feed.json"; - const auto config = tree.path() / "config.json"; - constexpr std::string_view oldCore = "old-core"; - constexpr std::string_view newCore = "new-core"; - constexpr std::string_view oldPlugin = "old-plugin"; - constexpr std::string_view newPlugin = "new-plugin"; - check(writeFile(currentCore, oldCore), "failed to write current Core"); - check(writeFile(currentPlugin, oldPlugin), - "failed to write current plugin"); - check(writeFile(coreArtifact, newCore), "failed to write Core artifact"); - check(writeFile(pluginArtifact, newPlugin), - "failed to write plugin artifact"); - check(writeFile(feed, - feedDocument(coreArtifact, newCore, pluginArtifact, - newPlugin, 9)), - "failed to write update feed"); - check(writeFile(config, configDocument(feed)), "failed to write config"); - check(publishHistoricalVersion(state / "updates" / "components" / "core", - "0.9.0", "Echoion.ts", "historical-core"), - "failed to seed a historical Core version"); - check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture", - "1.0.0", "fixture.so", "oldest-plugin"), - "failed to seed the oldest historical plugin version"); - check(publishHistoricalVersion(state / "plugins" / ".managed" / "fixture", - "2.0.0", "fixture.so", "historical-plugin"), - "failed to seed a historical plugin version"); - check(publishHistoricalVersion(installRoot, "0.8.0", "bin/echoiond", - "previous-runtime"), - "failed to seed a runtime rollback version"); - check(publishHistoricalVersion(installRoot, "0.9.0", "bin/not-echoiond", - "invalid-runtime-rollback"), - "failed to seed a runtime rollback decoy"); - check(publishHistoricalVersion(installRoot, "1.0.0", "bin/echoiond", - "current-runtime"), - "failed to seed the current runtime version"); - check(activatePublishedVersion(installRoot, "1.0.0"), - "failed to activate the current runtime version"); - - std::string coreVersion = "1.0.0"; - std::string pluginVersion = "3.0.0"; - std::filesystem::path activatedCore; - std::filesystem::path activatedPlugin; - int coreReplacements{}; - int pluginReplacements{}; - bool rejectCore{}; - Void::Update::VersionStore pluginStore(state / "plugins" / ".managed" / - "fixture"); - - const auto makeService = [&] { - return Echoion::Standalone::UpdateService( - Echoion::Standalone::UpdateService::Options{ - .configPath = config, - .stateDirectory = state, - .installRoot = installRoot, - .runningExecutable = runningExecutable, - .currentCore = currentCore, - .releaseManifestPath = {}, - .officialFeedUrl = {}, - .officialPublicKeysJson = "[]", - .runtimeVersion = "1.0.0", - .apiVersion = "1.1.0", - .toolchainAbi = "test", - .incomingDirectory = incoming}, - Echoion::Standalone::UpdateService::Hooks{ - .replaceCore = [&](const std::filesystem::path& path) - -> Echoion::Api::Result { - ++coreReplacements; - if (rejectCore) { - return Echoion::Api::fail( - Echoion::Api::ErrorCode::PluginError, - "rejected by test"); - } - activatedCore = path; - coreVersion = path.parent_path().filename().string(); - return {}; - }, - .managePlugins = [&](const std::string& request) - -> Echoion::Api::Result { - auto parsed = Void::Json::parse(request); - if (!parsed) { - return Echoion::Api::fail( - Echoion::Api::ErrorCode::ParseError, - "invalid test request"); - } - if (parsed->get_str("action") == "status") { - return std::format( - R"json({{"plugins":[{{"id":"fixture","name":"Fixture","version":"{}","path":"{}","managed":true}}]}})json", - pluginVersion, currentPlugin.string()); - } - if (parsed->get_str("action") != "replace") { - return Echoion::Api::fail( - Echoion::Api::ErrorCode::InvalidArgument, - "unexpected test plugin action"); - } - ++pluginReplacements; - activatedPlugin = parsed->get_str("path"); - pluginVersion = parsed->get_str("version"); - return "{}"; - }, - .manageRuntime = {}, - .playbackActive = [] { return false; }, - .coreVersion = [&] { return coreVersion; }}); - }; - auto service = makeService(); - check(service.start().has_value(), "UpdateService did not start"); - check(!std::filesystem::exists( - pluginStore.versionPath(*Void::Semver::parse("1.0.0"))), - "managed plugin startup retention did not prune the oldest version"); - - auto checked = service.handle("updates.check", "{}"); - std::optional checkedJson; - const auto* checkedStatus = parseResponse(checked, checkedJson); - check(checkedStatus != nullptr, "manual update check failed"); - const auto coreId = checkedStatus ? coreCandidateId(*checkedStatus) : ""; - const auto pluginId = - checkedStatus ? pluginCandidateId(*checkedStatus) : ""; - if ((coreId.empty() || pluginId.empty()) && checked) { - std::cerr << "update check response: " << *checked << '\n'; - } - check(!coreId.empty(), "Core candidate was not selected"); - check(!pluginId.empty(), "plugin candidate was not selected"); - check(checkedStatus && !checkedStatus->get_bool("checking", true), - "completed manual check was returned as still running"); - auto repeatedCheck = service.handle("updates.check", "{}"); - std::optional repeatedJson; - const auto* repeatedStatus = parseResponse(repeatedCheck, repeatedJson); - check(repeatedStatus && coreCandidateId(*repeatedStatus) == coreId && - pluginCandidateId(*repeatedStatus) == pluginId, - "an unchanged feed sequence was incorrectly treated as a replay"); - const auto replacementFeed = incoming / "replacement-feed.json"; - check(writeFile( - replacementFeed, - feedDocument(coreArtifact, newCore, pluginArtifact, newPlugin)), - "failed to write replacement update feed"); - auto replacementConfig = Void::Json::parse(configDocument(replacementFeed)); - const auto* replacementUpdates = - replacementConfig ? replacementConfig->find("updates") : nullptr; - check(replacementUpdates != nullptr, - "failed to construct replacement updater configuration"); - bool replacementSaved = false; - if (replacementUpdates) { - replacementSaved = - service - .handle("updates.setConfig", - std::format(R"({{"config":{}}})", - Void::Json::serialize(*replacementUpdates))) - .has_value(); - } - check(replacementSaved, "custom source URL could not be saved"); - auto replacementCheck = service.handle("updates.check", "{}"); - std::optional replacementJson; - const auto* replacementStatus = - parseResponse(replacementCheck, replacementJson); - check(replacementStatus && coreCandidateId(*replacementStatus) == coreId && - pluginCandidateId(*replacementStatus) == pluginId, - "changing a custom source URL inherited the old feed replay floor"); - - const auto rejectedCoreToken = - confirmationToken(service, "core", "", coreId, "2.0.0"); - check(!rejectedCoreToken.empty(), "Core unsigned confirmation failed"); - rejectCore = true; - auto rejectedCoreApply = service.handle( - "updates.apply", - std::format( - R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json", - coreId, rejectedCoreToken)); - check(rejectedCoreApply.has_value(), "failing Core apply did not queue"); - service.processPendingHostActions(); - check(coreReplacements == 1, - "failing queued Core replacement did not run exactly once"); - auto replayedCoreApply = service.handle( - "updates.apply", - std::format( - R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json", - coreId, rejectedCoreToken)); - check(!replayedCoreApply.has_value(), - "failed unsigned Core apply reused a consumed confirmation token"); - - const auto coreToken = - confirmationToken(service, "core", "", coreId, "2.0.0"); - check(!coreToken.empty(), "fresh Core unsigned confirmation failed"); - rejectCore = false; - auto coreApply = service.handle( - "updates.apply", - std::format( - R"json({{"component":"core","candidateId":"{}","version":"2.0.0","confirmationToken":"{}"}})json", - coreId, coreToken)); - check(coreApply.has_value(), "Core apply did not queue"); - check(coreReplacements == 1, - "Core was replaced synchronously on the RPC call stack"); - service.processPendingHostActions(); - check(coreReplacements == 2, "queued Core replacement did not run"); - check(readFile(activatedCore) == newCore, - "queued Core replacement used the wrong artifact"); - - Void::Update::VersionStore coreStore(state / "updates" / "components" / - "core"); - auto activeCoreVersion = coreStore.currentVersion(); - check(activeCoreVersion && activeCoreVersion->has_value() && - (*activeCoreVersion)->to_string() == "2.0.0", - "Core activation was not committed"); - check(readFile(coreStore.versionPath(*Void::Semver::parse("1.0.0")) / - "Echoion.ts") == oldCore, - "initial Core was not seeded for rollback"); - check(!std::filesystem::exists( - coreStore.versionPath(*Void::Semver::parse("0.9.0"))), - "Core retention did not remove an excess healthy version"); - - const auto pluginToken = - confirmationToken(service, "plugins", "fixture", pluginId, "4.0.0"); - check(!pluginToken.empty(), "plugin unsigned confirmation failed"); - auto pluginApply = service.handle( - "updates.apply", - std::format( - R"json({{"component":"plugins","pluginId":"fixture","candidateId":"{}","version":"4.0.0","confirmationToken":"{}"}})json", - pluginId, pluginToken)); - check(pluginApply.has_value(), "plugin apply failed"); - check(pluginReplacements == 1 && readFile(activatedPlugin) == newPlugin, - "plugin replacement used the wrong artifact"); - check(readFile(pluginStore.versionPath(*Void::Semver::parse("3.0.0")) / - "fixture.so") == oldPlugin, - "initial plugin was not seeded for rollback"); - check(!std::filesystem::exists( - pluginStore.versionPath(*Void::Semver::parse("2.0.0"))), - "plugin retention did not remove an excess healthy version"); - auto unsafePluginRollback = service.handle( - "updates.rollback", - R"({"component":"plugins","pluginId":"../escape","version":"3.0.0"})"); - check(!unsafePluginRollback.has_value(), - "plugin rollback accepted a path-traversal plugin id"); - auto pluginRollback = service.handle( - "updates.rollback", - R"({"component":"plugins","pluginId":"fixture","version":"3.0.0"})"); - check(pluginRollback.has_value() && pluginReplacements == 2 && - readFile(activatedPlugin) == oldPlugin, - "plugin rollback did not restore the seeded version"); - - auto unadvertisedRollback = service.handle( - "updates.rollback", R"({"component":"core","version":"2.0.0"})"); - check(!unadvertisedRollback.has_value(), - "Core rollback accepted a version that was not advertised healthy"); - auto rollback = service.handle("updates.rollback", - R"({"component":"core","version":"1.0.0"})"); - check(rollback.has_value(), "Core rollback did not queue"); - check(coreReplacements == 2, - "Core rollback ran synchronously on the RPC call stack"); - service.processPendingHostActions(); - check(coreReplacements == 3 && readFile(activatedCore) == oldCore, - "queued Core rollback did not restore the seed"); - - rejectCore = true; - auto failedRollback = service.handle( - "updates.rollback", R"({"component":"core","version":"2.0.0"})"); - check(failedRollback.has_value(), "failing Core rollback did not queue"); - service.processPendingHostActions(); - activeCoreVersion = coreStore.currentVersion(); - check(coreReplacements == 4 && activeCoreVersion && - activeCoreVersion->has_value() && - (*activeCoreVersion)->to_string() == "1.0.0", - "failed Core replacement did not roll back the VersionStore"); - auto finalStatus = service.handle("updates.getStatus", "{}"); - check(finalStatus && finalStatus->contains("rejected by test"), - "failed deferred activation was not reported in status/history"); - const auto plugin4 = *Void::Semver::parse("4.0.0"); - check(pluginStore.activate(plugin4).has_value(), - "could not stage an interrupted plugin activation"); - check(Echoion::Standalone::reconcileManagedPluginUpdates(state).has_value(), - "managed plugin startup reconciliation failed"); - auto recoveredPluginVersion = pluginStore.currentVersion(); - check(recoveredPluginVersion && recoveredPluginVersion->has_value() && - (*recoveredPluginVersion)->to_string() == "3.0.0", - "startup reconciliation did not roll back the interrupted plugin"); - const auto sequenceState = state / "updates" / "sequences.json"; - std::filesystem::remove(sequenceState); - std::filesystem::create_directory(sequenceState); - check(!service.handle("updates.check", "{}").has_value(), - "update check ignored a replay-floor persistence failure"); - std::filesystem::remove(sequenceState); - - service.stop(); - auto restarted = makeService(); - check(restarted.start().has_value(), - "restarted UpdateService did not start"); - auto restartedStatusResponse = restarted.handle("updates.getStatus", "{}"); - std::optional restartedStatusJson; - const auto* restartedStatus = - parseResponse(restartedStatusResponse, restartedStatusJson); - check(restartedStatus != nullptr, - "restarted UpdateService did not return status"); - check(restartedStatus && - componentRollbackVersion(*restartedStatus, "runtime") == "0.8.0", - "runtime rollback metadata was not reconstructed or accepted an " - "invalid payload"); - check(restartedStatus && - componentRollbackVersion(*restartedStatus, "core") == "2.0.0", - "Core rollback metadata was not reconstructed after restart"); - check(restartedStatus && - pluginRollbackVersion(*restartedStatus, "fixture") == "4.0.0", - "plugin rollback metadata was not reconstructed after restart"); - check(readFile(coreStore.versionPath(*Void::Semver::parse("2.0.0")) / - "Echoion.ts") == newCore, - "retained Core rollback payload was unavailable after restart"); - check(readFile(pluginStore.versionPath(*Void::Semver::parse("4.0.0")) / - "fixture.so") == newPlugin, - "retained plugin rollback payload was unavailable after restart"); - Void::Update::VersionStore runtimeStore(installRoot); - check(readFile(runtimeStore.versionPath(*Void::Semver::parse("0.8.0")) / - "bin" / "echoiond") == "previous-runtime", - "retained runtime rollback payload was unavailable after restart"); - restarted.stop(); - check(writeFile(sequenceState, "{not-json"), - "failed to write corrupt replay-floor fixture"); - auto corruptReplayState = makeService(); - const auto corruptReplayStart = corruptReplayState.start(); - check( - !corruptReplayStart && - corruptReplayStart.error().message.contains("replay-floor"), - "corrupt replay-floor state silently disabled anti-replay persistence"); - std::filesystem::remove(sequenceState); - -#ifndef _WIN32 - const auto runtimeLock = installRoot / ".update.lock"; - const auto runtimeHealth = installRoot / "health.log"; - std::filesystem::permissions(runtimeLock, std::filesystem::perms::none, - std::filesystem::perm_options::replace); - std::filesystem::permissions(runtimeHealth, std::filesystem::perms::none, - std::filesystem::perm_options::replace); - std::ifstream unreadableProbe{runtimeLock, std::ios::binary}; - if (!unreadableProbe) { - auto legacy = makeService(); - check(legacy.start().has_value(), - "unreadable legacy runtime metadata disabled UpdateService"); - auto legacyStatusResponse = legacy.handle("updates.getStatus", "{}"); - std::optional legacyStatusJson; - const auto* legacyStatus = - parseResponse(legacyStatusResponse, legacyStatusJson); - check(legacyStatus && - componentRollbackVersion(*legacyStatus, "runtime").empty(), - "unreadable legacy metadata exposed a runtime rollback"); - legacy.stop(); - } - const auto readableMetadata = std::filesystem::perms::owner_read | - std::filesystem::perms::owner_write | - std::filesystem::perms::group_read | - std::filesystem::perms::others_read; - std::filesystem::permissions(runtimeLock, readableMetadata, - std::filesystem::perm_options::replace); - std::filesystem::permissions(runtimeHealth, readableMetadata, - std::filesystem::perm_options::replace); -#endif - - TemporaryTree freshTree; - const auto freshState = freshTree.path() / "state"; - const auto freshIncoming = freshTree.path() / "incoming"; - const auto freshFeed = freshIncoming / "feed.json"; - const auto freshConfig = freshTree.path() / "config.json"; - const auto freshCore = freshTree.path() / "installed" / "Echoion.ts"; - const auto freshInstall = freshTree.path() / "runtime"; - check(writeFile(freshFeed, "{}"), - "failed to write fresh-install feed fixture"); - check(writeFile(freshConfig, configDocument(freshFeed)), - "failed to write fresh-install config fixture"); - check(writeFile(freshCore, oldCore), - "failed to write fresh-install Core fixture"); - check(writeFile(freshInstall / "versions" / "1.0.0" / "bin" / "echoiond", - "fresh-runtime"), - "failed to write fresh-install runtime fixture"); - std::filesystem::create_directory_symlink( - std::filesystem::path{"versions"} / "1.0.0", freshInstall / "current"); - Echoion::Standalone::UpdateService freshService( - Echoion::Standalone::UpdateService::Options{ - .configPath = freshConfig, - .stateDirectory = freshState, - .installRoot = freshInstall, - .runningExecutable = freshInstall / "bin" / "echoiond", - .currentCore = freshCore, - .releaseManifestPath = {}, - .officialFeedUrl = {}, - .officialPublicKeysJson = "[]", - .runtimeVersion = "1.0.0", - .apiVersion = "1.1.0", - .toolchainAbi = "test", - .incomingDirectory = freshIncoming}, - Echoion::Standalone::UpdateService::Hooks{}); - check(freshService.start().has_value(), - "fresh install without VersionStore metadata did not start"); - auto freshStatusResponse = freshService.handle("updates.getStatus", "{}"); - std::optional freshStatusJson; - const auto* freshStatus = - parseResponse(freshStatusResponse, freshStatusJson); - check(freshStatus && - componentRollbackVersion(*freshStatus, "runtime").empty(), - "fresh install synthesized runtime rollback metadata"); - freshService.stop(); - - TemporaryTree blockedTree; - const auto blockedState = blockedTree.path() / "state"; - const auto blockedIncoming = blockedTree.path() / "incoming"; - const auto blockedFeed = blockedIncoming / "feed.json"; - const auto blockedConfig = blockedTree.path() / "config.json"; - const auto blockedCore = blockedTree.path() / "installed" / "Echoion.ts"; - check(writeFile(blockedFeed, "{}"), - "failed to write blocked-start feed fixture"); - check(writeFile(blockedConfig, configDocument(blockedFeed)), - "failed to write blocked-start config fixture"); - check(writeFile(blockedCore, oldCore), - "failed to write blocked-start Core fixture"); - check(writeFile(blockedState / "updates" / "downloads", "not-a-directory"), - "failed to create blocked updater directory fixture"); - Echoion::Standalone::UpdateService blockedService( - Echoion::Standalone::UpdateService::Options{ - .configPath = blockedConfig, - .stateDirectory = blockedState, - .installRoot = blockedTree.path() / "runtime", - .runningExecutable = - blockedTree.path() / "runtime" / "bin" / "echoiond", - .currentCore = blockedCore, - .releaseManifestPath = {}, - .officialFeedUrl = {}, - .officialPublicKeysJson = "[]", - .runtimeVersion = "1.0.0", - .apiVersion = "1.1.0", - .toolchainAbi = "test", - .incomingDirectory = blockedIncoming}, - Echoion::Standalone::UpdateService::Hooks{}); - const auto blockedStart = blockedService.start(); - check(!blockedStart && blockedStart.error().message.contains("downloads"), - "startup masked an earlier updater directory creation failure"); - blockedService.stop(); - return failures == 0 ? 0 : 1; -} diff --git a/EchoionWeb/CMakeLists.txt b/EchoionWeb/CMakeLists.txt deleted file mode 100644 index 8b67af3..0000000 --- a/EchoionWeb/CMakeLists.txt +++ /dev/null @@ -1,131 +0,0 @@ -cmake_minimum_required(VERSION 4.0.0) -if(NOT DEFINED ECHOION_PRODUCT_VERSION) - set(ECHOION_PRODUCT_VERSION 0.0.0) -endif() -project(EchoionWeb VERSION "${ECHOION_PRODUCT_VERSION}" LANGUAGES CXX) -set(CMAKE_CXX_STANDARD 26) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) -set(CMAKE_POSITION_INDEPENDENT_CODE ON) - -file(GLOB_RECURSE WEB_SOURCES CONFIGURE_DEPENDS "src/**.cpp") -add_library(EchoionWeb STATIC ${WEB_SOURCES}) -add_library(Echoion::Web ALIAS EchoionWeb) - -target_include_directories(EchoionWeb PUBLIC - $ - $ -) - -# EchoionCore is configured before this module and creates the header-only -# Boost:: targets from the single system Boost. Fall back to discovering them -# only if this module is ever built without Core. Check each target because -# aliases created by a sibling directory are not necessarily visible here. -find_package(Boost 1.87 CONFIG QUIET COMPONENTS system url) -foreach(_hdr asio beast system) - if(NOT TARGET Boost::${_hdr}) - add_library(_web_boost_${_hdr}_hdr INTERFACE) - add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr) - target_include_directories(_web_boost_${_hdr}_hdr INTERFACE - "${Boost_INCLUDE_DIRS}") - endif() -endforeach() - -find_package(Threads REQUIRED) - -target_link_libraries(EchoionWeb - PUBLIC - Echoion::ApiConfig - Void::Data - Void::Log - Void::Async - PRIVATE - Threads::Threads - Boost::beast - Boost::asio - Boost::system - Boost::url -) - -if(MSVC) - target_compile_options(EchoionWeb PRIVATE /W4 /WX-) -else() - target_compile_options(EchoionWeb PRIVATE -Wall -Wextra -Wpedantic) -endif() - -# ── Browser frontend (Vite + React + TypeScript) ───────────────────────────── -# The UI lives in frontend/ and is built with npm/vite into frontend/web-dist. -# That build output is what ships next to the runtime binary (default webRoot -# "./web", relative to the working directory) and is installed. Opt out with -# -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job). -if(BUILD_TESTS) - add_executable(echoion_web_security_tests - tests/HttpSecurityTests.cpp) - target_link_libraries(echoion_web_security_tests PRIVATE - EchoionWeb - Threads::Threads) - add_test(NAME echoion_web_security_tests - COMMAND echoion_web_security_tests) -endif() - -option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON) - -set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend") -set(_web_dist "${_web_frontend}/web-dist") - -if(ECHOION_BUILD_WEB) - find_program(NPM_EXECUTABLE NAMES npm npm.cmd) - if(NOT NPM_EXECUTABLE) - message(FATAL_ERROR - "npm was not found but ECHOION_BUILD_WEB is ON. Install Node.js/npm, " - "or configure with -DECHOION_BUILD_WEB=OFF to skip the web frontend.") - endif() - - # Rebuild web-dist whenever any source/config under frontend/ (excluding - # node_modules and the output dir) changes. CONFIGURE_DEPENDS re-globs at - # build time so new files are picked up without re-running CMake. - file(GLOB_RECURSE _web_tree_srcs CONFIGURE_DEPENDS - LIST_DIRECTORIES FALSE - "${_web_frontend}/src/*" - "${_web_frontend}/public/*") - set(_web_srcs - ${_web_tree_srcs} - "${_web_frontend}/index.html" - "${_web_frontend}/package.json" - "${_web_frontend}/package-lock.json" - "${_web_frontend}/tsconfig.json" - "${_web_frontend}/vite.config.ts") - - add_custom_command( - OUTPUT "${_web_dist}/index.html" - # Release builds run `npm ci` before CMake. This lockfile-aware fallback - # keeps direct developer builds convenient without reinstalling on every - # incremental build. - COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit --no-fund - COMMAND ${NPM_EXECUTABLE} run build - WORKING_DIRECTORY "${_web_frontend}" - DEPENDS ${_web_srcs} - COMMENT "Building Echoion web frontend (vite)" - VERBATIM) - add_custom_target(EchoionWebFrontend ALL - DEPENDS "${_web_dist}/index.html") - add_dependencies(EchoionWeb EchoionWebFrontend) - - set(_web_assets "${_web_dist}") -else() - # Frontend build skipped: ship whatever is already in web-dist (a prior - # build or a committed snapshot). Falls back to nothing if absent. - set(_web_assets "${_web_dist}") -endif() - -# Ship the built browser assets next to the runtime binary. Remove the target -# first so stale files (e.g. an earlier vanilla-JS build) never linger. -add_custom_command(TARGET EchoionWeb POST_BUILD - COMMAND ${CMAKE_COMMAND} -E rm -rf "${CMAKE_BINARY_DIR}/bin/web" - COMMAND ${CMAKE_COMMAND} -E copy_directory - "${_web_assets}" - "${CMAKE_BINARY_DIR}/bin/web" - COMMENT "Copying EchoionWeb static assets to bin/web" -) - -install(DIRECTORY "${_web_dist}/" DESTINATION share/echoion/web) diff --git a/EchoionWeb/frontend/.gitignore b/EchoionWeb/frontend/.gitignore deleted file mode 100644 index 3c21059..0000000 --- a/EchoionWeb/frontend/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules/ -web-dist/ -*.tsbuildinfo diff --git a/EchoionWeb/frontend/index.html b/EchoionWeb/frontend/index.html deleted file mode 100644 index 7031cd4..0000000 --- a/EchoionWeb/frontend/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - -Echoion — Music Bot - - - - - - - - - -
- - - diff --git a/EchoionWeb/frontend/package-lock.json b/EchoionWeb/frontend/package-lock.json deleted file mode 100644 index b234a9a..0000000 --- a/EchoionWeb/frontend/package-lock.json +++ /dev/null @@ -1,2281 +0,0 @@ -{ - "name": "echoion-web", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "echoion-web", - "version": "1.0.0", - "dependencies": { - "react": "^19.1.0", - "react-dom": "^19.1.0" - }, - "devDependencies": { - "@types/react": "^19.1.0", - "@types/react-dom": "^19.1.0", - "@types/youtube": "^0.1.2", - "@vitejs/plugin-react": "^4.5.0", - "typescript": "^5.8.0", - "vite": "^6.3.0", - "vitest": "^3.1.0" - } - }, - "node_modules/@babel/code-frame": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", - "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.29.7", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", - "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", - "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helpers": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7", - "@jridgewell/remapping": "^2.3.5", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/generator": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", - "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.7", - "@babel/types": "^7.29.7", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", - "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/compat-data": "^7.29.7", - "@babel/helper-validator-option": "^7.29.7", - "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-globals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", - "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", - "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", - "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7", - "@babel/traverse": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", - "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", - "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", - "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", - "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", - "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.7" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-transform-react-jsx-self": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", - "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-react-jsx-source": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", - "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/template": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", - "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz", - "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-globals": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.7", - "debug": "^4.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", - "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", - "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", - "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", - "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", - "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", - "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", - "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", - "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", - "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", - "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", - "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", - "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", - "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", - "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", - "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", - "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", - "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", - "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", - "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", - "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", - "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", - "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", - "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", - "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", - "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", - "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", - "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-beta.27", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", - "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz", - "integrity": "sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.2.tgz", - "integrity": "sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.2.tgz", - "integrity": "sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.2.tgz", - "integrity": "sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.2.tgz", - "integrity": "sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.2.tgz", - "integrity": "sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.2.tgz", - "integrity": "sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.2.tgz", - "integrity": "sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.2.tgz", - "integrity": "sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.2.tgz", - "integrity": "sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.2.tgz", - "integrity": "sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.2.tgz", - "integrity": "sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.2.tgz", - "integrity": "sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.2.tgz", - "integrity": "sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.2.tgz", - "integrity": "sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.2.tgz", - "integrity": "sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.2.tgz", - "integrity": "sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.2.tgz", - "integrity": "sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.2.tgz", - "integrity": "sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.2.tgz", - "integrity": "sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ] - }, - "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.2.tgz", - "integrity": "sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.2.tgz", - "integrity": "sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.2.tgz", - "integrity": "sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.2.tgz", - "integrity": "sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.2.tgz", - "integrity": "sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@types/babel__core": { - "version": "7.20.5", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", - "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "node_modules/@types/babel__generator": { - "version": "7.27.0", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", - "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__template": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", - "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__traverse": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", - "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.28.2" - } - }, - "node_modules/@types/chai": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", - "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/deep-eql": "*", - "assertion-error": "^2.0.1" - } - }, - "node_modules/@types/deep-eql": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", - "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/react": { - "version": "19.2.17", - "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz", - "integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==", - "dev": true, - "license": "MIT", - "dependencies": { - "csstype": "^3.2.2" - } - }, - "node_modules/@types/react-dom": { - "version": "19.2.3", - "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", - "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "@types/react": "^19.2.0" - } - }, - "node_modules/@types/youtube": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/@types/youtube/-/youtube-0.1.2.tgz", - "integrity": "sha512-n1/KqusanheyQRWHamNZv8K3kydlRqyEsZEKxMTeNWXQTC15lZprITCUt+WgL1vAIvKHCjPBIWz/gf/KQLsB3g==", - "dev": true, - "license": "MIT" - }, - "node_modules/@vitejs/plugin-react": { - "version": "4.7.0", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", - "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.28.0", - "@babel/plugin-transform-react-jsx-self": "^7.27.1", - "@babel/plugin-transform-react-jsx-source": "^7.27.1", - "@rolldown/pluginutils": "1.0.0-beta.27", - "@types/babel__core": "^7.20.5", - "react-refresh": "^0.17.0" - }, - "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "peerDependencies": { - "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" - } - }, - "node_modules/@vitest/expect": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz", - "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/chai": "^5.2.2", - "@vitest/spy": "3.2.7", - "@vitest/utils": "3.2.7", - "chai": "^5.2.0", - "tinyrainbow": "^2.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/mocker": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz", - "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/spy": "3.2.7", - "estree-walker": "^3.0.3", - "magic-string": "^0.30.17" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "msw": "^2.4.9", - "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" - }, - "peerDependenciesMeta": { - "msw": { - "optional": true - }, - "vite": { - "optional": true - } - } - }, - "node_modules/@vitest/pretty-format": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", - "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "tinyrainbow": "^2.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/runner": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz", - "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/utils": "3.2.7", - "pathe": "^2.0.3", - "strip-literal": "^3.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/snapshot": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz", - "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "3.2.7", - "magic-string": "^0.30.17", - "pathe": "^2.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/spy": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz", - "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "tinyspy": "^4.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/utils": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz", - "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "3.2.7", - "loupe": "^3.1.4", - "tinyrainbow": "^2.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/assertion-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", - "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/baseline-browser-mapping": { - "version": "2.10.42", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.42.tgz", - "integrity": "sha512-c/jurFrDLyui7o1J86yLkRu4LMsTYcBohveus7/I2Hzdn9KIP2bdJPTue/lR1KH46enoPbD77GKeSYNdyPoD3Q==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "baseline-browser-mapping": "dist/cli.cjs" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/browserslist": { - "version": "4.28.5", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.5.tgz", - "integrity": "sha512-Cu2E6QejHWzuDMTkuwgpABFgDfZrXLQq5V13YOACZx4mFAG4IwGTbTfHPMr4WtxlHoXSM8FIuRwYYCz5XiabaQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "baseline-browser-mapping": "^2.10.42", - "caniuse-lite": "^1.0.30001800", - "electron-to-chromium": "^1.5.387", - "node-releases": "^2.0.50", - "update-browserslist-db": "^1.2.3" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/cac": { - "version": "6.7.14", - "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", - "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001803", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001803.tgz", - "integrity": "sha512-g/uHREV2ZpK9qMalCsWaxmA6ol+DX8GYhuf3T40RKoP+oL7vhRJh8LNt73PCjpnR6l14FzfPrB5Yux4PKm2meg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/chai": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", - "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", - "dev": true, - "license": "MIT", - "dependencies": { - "assertion-error": "^2.0.1", - "check-error": "^2.1.1", - "deep-eql": "^5.0.1", - "loupe": "^3.1.0", - "pathval": "^2.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/check-error": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", - "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 16" - } - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/csstype": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", - "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", - "dev": true, - "license": "MIT" - }, - "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": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/deep-eql": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", - "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/electron-to-chromium": { - "version": "1.5.389", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.389.tgz", - "integrity": "sha512-cEto7aeOqBfU1D+c5py5pE+ooscKE75JifxLBdFUZsqAxRS6y7kebtxAZvICszSl05gPjYHDTjY+lXpyGvpJbg==", - "dev": true, - "license": "ISC" - }, - "node_modules/es-module-lexer": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", - "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", - "dev": true, - "license": "MIT" - }, - "node_modules/esbuild": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", - "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.25.12", - "@esbuild/android-arm": "0.25.12", - "@esbuild/android-arm64": "0.25.12", - "@esbuild/android-x64": "0.25.12", - "@esbuild/darwin-arm64": "0.25.12", - "@esbuild/darwin-x64": "0.25.12", - "@esbuild/freebsd-arm64": "0.25.12", - "@esbuild/freebsd-x64": "0.25.12", - "@esbuild/linux-arm": "0.25.12", - "@esbuild/linux-arm64": "0.25.12", - "@esbuild/linux-ia32": "0.25.12", - "@esbuild/linux-loong64": "0.25.12", - "@esbuild/linux-mips64el": "0.25.12", - "@esbuild/linux-ppc64": "0.25.12", - "@esbuild/linux-riscv64": "0.25.12", - "@esbuild/linux-s390x": "0.25.12", - "@esbuild/linux-x64": "0.25.12", - "@esbuild/netbsd-arm64": "0.25.12", - "@esbuild/netbsd-x64": "0.25.12", - "@esbuild/openbsd-arm64": "0.25.12", - "@esbuild/openbsd-x64": "0.25.12", - "@esbuild/openharmony-arm64": "0.25.12", - "@esbuild/sunos-x64": "0.25.12", - "@esbuild/win32-arm64": "0.25.12", - "@esbuild/win32-ia32": "0.25.12", - "@esbuild/win32-x64": "0.25.12" - } - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/estree-walker": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", - "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0" - } - }, - "node_modules/expect-type": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", - "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.0.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/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", - "dev": true, - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/loupe": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", - "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "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/nanoid": { - "version": "3.3.15", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz", - "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/node-releases": { - "version": "2.0.50", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.50.tgz", - "integrity": "sha512-J6l92tKHX6w8Jy5nO1Vuc01NoIiRGi/d6qBKVxh+IQ8Cr3b6HbVNfKiF8ZpFKufTwpwxMmce2W3iQZ861ZRyTg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/pathe": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", - "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", - "dev": true, - "license": "MIT" - }, - "node_modules/pathval": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", - "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14.16" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", - "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/postcss": { - "version": "8.5.16", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz", - "integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.12", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/react": { - "version": "19.2.7", - "resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz", - "integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "19.2.7", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz", - "integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==", - "license": "MIT", - "dependencies": { - "scheduler": "^0.27.0" - }, - "peerDependencies": { - "react": "^19.2.7" - } - }, - "node_modules/react-refresh": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", - "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/rollup": { - "version": "4.62.2", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz", - "integrity": "sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.9" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.62.2", - "@rollup/rollup-android-arm64": "4.62.2", - "@rollup/rollup-darwin-arm64": "4.62.2", - "@rollup/rollup-darwin-x64": "4.62.2", - "@rollup/rollup-freebsd-arm64": "4.62.2", - "@rollup/rollup-freebsd-x64": "4.62.2", - "@rollup/rollup-linux-arm-gnueabihf": "4.62.2", - "@rollup/rollup-linux-arm-musleabihf": "4.62.2", - "@rollup/rollup-linux-arm64-gnu": "4.62.2", - "@rollup/rollup-linux-arm64-musl": "4.62.2", - "@rollup/rollup-linux-loong64-gnu": "4.62.2", - "@rollup/rollup-linux-loong64-musl": "4.62.2", - "@rollup/rollup-linux-ppc64-gnu": "4.62.2", - "@rollup/rollup-linux-ppc64-musl": "4.62.2", - "@rollup/rollup-linux-riscv64-gnu": "4.62.2", - "@rollup/rollup-linux-riscv64-musl": "4.62.2", - "@rollup/rollup-linux-s390x-gnu": "4.62.2", - "@rollup/rollup-linux-x64-gnu": "4.62.2", - "@rollup/rollup-linux-x64-musl": "4.62.2", - "@rollup/rollup-openbsd-x64": "4.62.2", - "@rollup/rollup-openharmony-arm64": "4.62.2", - "@rollup/rollup-win32-arm64-msvc": "4.62.2", - "@rollup/rollup-win32-ia32-msvc": "4.62.2", - "@rollup/rollup-win32-x64-gnu": "4.62.2", - "@rollup/rollup-win32-x64-msvc": "4.62.2", - "fsevents": "~2.3.2" - } - }, - "node_modules/scheduler": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", - "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", - "license": "MIT" - }, - "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/siginfo": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", - "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", - "dev": true, - "license": "ISC" - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/stackback": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", - "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", - "dev": true, - "license": "MIT" - }, - "node_modules/std-env": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", - "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", - "dev": true, - "license": "MIT" - }, - "node_modules/strip-literal": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", - "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", - "dev": true, - "license": "MIT", - "dependencies": { - "js-tokens": "^9.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/strip-literal/node_modules/js-tokens": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", - "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinybench": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", - "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinyexec": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", - "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", - "dev": true, - "license": "MIT" - }, - "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/tinypool": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", - "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.0.0 || >=20.0.0" - } - }, - "node_modules/tinyrainbow": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", - "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/tinyspy": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz", - "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/update-browserslist-db": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", - "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/vite": { - "version": "6.4.3", - "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", - "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.25.0", - "fdir": "^6.4.4", - "picomatch": "^4.0.2", - "postcss": "^8.5.3", - "rollup": "^4.34.9", - "tinyglobby": "^0.2.13" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^18.0.0 || ^20.0.0 || >=22.0.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", - "jiti": ">=1.21.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.16.0", - "tsx": "^4.8.1", - "yaml": "^2.4.2" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "jiti": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - }, - "tsx": { - "optional": true - }, - "yaml": { - "optional": true - } - } - }, - "node_modules/vite-node": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", - "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cac": "^6.7.14", - "debug": "^4.4.1", - "es-module-lexer": "^1.7.0", - "pathe": "^2.0.3", - "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" - }, - "bin": { - "vite-node": "vite-node.mjs" - }, - "engines": { - "node": "^18.0.0 || ^20.0.0 || >=22.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/vitest": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", - "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/chai": "^5.2.2", - "@vitest/expect": "3.2.7", - "@vitest/mocker": "3.2.7", - "@vitest/pretty-format": "^3.2.7", - "@vitest/runner": "3.2.7", - "@vitest/snapshot": "3.2.7", - "@vitest/spy": "3.2.7", - "@vitest/utils": "3.2.7", - "chai": "^5.2.0", - "debug": "^4.4.1", - "expect-type": "^1.2.1", - "magic-string": "^0.30.17", - "pathe": "^2.0.3", - "picomatch": "^4.0.2", - "std-env": "^3.9.0", - "tinybench": "^2.9.0", - "tinyexec": "^0.3.2", - "tinyglobby": "^0.2.14", - "tinypool": "^1.1.1", - "tinyrainbow": "^2.0.0", - "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", - "vite-node": "3.2.4", - "why-is-node-running": "^2.3.0" - }, - "bin": { - "vitest": "vitest.mjs" - }, - "engines": { - "node": "^18.0.0 || ^20.0.0 || >=22.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "@edge-runtime/vm": "*", - "@types/debug": "^4.1.12", - "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", - "@vitest/browser": "3.2.7", - "@vitest/ui": "3.2.7", - "happy-dom": "*", - "jsdom": "*" - }, - "peerDependenciesMeta": { - "@edge-runtime/vm": { - "optional": true - }, - "@types/debug": { - "optional": true - }, - "@types/node": { - "optional": true - }, - "@vitest/browser": { - "optional": true - }, - "@vitest/ui": { - "optional": true - }, - "happy-dom": { - "optional": true - }, - "jsdom": { - "optional": true - } - } - }, - "node_modules/why-is-node-running": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", - "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", - "dev": true, - "license": "MIT", - "dependencies": { - "siginfo": "^2.0.0", - "stackback": "0.0.2" - }, - "bin": { - "why-is-node-running": "cli.js" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true, - "license": "ISC" - } - } -} diff --git a/EchoionWeb/frontend/package.json b/EchoionWeb/frontend/package.json deleted file mode 100644 index 8fb4156..0000000 --- a/EchoionWeb/frontend/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "echoion-web", - "private": true, - "version": "1.0.0", - "type": "module", - "scripts": { - "dev": "vite", - "build": "tsc --noEmit && vite build", - "preview": "vite preview", - "test": "vitest run", - "i18n:check": "node scripts/i18n-check.mjs" - }, - "dependencies": { - "react": "^19.1.0", - "react-dom": "^19.1.0" - }, - "devDependencies": { - "@types/react": "^19.1.0", - "@types/react-dom": "^19.1.0", - "@types/youtube": "^0.1.2", - "@vitejs/plugin-react": "^4.5.0", - "typescript": "^5.8.0", - "vite": "^6.3.0", - "vitest": "^3.1.0" - } -} diff --git a/EchoionWeb/frontend/public/favicon.svg b/EchoionWeb/frontend/public/favicon.svg deleted file mode 100644 index af81a1a..0000000 --- a/EchoionWeb/frontend/public/favicon.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/EchoionWeb/frontend/public/fonts.css b/EchoionWeb/frontend/public/fonts.css deleted file mode 100644 index 8462a3d..0000000 --- a/EchoionWeb/frontend/public/fonts.css +++ /dev/null @@ -1,480 +0,0 @@ -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/JetBrainsMono-1.woff2") format('woff2'); - unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/JetBrainsMono-2.woff2") format('woff2'); - unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/JetBrainsMono-3.woff2") format('woff2'); - unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/JetBrainsMono-4.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/JetBrainsMono-5.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/JetBrainsMono-6.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/JetBrainsMono-1.woff2") format('woff2'); - unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/JetBrainsMono-2.woff2") format('woff2'); - unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/JetBrainsMono-3.woff2") format('woff2'); - unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/JetBrainsMono-4.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/JetBrainsMono-5.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/JetBrainsMono-6.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/JetBrainsMono-1.woff2") format('woff2'); - unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/JetBrainsMono-2.woff2") format('woff2'); - unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/JetBrainsMono-3.woff2") format('woff2'); - unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/JetBrainsMono-4.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/JetBrainsMono-5.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'JetBrains Mono'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/JetBrainsMono-6.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/Manrope-7.woff2") format('woff2'); - unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/Manrope-8.woff2") format('woff2'); - unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/Manrope-9.woff2") format('woff2'); - unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/Manrope-10.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/Manrope-11.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/Manrope-12.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/Manrope-7.woff2") format('woff2'); - unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/Manrope-8.woff2") format('woff2'); - unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/Manrope-9.woff2") format('woff2'); - unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/Manrope-10.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/Manrope-11.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/Manrope-12.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/Manrope-7.woff2") format('woff2'); - unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/Manrope-8.woff2") format('woff2'); - unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/Manrope-9.woff2") format('woff2'); - unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/Manrope-10.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/Manrope-11.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/Manrope-12.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/Manrope-7.woff2") format('woff2'); - unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/Manrope-8.woff2") format('woff2'); - unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/Manrope-9.woff2") format('woff2'); - unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/Manrope-10.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/Manrope-11.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/Manrope-12.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 800; - font-display: swap; - src: url("/fonts/Manrope-7.woff2") format('woff2'); - unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 800; - font-display: swap; - src: url("/fonts/Manrope-8.woff2") format('woff2'); - unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 800; - font-display: swap; - src: url("/fonts/Manrope-9.woff2") format('woff2'); - unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 800; - font-display: swap; - src: url("/fonts/Manrope-10.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 800; - font-display: swap; - src: url("/fonts/Manrope-11.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Manrope'; - font-style: normal; - font-weight: 800; - font-display: swap; - src: url("/fonts/Manrope-12.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 400; - font-display: swap; - src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 500; - font-display: swap; - src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 600; - font-display: swap; - src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2'); - unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2'); - unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF; -} -@font-face { - font-family: 'Space Grotesk'; - font-style: normal; - font-weight: 700; - font-display: swap; - src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2'); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; -} diff --git a/EchoionWeb/frontend/public/fonts/JetBrainsMono-1.woff2 b/EchoionWeb/frontend/public/fonts/JetBrainsMono-1.woff2 deleted file mode 100644 index 289de93..0000000 Binary files a/EchoionWeb/frontend/public/fonts/JetBrainsMono-1.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/JetBrainsMono-2.woff2 b/EchoionWeb/frontend/public/fonts/JetBrainsMono-2.woff2 deleted file mode 100644 index de39acb..0000000 Binary files a/EchoionWeb/frontend/public/fonts/JetBrainsMono-2.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/JetBrainsMono-3.woff2 b/EchoionWeb/frontend/public/fonts/JetBrainsMono-3.woff2 deleted file mode 100644 index a53d52d..0000000 Binary files a/EchoionWeb/frontend/public/fonts/JetBrainsMono-3.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/JetBrainsMono-4.woff2 b/EchoionWeb/frontend/public/fonts/JetBrainsMono-4.woff2 deleted file mode 100644 index e38f553..0000000 Binary files a/EchoionWeb/frontend/public/fonts/JetBrainsMono-4.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/JetBrainsMono-5.woff2 b/EchoionWeb/frontend/public/fonts/JetBrainsMono-5.woff2 deleted file mode 100644 index 82f9668..0000000 Binary files a/EchoionWeb/frontend/public/fonts/JetBrainsMono-5.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/JetBrainsMono-6.woff2 b/EchoionWeb/frontend/public/fonts/JetBrainsMono-6.woff2 deleted file mode 100644 index 4d09cda..0000000 Binary files a/EchoionWeb/frontend/public/fonts/JetBrainsMono-6.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/Manrope-10.woff2 b/EchoionWeb/frontend/public/fonts/Manrope-10.woff2 deleted file mode 100644 index 1e4b7a4..0000000 Binary files a/EchoionWeb/frontend/public/fonts/Manrope-10.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/Manrope-11.woff2 b/EchoionWeb/frontend/public/fonts/Manrope-11.woff2 deleted file mode 100644 index bd24140..0000000 Binary files a/EchoionWeb/frontend/public/fonts/Manrope-11.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/Manrope-12.woff2 b/EchoionWeb/frontend/public/fonts/Manrope-12.woff2 deleted file mode 100644 index 71eb731..0000000 Binary files a/EchoionWeb/frontend/public/fonts/Manrope-12.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/Manrope-7.woff2 b/EchoionWeb/frontend/public/fonts/Manrope-7.woff2 deleted file mode 100644 index 57c7c0e..0000000 Binary files a/EchoionWeb/frontend/public/fonts/Manrope-7.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/Manrope-8.woff2 b/EchoionWeb/frontend/public/fonts/Manrope-8.woff2 deleted file mode 100644 index 3a06229..0000000 Binary files a/EchoionWeb/frontend/public/fonts/Manrope-8.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/Manrope-9.woff2 b/EchoionWeb/frontend/public/fonts/Manrope-9.woff2 deleted file mode 100644 index e74e718..0000000 Binary files a/EchoionWeb/frontend/public/fonts/Manrope-9.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/SpaceGrotesk-13.woff2 b/EchoionWeb/frontend/public/fonts/SpaceGrotesk-13.woff2 deleted file mode 100644 index ce97d0f..0000000 Binary files a/EchoionWeb/frontend/public/fonts/SpaceGrotesk-13.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/SpaceGrotesk-14.woff2 b/EchoionWeb/frontend/public/fonts/SpaceGrotesk-14.woff2 deleted file mode 100644 index db732c2..0000000 Binary files a/EchoionWeb/frontend/public/fonts/SpaceGrotesk-14.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/fonts/SpaceGrotesk-15.woff2 b/EchoionWeb/frontend/public/fonts/SpaceGrotesk-15.woff2 deleted file mode 100644 index 0f3474e..0000000 Binary files a/EchoionWeb/frontend/public/fonts/SpaceGrotesk-15.woff2 and /dev/null differ diff --git a/EchoionWeb/frontend/public/icon-maskable.svg b/EchoionWeb/frontend/public/icon-maskable.svg deleted file mode 100644 index 79a58aa..0000000 --- a/EchoionWeb/frontend/public/icon-maskable.svg +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/EchoionWeb/frontend/public/icon.svg b/EchoionWeb/frontend/public/icon.svg deleted file mode 100644 index 9b9cd7b..0000000 --- a/EchoionWeb/frontend/public/icon.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/EchoionWeb/frontend/public/manifest.webmanifest b/EchoionWeb/frontend/public/manifest.webmanifest deleted file mode 100644 index ae42602..0000000 --- a/EchoionWeb/frontend/public/manifest.webmanifest +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "Echoion Music Bot", - "short_name": "Echoion", - "description": "Control the Echoion TeamSpeak music bot and view live server activity.", - "start_url": "/", - "scope": "/", - "display": "standalone", - "orientation": "any", - "background_color": "#0d0d1f", - "theme_color": "#151522", - "icons": [ - { - "src": "/icon.svg", - "sizes": "any", - "type": "image/svg+xml", - "purpose": "any" - }, - { - "src": "/icon-maskable.svg", - "sizes": "any", - "type": "image/svg+xml", - "purpose": "maskable" - } - ] -} diff --git a/EchoionWeb/frontend/public/sw.js b/EchoionWeb/frontend/public/sw.js deleted file mode 100644 index ee099dc..0000000 --- a/EchoionWeb/frontend/public/sw.js +++ /dev/null @@ -1,82 +0,0 @@ -// Minimal, dependency-free service worker: makes the panel installable and -// keeps the app shell available offline. It deliberately does NOT touch the -// live surfaces — /rpc (WebSockets aren't interceptable anyway), -// /config.json, /api/* and /avatar/* all fall through to the network so the -// UI never shows stale identity/config. - -// Bump when the player shell changes materially so installed/PWA clients do -// not retain an index that references a removed hashed bundle. -const CACHE = 'echoion-shell-v4'; -const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg']; - -self.addEventListener('install', (event) => { - event.waitUntil( - caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()) - ); -}); - -self.addEventListener('activate', (event) => { - event.waitUntil( - caches - .keys() - .then((keys) => - Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))) - ) - .then(() => self.clients.claim()) - ); -}); - -// Only same-origin GETs are cacheable; everything else passes through. -function isStaticAsset(url) { - return ( - url.pathname.startsWith('/assets/') || - url.pathname === '/manifest.webmanifest' || - url.pathname.startsWith('/icon') || - url.pathname.startsWith('/fonts') || - url.pathname.endsWith('.css') || - url.pathname.endsWith('.woff2') || - url.pathname.endsWith('.svg') - ); -} - -self.addEventListener('fetch', (event) => { - const req = event.request; - if (req.method !== 'GET') return; - const url = new URL(req.url); - if (url.origin !== self.location.origin) return; - - // Never intercept the live control/config/media surfaces. - if ( - url.pathname === '/config.json' || - url.pathname.startsWith('/api/') || - url.pathname.startsWith('/rpc') || - url.pathname.startsWith('/avatar') - ) { - return; - } - - // SPA navigations: network-first, fall back to the cached shell offline. - if (req.mode === 'navigate') { - event.respondWith( - fetch(req).catch(() => caches.match('/').then((r) => r || fetch(req))) - ); - return; - } - - // Hashed static assets: cache-first, populate on first hit. - if (isStaticAsset(url)) { - event.respondWith( - caches.match(req).then( - (hit) => - hit || - fetch(req).then((resp) => { - if (resp.ok) { - const copy = resp.clone(); - caches.open(CACHE).then((c) => c.put(req, copy)); - } - return resp; - }) - ) - ); - } -}); diff --git a/EchoionWeb/frontend/scripts/i18n-check.mjs b/EchoionWeb/frontend/scripts/i18n-check.mjs deleted file mode 100644 index c870d08..0000000 --- a/EchoionWeb/frontend/scripts/i18n-check.mjs +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env node -// Diffs the Russian catalog (src/i18n/ru.ts) against every t('…') / tf('…') -// literal in src/**/*.ts{,x}, both ways: -// - missing: used in code but absent from ru.ts (falls back to English) -// - orphaned: present in ru.ts but never used as a literal key -// -// Dynamic keys can't be found by this scan and must be checked by hand: -// - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label) -// - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub) -// Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC -// list below suppresses the ones we know about. -// -// Usage: npm run i18n:check (exits 1 when keys are missing) - -import { readFileSync, readdirSync, statSync } from 'node:fs'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const root = join(dirname(fileURLToPath(import.meta.url)), '..'); -const srcDir = join(root, 'src'); -const ruFile = join(srcDir, 'i18n', 'ru.ts'); - -// Keys reached through variables (see header); keep in sync by hand. -const KNOWN_DYNAMIC = new Set([ - // connection state rendered via t(s.connection) in Sidebar.tsx - 'connected', - 'disconnected', - 'error', - // SHORTCUTS labels (lib/shortcuts.ts) - 'Play / pause', - 'Seek 5s', - 'Volume', - 'Skip / vote skip', - 'Focus search', - 'This help', - // HEADS view titles/subtitles (App.tsx) - 'Dashboard', - 'Live playback and TeamSpeak server activity', - 'Queue', - 'Reorder and manage upcoming tracks', - 'Search', - 'Find tracks across YouTube and Yandex Music', - 'Library', - 'Your favorites and saved playlists', - 'History & Stats', - 'Playback history and server insights', - 'Server & Admin', - 'Manage subscribers and broadcast', - 'Updates', - 'Runtime, Core, and plugin release control', - 'RPC / API', - 'Connect to Echoion programmatically', - // Sidebar NAV labels rendered via t(item.label) — same strings as HEADS - // titles, listed above. -]); - -const unescape = (s) => s.replace(/\\(.)/g, '$1'); - -function walk(dir, out = []) { - for (const name of readdirSync(dir)) { - const p = join(dir, name); - if (statSync(p).isDirectory()) walk(p, out); - else if (/\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name)) { - out.push(p); - } - } - return out; -} - -// Catalog keys: top-level `'key': '…'` entries of the ru object literal. -const ruKeys = new Set(); -for (const m of readFileSync(ruFile, 'utf8').matchAll( - /^\s*'((?:[^'\\]|\\.)*)':/gm -)) { - ruKeys.add(unescape(m[1])); -} - -// Used keys: every t('…') / tf('…', …) string literal. -const used = new Set(); -for (const file of walk(srcDir)) { - if (file === ruFile) continue; - const text = readFileSync(file, 'utf8'); - for (const m of text.matchAll(/\btf?\(\s*'((?:[^'\\]|\\.)*)'/g)) { - used.add(unescape(m[1])); - } -} - -const missing = [...used].filter((k) => !ruKeys.has(k)).sort(); -const orphaned = [...ruKeys] - .filter((k) => !used.has(k) && !KNOWN_DYNAMIC.has(k)) - .sort(); - -if (missing.length) { - console.log(`Missing from ru.ts (${missing.length}):`); - for (const k of missing) console.log(`\t'${k.replace(/'/g, "\\'")}':`); -} -if (orphaned.length) { - console.log(`\nIn ru.ts but never used as a literal (${orphaned.length}):`); - for (const k of orphaned) console.log(`\t'${k.replace(/'/g, "\\'")}'`); - console.log('(may be dynamic keys — verify before deleting)'); -} -if (!missing.length && !orphaned.length) console.log('i18n: OK'); -process.exit(missing.length ? 1 : 0); diff --git a/EchoionWeb/frontend/src/App.tsx b/EchoionWeb/frontend/src/App.tsx deleted file mode 100644 index 3872007..0000000 --- a/EchoionWeb/frontend/src/App.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import { useEffect } from 'react'; -import { appStore, boot } from './lib/app'; -import { initRouter } from './lib/router'; -import { initShortcuts } from './lib/shortcuts'; -import { initMediaSession } from './lib/mediaSession'; -import { useStore } from './lib/store'; -import { useLanguage, t } from './i18n'; -import { HelpIcon, MenuIcon } from './components/icons'; -import { Sidebar } from './components/Sidebar'; -import { MiniPlayer } from './components/MiniPlayer'; -import { DialogHost } from './components/DialogHost'; -import { ShortcutsHelp } from './components/ShortcutsHelp'; -import { DashboardView } from './views/DashboardView'; -import { QueueView } from './views/QueueView'; -import { SearchView } from './views/SearchView'; -import { LibraryView } from './views/LibraryView'; -import { StatsView } from './views/StatsView'; -import { ServerView } from './views/ServerView'; -import { UpdatesView } from './views/UpdatesView'; -import { RpcView } from './views/RpcView'; - -const HEADS: Record = { - dashboard: ['Dashboard', 'Live playback and TeamSpeak server activity'], - queue: ['Queue', 'Reorder and manage upcoming tracks'], - search: ['Search', 'Find tracks across YouTube and Yandex Music'], - library: ['Library', 'Your favorites and saved playlists'], - stats: ['History & Stats', 'Playback history and server insights'], - server: ['Server & Admin', 'Manage subscribers and broadcast'], - updates: ['Updates', 'Runtime, Core, and plugin release control'], - rpc: ['RPC / API', 'Connect to Echoion programmatically'], -}; - -export function App() { - const s = useStore(appStore); - useLanguage(); // re-render everything on language switch - - useEffect(() => { - boot(); - initRouter(); - initShortcuts(); - initMediaSession(); - }, []); - - const [title, sub] = HEADS[s.view] || HEADS.dashboard; - - return ( -
- - {s.sidebarOpen && ( -
appStore.set({ sidebarOpen: false })} - /> - )} -
-
-
- -
-

{t(title)}

-
{t(sub)}
-
-
-
- - - {s.onlineCount} {t('online')} - - -
-
- - {s.view === 'dashboard' && } - {s.view === 'queue' && } - {s.view === 'search' && } - {s.view === 'library' && } - {s.view === 'stats' && } - {s.view === 'server' && } - {s.view === 'updates' && } - {s.view === 'rpc' && } - - -
- {s.toast &&
{s.toast}
} - - -
- ); -} diff --git a/EchoionWeb/frontend/src/components/AnnounceModal.tsx b/EchoionWeb/frontend/src/components/AnnounceModal.tsx deleted file mode 100644 index 9ae0274..0000000 --- a/EchoionWeb/frontend/src/components/AnnounceModal.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import { useState } from 'react'; -import { safeCall, toast } from '../lib/app'; -import { renderTsMarkup } from '../lib/tsMarkup'; -import { Modal } from './Modal'; -import { t } from '../i18n'; - -// Announce composer with a live TS6-markdown/BBCode preview (item 14). -// Replaces the old prompt(). A small toolbar wraps the selection in common -// formatting tags; the preview renders exactly what subscribers will see. -const TOOLBAR: Array<{ label: string; before: string; after: string }> = [ - { label: 'B', before: '**', after: '**' }, - { label: 'I', before: '*', after: '*' }, - { label: 'U', before: '[u]', after: '[/u]' }, - { label: 'S', before: '~~', after: '~~' }, - { label: '', before: '`', after: '`' }, - { label: '🔗', before: '[', after: '](https://)' }, - { label: 'H', before: '# ', after: '' }, - { label: '❝', before: '> ', after: '' }, -]; - -export function AnnounceModal({ onClose }: { onClose: () => void }) { - const [text, setText] = useState(''); - const [sending, setSending] = useState(false); - let ref: HTMLTextAreaElement | null = null; - - const wrap = (before: string, after: string) => { - const el = ref; - if (!el) return; - const start = el.selectionStart; - const end = el.selectionEnd; - const selected = text.slice(start, end); - const next = - text.slice(0, start) + before + selected + after + text.slice(end); - setText(next); - // Restore focus with the caret after the inserted opening tag. - queueMicrotask(() => { - el.focus(); - const pos = start + before.length + selected.length; - el.setSelectionRange(pos, pos); - }); - }; - - return ( - - - - - } - > -
- {TOOLBAR.map((b) => ( - - ))} -
-
-