diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e2694b4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +.git +build* +dist +release +EchoionWeb/frontend/node_modules +EchoionWeb/frontend/web-dist +docs diff --git a/.gitea/RELEASING.md b/.gitea/RELEASING.md new file mode 100644 index 0000000..cb3b5e1 --- /dev/null +++ b/.gitea/RELEASING.md @@ -0,0 +1,137 @@ +# Echoion releases on Gitea + +Echoion release builds run only through `scripts/release.sh`, whose default +mode builds, tests, validates, and packages inside +`containers/release.Dockerfile`. The runner host only checks out sources and +controls Docker; the workflow never starts `echoiond`. + +## One-time Gitea setup + +Register exactly one trusted Linux AMD64 Actions runner with the +`echoion-release` label and Docker access. Using one runner serializes release +and feed writes on Gitea versions that do not implement workflow +`concurrency`. Do not attach this label to runners serving untrusted +repositories. The runner host needs Bash, Git with SSH-signature support, +OpenSSH client tools, Python 3.10 or newer, OpenSSL with Ed25519 support, +coreutils, and Docker. The release builder itself remains containerized. + +The Docker-capable runner executes only protected `main` pushes, manual runs, +scheduled nightlies, and signed release tags. The container CI workflow does +not run for pull requests because contributor-controlled scripts must not +receive a privileged Docker socket or the private-submodule checkout key. If +pre-merge CI is required, register a separate ephemeral `echoion-pr` runner +without release secrets or host-level Docker access and give it a dedicated +workflow. + +Enable Actions and add these repository secrets: + +| Secret | Purpose | +| --- | --- | +| `RELEASE_CHECKOUT_SSH_KEY` | Read-only deploy key that can clone every private nested repository in `.gitmodules`. | +| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot, limited to writing releases, tags, and the `release-feed` branch 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. | + +The release PAT must not be shared with checkout of nested repositories. The +feed signing key must not be stored in Git, runner images, Actions variables, +or release assets. + +Create an orphan `release-feed` branch containing a tracked `feeds/` +directory, then protect it so only the release bot can push. Protect the `v*` +tag pattern so only the release maintainers represented by +`RELEASE_TAG_ALLOWED_SIGNERS` can create, update, or delete matching tags. The +workflow requires the exact `v*` rule to have an explicit non-empty user or +team allowlist. 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: + +```text +https://///raw/branch/release-feed/feeds/echoion-runtime.json +``` + +The embedded updater trust configuration is represented by +`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. + +## Stable and beta releases + +Create an annotated SSH-signed tag. A version without a prerelease suffix goes +to `stable`; any strict SemVer prerelease goes to `beta`. + +```bash +git config gpg.format ssh +git config user.signingkey ~/.ssh/echoion-release-maintainer.pub +git tag -s -a v1.2.3 -m 'Echoion 1.2.3' +git push origin v1.2.3 +``` + +`.gitea/workflows/release.yml` rejects a lightweight tag, a non-SSH +signature, an untrusted signer, a repository without the exact `v*` protected +tag rule and explicit allowlist, a non-SemVer name, an event object unrelated +to the tag, or a checkout whose commit differs from the signed tag target. +Release notes contain the signed tag subject and body but not its SSH signature +armor. + +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. + +## Nightly releases + +`.gitea/workflows/nightly.yml` runs at 02:17 UTC and can also be dispatched +manually. Nightly versions use +`0.0.0-nightly.YYYYMMDD.RUN_NUMBER`, publish as prereleases on the `nightly` +channel, and keep the newest 14 Gitea releases. The aggregate feed also keeps +the newest 14 distinct nightly versions while retaining stable and beta +records. + +Every aggregate 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. + +## Feed key custody and rotation + +The active public key id is `echoion-release-2026-07`. To rotate, generate the +private key on a trusted operator machine: + +```bash +umask 077 +openssl genpkey -algorithm ED25519 -out echoion-release-YYYY-MM.pem +openssl pkey -in echoion-release-YYYY-MM.pem -pubout \ + -out echoion-release-YYYY-MM.pub.pem +``` + +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. + +## Recovery rules + +- A failed build creates no Gitea release. +- A failed upload leaves a draft. Rerun the same workflow to replace the + partial draft assets. +- A failed verification never publishes the draft. +- A published release with mismatched assets is immutable; investigate and + create a new version instead of replacing it. +- 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. diff --git a/.gitea/release-keys/echoion-release-2026-07.pub.pem b/.gitea/release-keys/echoion-release-2026-07.pub.pem new file mode 100644 index 0000000..e1f8c2d --- /dev/null +++ b/.gitea/release-keys/echoion-release-2026-07.pub.pem @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEASj3V/xDWSJ37MwLjhyZ0MZPwj/DoJUEWZdYSv+R5NNI= +-----END PUBLIC KEY----- diff --git a/.gitea/release-keys/official-update-keys.json b/.gitea/release-keys/official-update-keys.json new file mode 100644 index 0000000..8d8dd36 --- /dev/null +++ b/.gitea/release-keys/official-update-keys.json @@ -0,0 +1,6 @@ +[ + { + "id": "echoion-release-2026-07", + "ed25519": "Sj3V/xDWSJ37MwLjhyZ0MZPwj/DoJUEWZdYSv+R5NNI=" + } +] diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..c5cf1b9 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,50 @@ +name: Container CI + +on: + push: + branches: + - main + workflow_dispatch: + +permissions: + contents: read + +jobs: + release-build: + runs-on: echoion-release + steps: + - name: Check out source and nested repositories + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + fetch-depth: 0 + submodules: recursive + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + persist-credentials: false + + - name: Verify runner isolation prerequisites + run: | + set -eu + test "$(uname -s)" = Linux + docker version + + - name: Build, test, and package without starting Echoion + env: + CI_VERSION: 0.0.0-ci.${{ gitea.run_number }}.${{ gitea.run_attempt }} + run: | + set -eu + scripts/release.sh --version "$CI_VERSION" + + - name: Test release control-plane scripts + run: | + set -eu + bash scripts/tests/test-gitea-tag-verification.sh + docker run --rm --network none \ + --volume "$PWD:/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 "$PWD:/workspace:ro" \ + --workdir /workspace \ + echoion-release-builder:gcc-16.1.0 \ + python3 scripts/tests/test_gitea_release.py diff --git a/.gitea/workflows/nightly.yml b/.gitea/workflows/nightly.yml new file mode 100644 index 0000000..e6e5955 --- /dev/null +++ b/.gitea/workflows/nightly.yml @@ -0,0 +1,158 @@ +name: Nightly release + +on: + schedule: + - cron: '17 2 * * *' + workflow_dispatch: + +permissions: + contents: read + +jobs: + publish-nightly: + runs-on: echoion-release + steps: + - name: Check out main and nested repositories + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: main + fetch-depth: 0 + submodules: recursive + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + persist-credentials: false + + - name: Derive the nightly identity + shell: bash + env: + SERVER_URL: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + RUN_NUMBER: ${{ gitea.run_number }} + run: | + set -euo pipefail + date_id=$(date -u +%Y%m%d) + version="0.0.0-nightly.${date_id}.${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_TARGET=%s\n' "$(git rev-parse HEAD)" + } >>"$GITHUB_ENV" + + - name: Build and test the dynamic nightly in Docker + shell: bash + run: | + set -euo pipefail + scripts/release.sh \ + --version "$RELEASE_VERSION" \ + --update-url "$RELEASE_ARTIFACT_URL" \ + --official-update-feed-url "$RELEASE_FEED_URL" \ + --update-channel nightly \ + --update-valid-days 45 + { + 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 + 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" \ + publish \ + --owner "$owner" \ + --repo "$repo" \ + --tag "$RELEASE_TAG" \ + --target "$RELEASE_TARGET" \ + --name "Echoion nightly $RELEASE_VERSION" \ + --body-file "$RUNNER_TEMP/release-notes.md" \ + --artifacts dist \ + --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 \ + --owner "$owner" \ + --repo "$repo" \ + --tag-prefix nightly- \ + --keep 14 \ + --protect-tag "$RELEASE_TAG" + + - name: Check out the aggregate feed branch + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: release-feed + path: feed-state + token: ${{ secrets.RELEASE_BOT_TOKEN }} + fetch-depth: 1 + + - name: Sign and push the aggregate feed last + shell: bash + env: + FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_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 + 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" \ + "${existing[@]}" \ + --public-key \ + .gitea/release-keys/echoion-release-2026-07.pub.pem \ + --private-key "$key" \ + --key-id echoion-release-2026-07 \ + --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 + 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 + if git -C feed-state diff --cached --quiet; then + exit 0 + fi + git -C feed-state commit -m \ + "Feed: nightly ${RELEASE_VERSION}" + git -C feed-state push origin HEAD:release-feed diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..f3c47a7 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,180 @@ +name: Signed release + +on: + push: + tags: + - v* + +permissions: + contents: read + +jobs: + publish: + runs-on: echoion-release + steps: + - name: Check out the signed tag + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: ${{ gitea.ref }} + fetch-depth: 0 + submodules: recursive + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + persist-credentials: false + + - name: Verify protected annotated SSH tag + shell: bash + env: + TAG: ${{ gitea.ref_name }} + EXPECTED_EVENT_SHA: ${{ gitea.sha }} + EXPECTED_REF: ${{ gitea.ref }} + EXPECTED_REF_TYPE: ${{ gitea.ref_type }} + TAG_ALLOWED_SIGNERS: ${{ secrets.RELEASE_TAG_ALLOWED_SIGNERS }} + GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} + API_URL: ${{ gitea.api_url }} + REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + test "$EXPECTED_REF_TYPE" = tag + test "$EXPECTED_REF" = "refs/tags/$TAG" + allowed_signers="$RUNNER_TEMP/echoion-release-allowed-signers" + trap 'rm -f -- "$allowed_signers"' EXIT + umask 077 + printf '%s\n' "$TAG_ALLOWED_SIGNERS" >"$allowed_signers" + test -s "$allowed_signers" + target_commit=$( + scripts/verify-gitea-release-tag.sh \ + --tag "$TAG" \ + --event-sha "$EXPECTED_EVENT_SHA" \ + --allowed-signers "$allowed_signers" \ + --notes-output "$RUNNER_TEMP/release-notes.md" + ) + printf 'RELEASE_TARGET=%s\n' "$target_commit" >>"$GITHUB_ENV" + owner=${REPOSITORY%%/*} + repo=${REPOSITORY#*/} + python3 scripts/gitea_release.py \ + --api-url "$API_URL" \ + verify-tag-protection \ + --owner "$owner" \ + --repo "$repo" \ + --required-pattern 'v*' + + - name: Derive the stable or beta release + shell: bash + env: + TAG: ${{ gitea.ref_name }} + SERVER_URL: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + run: | + set -euo pipefail + version=${TAG#v} + test "$version" != "$TAG" + python3 scripts/validate-semver.py "$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" + { + 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_FEED_URL=%s\n' "$feed_url" + } >>"$GITHUB_ENV" + + - name: Build and test the dynamic release in Docker + shell: bash + run: | + set -euo pipefail + scripts/release.sh \ + --version "$RELEASE_VERSION" \ + --update-url "$RELEASE_ARTIFACT_URL" \ + --official-update-feed-url "$RELEASE_FEED_URL" \ + --update-channel "$RELEASE_CHANNEL" \ + --update-valid-days 45 + + - name: Create draft, upload, download-verify, and publish + 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#*/} + prerelease=() + if [[ "$RELEASE_PRERELEASE" = true ]]; then + prerelease+=(--prerelease) + fi + python3 scripts/gitea_release.py \ + --api-url "$API_URL" \ + publish \ + --owner "$owner" \ + --repo "$repo" \ + --tag "$RELEASE_TAG" \ + --target "$RELEASE_TARGET" \ + --name "Echoion $RELEASE_VERSION" \ + --body-file "$RUNNER_TEMP/release-notes.md" \ + --artifacts dist \ + "${prerelease[@]}" + + - name: Check out the aggregate feed branch + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: release-feed + path: feed-state + token: ${{ secrets.RELEASE_BOT_TOKEN }} + fetch-depth: 1 + + - name: Sign and push the aggregate feed last + shell: bash + env: + FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_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 + 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" \ + "${existing[@]}" \ + --public-key \ + .gitea/release-keys/echoion-release-2026-07.pub.pem \ + --private-key "$key" \ + --key-id echoion-release-2026-07 \ + --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 + 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 + if git -C feed-state diff --cached --quiet; then + exit 0 + fi + git -C feed-state commit -m \ + "Feed: ${RELEASE_CHANNEL} ${RELEASE_VERSION}" + git -C feed-state push origin HEAD:release-feed diff --git a/.gitignore b/.gitignore index 3a34447..50cfbb9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,11 @@ *build* +release +/dist/ +__pycache__/ +*.py[cod] +.claude .cache .idea AGENTS.md .vscode -.opencode/ \ No newline at end of file +.opencode/ diff --git a/.gitmodules b/.gitmodules index de313f3..b9aca0d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,9 +4,6 @@ [submodule "EchoionCore"] path = EchoionCore url = ssh://gitea@git.faumaray.ru/void/echoioncore.git -[submodule "EchoionPlugin"] - path = EchoionPlugin - url = ssh://gitea@git.faumaray.ru/void/echoionplugin.git [submodule "EchoionDesktop"] path = EchoionDesktop url = ssh://gitea@git.faumaray.ru/void/echoiondesktop.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 26d0abf..f44ac40 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,9 @@ cmake_minimum_required(VERSION 4.0.0) project(Echoion VERSION 1.0.0 LANGUAGES CXX) +include(GNUInstallDirs) +include(cmake/DependencyLock.cmake) + # 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 # falls back to -O0, so "production" builds shipped unoptimised. Set this before @@ -26,6 +29,51 @@ if(ECHOION_USE_CCACHE AND NOT CMAKE_CXX_COMPILER_LAUNCHER) endif() endif() +# Decide linkage before configuring CPM dependencies. Protocol and VoidLibrary +# must be part of the validated echoiond artifact in production, otherwise a +# release could pair a new daemon with an old/incompatible shared library. +option(BUILD_SHARED_LIBS "Build shared libraries" ON) +option(ECHOION_STATIC_LINK "Statically link the GCC runtimes" OFF) +if(ECHOION_STATIC_LINK) + set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE) + set(BUILD_SHARED_LIBS OFF) + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + message(STATUS "Static GCC runtime linking enabled") +endif() + +# Release artifacts should not expose checkout, dependency, or build-machine +# paths through __FILE__, std::source_location, or optional DWARF data. Keep +# developer builds unchanged so local diagnostics can still use absolute paths; +# scripts/release.sh enables this option for production builds. +option(ECHOION_REPRODUCIBLE_BUILD + "Replace local source/build prefixes in compiler-generated paths" OFF) +if(ECHOION_REPRODUCIBLE_BUILD) + if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + set(_echoionPrefixMaps + "${CMAKE_SOURCE_DIR}=Echoion" + "${CMAKE_BINARY_DIR}=EchoionBuild") + if(DEFINED CPM_Void_SOURCE AND NOT CPM_Void_SOURCE STREQUAL "") + list(APPEND _echoionPrefixMaps + "${CPM_Void_SOURCE}=VoidLibrary") + endif() + if(DEFINED CPM_VoidTeamspeak_SOURCE AND + NOT CPM_VoidTeamspeak_SOURCE STREQUAL "") + list(APPEND _echoionPrefixMaps + "${CPM_VoidTeamspeak_SOURCE}=VoidTeamspeak") + endif() + foreach(_echoionPrefixMap IN LISTS _echoionPrefixMaps) + add_compile_options( + "$<$:-ffile-prefix-map=${_echoionPrefixMap}>" + "$<$:-fmacro-prefix-map=${_echoionPrefixMap}>" + "$<$:-fdebug-prefix-map=${_echoionPrefixMap}>") + endforeach() + message(STATUS "Reproducible compiler path mapping enabled") + else() + message(WARNING + "ECHOION_REPRODUCIBLE_BUILD is not supported by this compiler") + endif() +endif() + # Include CPM file( DOWNLOAD @@ -50,12 +98,27 @@ CPMAddPackage( # which CPM honours over the git checkout below. CPMAddPackage( NAME Void - GIT_REPOSITORY http://git.faumaray.ru/void/voidlibrary.git - GIT_TAG main + GIT_REPOSITORY https://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} OPTIONS "VOID_ENABLE_TESTING OFF" ) +# Modern native TeamSpeak client library. Local development can point at the +# adjacent history-preserving extraction with: +# -DCPM_VoidTeamspeak_SOURCE=$HOME/Project/Personal/VoidTeamspeak +CPMAddPackage( + NAME VoidTeamspeak + GIT_REPOSITORY https://git.faumaray.ru/void/voidteamspeak.git + # This revision supplies the typed administration API used by Standalone. + GIT_TAG ${ECHOION_VOID_TEAMSPEAK_REVISION} + OPTIONS + "VOID_TEAMSPEAK_BUILD_TESTS OFF" + "VOID_ENABLE_TESTING OFF" +) + set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) @@ -103,20 +166,14 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON) # Options option(BUILD_API "Build EchoionApi" ON) option(BUILD_CORE "Build EchoionCore" ON) -option(BUILD_PLUGIN "Build EchoionPlugin" ON) option(BUILD_DESKTOP "Build EchoionDesktop" ON) -option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON) -option(BUILD_PROTOCOL "Build EchoionProtocol (native TeamSpeak UDP client)" ON) -option(BUILD_STANDALONE "Build EchoionStandalone (daemon; no TeamSpeak client)" ON) +option(BUILD_WEB "Build EchoionWeb browser dashboard" ON) +option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON) +option(BUILD_FIRST_PARTY_PLUGINS "Build bundled Echoion extension plugins" ON) option(BUILD_TESTS "Build tests" OFF) -option(BUILD_SHARED_LIBS "Build shared libraries" ON) -option(ECHOION_STATIC_LINK "Statically link dependencies for standalone distribution" ON) -# Static linking configuration -if(ECHOION_STATIC_LINK) - set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++" CACHE STRING "" FORCE) - set(BUILD_SHARED_LIBS OFF) - message(STATUS "Static linking enabled - building standalone distribution") +if(BUILD_TESTS) + enable_testing() endif() # Find packages @@ -127,6 +184,14 @@ if(BUILD_API) add_subdirectory(EchoionApi) endif() +if(BUILD_FIRST_PARTY_PLUGINS) + add_subdirectory(plugins) +endif() + +if(BUILD_STANDALONE) + add_subdirectory(EchoionHost) +endif() + if(BUILD_CORE) add_subdirectory(EchoionCore) endif() @@ -142,17 +207,18 @@ if(BUILD_WEB AND BUILD_CORE) endif() endif() -if(BUILD_PLUGIN) - add_subdirectory(EchoionPlugin) +# VoidTeamspeak is resolved above as a regular reusable package. The legacy +# TeamSpeak client plugin and in-tree protocol directories are no longer built. + +# The updater is a deliberately small, dynamically linked lifecycle helper. +# 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) endif() -# EchoionProtocol: standalone TeamSpeak UDP client library (no Echoion deps). -if(BUILD_PROTOCOL OR BUILD_STANDALONE) - add_subdirectory(EchoionProtocol) -endif() - -# EchoionStandalone: reuses the plugin's CoreLoader, so it needs EchoionPlugin's -# sources present. It links the Api + EchoionProtocol and loads Core at runtime. +# EchoionStandalone links the host-common loader and native protocol client. if(BUILD_STANDALONE) add_subdirectory(EchoionStandalone) endif() @@ -161,41 +227,64 @@ if(BUILD_DESKTOP) add_subdirectory(EchoionDesktop) endif() -# Tests -if(BUILD_TESTS) - enable_testing() - add_subdirectory(tests) -endif() +# The release install component is deliberately runtime-only. Nested projects +# keep their normal SDK/development install rules, while scripts/release.sh uses +# this component as the single input to dependency collection and packaging. +option(ECHOION_INSTALL_RUNTIME_BUNDLE + "Provide the relocatable Echoion Runtime install component" ON) +if(ECHOION_INSTALL_RUNTIME_BUNDLE) + if(TARGET EchoionStandalone) + if(UNIX AND NOT APPLE) + set_target_properties(EchoionStandalone PROPERTIES + INSTALL_RPATH "$ORIGIN/../${CMAKE_INSTALL_LIBDIR}" + INSTALL_RPATH_USE_LINK_PATH FALSE) + endif() + install(TARGETS EchoionStandalone + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + COMPONENT Runtime) + endif() -# Packaging configuration -include(CPack) -set(CPACK_PACKAGE_NAME "Echoion") -set(CPACK_PACKAGE_VENDOR "Echoion") -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak") -set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) -set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) -set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) -set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") -set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md") + if(TARGET EchoionCore) + if(UNIX AND NOT APPLE) + set_target_properties(EchoionCore PROPERTIES + INSTALL_RPATH "$ORIGIN" + INSTALL_RPATH_USE_LINK_PATH FALSE) + endif() + install(TARGETS EchoionCore + RUNTIME DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + COMPONENT Runtime) + endif() -# Platform-specific packaging -if(WIN32) - set(CPACK_GENERATOR "ZIP;NSIS") - set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot") - set(CPACK_NSIS_HELP_LINK "https://github.com/yourusername/echoion") - set(CPACK_NSIS_URL_INFO_ABOUT "https://github.com/yourusername/echoion") -elseif(APPLE) - set(CPACK_GENERATOR "DragNDMGZ") - set(CPACK_DMG_VOLUME_NAME "Echoion") -else() - set(CPACK_GENERATOR "TGZ;DEB;RPM") - set(CPACK_DEBIAN_PACKAGE_DEPENDS "libssl3, libavformat58, libavcodec58, libsqlite3-0") - set(CPACK_RPM_PACKAGE_REQUIRES "openssl, ffmpeg-libs, sqlite") + if(TARGET EchoionWeb) + install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/EchoionWeb/frontend/web-dist/" + DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/web" + COMPONENT Runtime) + endif() + + install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/config.example.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" + "${CMAKE_CURRENT_SOURCE_DIR}/packaging/service/echoion-updater.timer.in" + DESTINATION service + COMPONENT Runtime) + install(PROGRAMS + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/validate-release-manifest.py" + DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/tools" + COMPONENT Runtime) + + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE") + install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE" + DESTINATION "${CMAKE_INSTALL_DATADIR}/echoion/licenses" + RENAME Echoion-LICENSE + COMPONENT Runtime) + endif() endif() # Bundling and deployment helpers -include(GNUInstallDirs) - # Function to bundle Qt dependencies function(bundle_qt_dependencies target) if(NOT TARGET ${target}) @@ -269,24 +358,70 @@ if(BUILD_CORE AND TARGET EchoionCore) install_with_dependencies(EchoionCore) endif() -if(BUILD_PLUGIN AND TARGET EchoionPlugin) - install_with_dependencies(EchoionPlugin) +if(BUILD_TESTS AND UNIX) + add_test(NAME echoion_release_manifest_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-packaging.sh" + "${CMAKE_CURRENT_SOURCE_DIR}") + add_test(NAME echoion_runtime_dependency_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-runtime-dependencies.sh" + "${CMAKE_CURRENT_SOURCE_DIR}") + add_test(NAME echoion_release_archive_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-release-archive.sh" + "${CMAKE_CURRENT_SOURCE_DIR}") + add_test(NAME echoion_frontend_license_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test-frontend-licenses.sh" + "${CMAKE_CURRENT_SOURCE_DIR}") + add_test(NAME echoion_installer_packaging_tests + COMMAND bash + "${CMAKE_CURRENT_SOURCE_DIR}/packaging/tests/installer_test.sh") +endif() + +# The universal .tar.zst/.run workflow is the supported Linux distribution +# format. Keep legacy CPack available for local Windows/macOS experiments, +# without publishing inaccurate DEB/RPM host-dependency metadata. +option(ECHOION_ENABLE_LEGACY_CPACK "Enable legacy platform packaging" OFF) +if(ECHOION_ENABLE_LEGACY_CPACK) + set(CPACK_PACKAGE_NAME "Echoion") + set(CPACK_PACKAGE_VENDOR "Echoion") + set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Echoion Music Bot for TeamSpeak") + set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) + set(CPACK_RESOURCE_FILE_README "${CMAKE_CURRENT_SOURCE_DIR}/README.md") + if(WIN32) + set(CPACK_GENERATOR "ZIP;NSIS") + set(CPACK_NSIS_DISPLAY_NAME "Echoion Music Bot") + elseif(APPLE) + set(CPACK_GENERATOR "DragNDrop") + set(CPACK_DMG_VOLUME_NAME "Echoion") + else() + set(CPACK_GENERATOR "TGZ") + endif() + include(CPack) endif() # Print configuration summary message(STATUS "") message(STATUS "Echoion Configuration:") message(STATUS " Version: ${PROJECT_VERSION}") +if(DEFINED ECHOION_RUNTIME_VERSION) + message(STATUS " Runtime release version: ${ECHOION_RUNTIME_VERSION}") +endif() message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}") message(STATUS " Build API: ${BUILD_API}") +message(STATUS " Build first-party plugins: ${BUILD_FIRST_PARTY_PLUGINS}") message(STATUS " Build Core: ${BUILD_CORE}") -message(STATUS " Build Plugin: ${BUILD_PLUGIN}") message(STATUS " Build Desktop: ${BUILD_DESKTOP}") +message(STATUS " Build Web: ${BUILD_WEB}") +message(STATUS " Build Standalone: ${BUILD_STANDALONE}") message(STATUS " Build Tests: ${BUILD_TESTS}") message(STATUS " Static Link: ${ECHOION_STATIC_LINK}") +message(STATUS " Runtime install component: ${ECHOION_INSTALL_RUNTIME_BUNDLE}") message(STATUS "") message(STATUS "Install prefix: ${CMAKE_INSTALL_PREFIX}") message(STATUS "To build: cmake --build build") message(STATUS "To install: cmake --install build --prefix ") -message(STATUS "To package: cpack -G TGZ (or DEB, RPM, ZIP, NSIS)") +message(STATUS "To release: scripts/release.sh --version ") message(STATUS "") diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..359a3cb --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,54 @@ +{ + "version": 9, + "cmakeMinimumRequired": { + "major": 4, + "minor": 0, + "patch": 0 + }, + "configurePresets": [ + { + "name": "linux-release", + "displayName": "Linux dynamic runtime release", + "description": "Bot, Core, web dashboard, tests, and a runtime-only install component", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build-release", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_INSTALL_PREFIX": "${sourceDir}/build-release/stage", + "BUILD_SHARED_LIBS": "ON", + "ECHOION_STATIC_LINK": "OFF", + "ECHOION_INSTALL_RUNTIME_BUNDLE": "ON", + "ECHOION_ENABLE_LEGACY_CPACK": "OFF", + "ECHOION_ENABLE_LTO": "ON", + "BUILD_API": "ON", + "BUILD_CORE": "ON", + "BUILD_WEB": "ON", + "ECHOION_BUILD_WEB": "ON", + "BUILD_STANDALONE": "ON", + "BUILD_FIRST_PARTY_PLUGINS": "ON", + "BUILD_DESKTOP": "OFF", + "BUILD_TESTS": "ON" + } + } + ], + "buildPresets": [ + { + "name": "linux-release", + "configurePreset": "linux-release", + "configuration": "Release" + } + ], + "testPresets": [ + { + "name": "linux-release", + "configurePreset": "linux-release", + "configuration": "Release", + "output": { + "outputOnFailure": true + }, + "execution": { + "noTestsAction": "error" + } + } + ] +} diff --git a/EchoionApi b/EchoionApi index e7573fb..caac928 160000 --- a/EchoionApi +++ b/EchoionApi @@ -1 +1 @@ -Subproject commit e7573fbcd0b4778c347e6af865057200e35d3a64 +Subproject commit caac9289234fadfecf1c036fa50ce89c86eafcd2 diff --git a/EchoionCore b/EchoionCore index 5c036d9..7975f2b 160000 --- a/EchoionCore +++ b/EchoionCore @@ -1 +1 @@ -Subproject commit 5c036d91fb4666ba072137e839c448b03892270d +Subproject commit 7975f2b38e76c185f85e2d80a9777b8fbba065e5 diff --git a/EchoionHost/CMakeLists.txt b/EchoionHost/CMakeLists.txt new file mode 100644 index 0000000..6388601 --- /dev/null +++ b/EchoionHost/CMakeLists.txt @@ -0,0 +1,35 @@ +cmake_minimum_required(VERSION 4.0.0) +project(EchoionHost VERSION 1.0.0 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 new file mode 100644 index 0000000..3946d94 --- /dev/null +++ b/EchoionHost/include/echoion/host/CoreLoader.hpp @@ -0,0 +1,100 @@ +#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 new file mode 100644 index 0000000..77f891a --- /dev/null +++ b/EchoionHost/src/CoreLoader.cpp @@ -0,0 +1,585 @@ +#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/EchoionPlugin b/EchoionPlugin deleted file mode 160000 index 470ab50..0000000 --- a/EchoionPlugin +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 470ab507e16fcdf4dfd8ab8bdc385258979032ef diff --git a/EchoionProtocol/CMakeLists.txt b/EchoionProtocol/CMakeLists.txt deleted file mode 100644 index a8579cf..0000000 --- a/EchoionProtocol/CMakeLists.txt +++ /dev/null @@ -1,49 +0,0 @@ -# EchoionProtocol — reverse-engineered TeamSpeak 3/6 full-client voice protocol. -# -# Deliberately dependency-isolated: it knows nothing about Echoion::Api, Void or -# reflection. It links only OpenSSL (crypto), libopus (voice) and a vendored -# QuickLZ. This keeps it independently unit-testable and reusable, and lets it -# build with a plain C++20 toolchain even though the rest of Echoion needs -# C++26/reflection. - -cmake_minimum_required(VERSION 3.24) - -# Allow standalone configuration (own build) as well as add_subdirectory() from -# the Echoion root. -if(NOT DEFINED PROJECT_NAME) - project(EchoionProtocol LANGUAGES CXX) -endif() - -option(ECHOIONPROTOCOL_BUILD_TESTS "Build EchoionProtocol unit tests" OFF) - -find_package(OpenSSL REQUIRED) - -find_package(PkgConfig QUIET) -if(PkgConfig_FOUND) - pkg_check_modules(OPUS IMPORTED_TARGET opus) - # libsodium provides the raw Ed25519 point arithmetic the TS6 license chain - # (initivexpand2) needs; OpenSSL cannot do it. - pkg_check_modules(SODIUM REQUIRED IMPORTED_TARGET libsodium) -endif() - -file(GLOB ECHOIONPROTOCOL_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_library(EchoionProtocol STATIC ${ECHOIONPROTOCOL_SOURCES}) -add_library(Echoion::Protocol ALIAS EchoionProtocol) - -target_include_directories(EchoionProtocol - PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include") - -# This target is standalone C++20 on purpose — do not inherit the tree's C++26. -target_compile_features(EchoionProtocol PUBLIC cxx_std_20) - -target_link_libraries(EchoionProtocol PUBLIC OpenSSL::Crypto PkgConfig::SODIUM) -if(TARGET PkgConfig::OPUS) - target_link_libraries(EchoionProtocol PUBLIC PkgConfig::OPUS) - target_compile_definitions(EchoionProtocol PUBLIC ECHOION_HAVE_OPUS=1) -endif() - -if(ECHOIONPROTOCOL_BUILD_TESTS OR BUILD_TESTS) - enable_testing() - add_subdirectory(tests) -endif() diff --git a/EchoionProtocol/README.md b/EchoionProtocol/README.md deleted file mode 100644 index f6a6fda..0000000 --- a/EchoionProtocol/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# EchoionProtocol - -A native C++ implementation of the TeamSpeak 3/6 **full-client voice protocol**, -so Echoion can connect to a TeamSpeak server as its own client — no TeamSpeak -client and no plugin required. Ported from -[ts6-manager](https://github.com/clusterzx/ts6-manager)'s `tslib` (MIT) and -cross-checked against ReSpeak's protocol documentation. - -TeamSpeak 6 has **no WebRTC voice** — its voice is still the legacy TS3 UDP -protocol on port 9987, which this library speaks. - -## Modules - -| Module | Purpose | -|--------|---------| -| `Crypto` | AES-128-EAX (composed from AES-CTR + CMAC/OMAC1), per-packet key/nonce derivation, SHA hashes. **Byte-verified against RFC 4493 (CMAC) and the EAX spec test vectors.** | -| `Identity` | ECDSA P-256 identity, libtomcrypt public-key export ("omega"), uid, hashcash security-level. OpenSSL. | -| `License` | TS6 `initivexpand2` license chain — Ed25519 point arithmetic via libsodium. | -| `Command` | TS3 escaped `key=value` command serialization + notify parsing. | -| `QuickLz` | QuickLZ level-1 decompression for compressed command packets. | -| `TsClient` | UDP socket, handshake (`init0`–`init4` + RSA puzzle, `clientinitiv`, `initivexpand`/`initivexpand2`), per-packet crypto, ack/resend, keepalive, voice/whisper send, event callbacks. | - -## Dependencies - -OpenSSL (crypto), libsodium (Ed25519), libopus (only consumed by the host's -audio encoder, not this library). No Boost, no Void, no reflection — plain C++20, -independently buildable and testable. - -## Build & test standalone - -```bash -cmake -S . -B build -DECHOIONPROTOCOL_BUILD_TESTS=ON -cmake --build build -./build/tests/echoion_protocol_tests -``` - -## Verified - -- Unit tests: CMAC (RFC 4493), EAX (spec vectors), SHA-1, base64, command - escaping, QuickLZ, identity uid/security-level/sign, save/load. -- **Live handshake**: connects to a real TeamSpeak 3 server (Docker) through the - full handshake and appears in the server's client list. - -## Not yet integration-tested against a live server - -Audio audibility to a second client, whisper targeting, and inbound-command -event mapping are implemented but need a full end-to-end run with Core. diff --git a/EchoionProtocol/include/echoion/protocol/Command.hpp b/EchoionProtocol/include/echoion/protocol/Command.hpp deleted file mode 100644 index 9238eba..0000000 --- a/EchoionProtocol/include/echoion/protocol/Command.hpp +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -// TS3 command wire format: "commandname key=value key=value|key=value". -// Ported from ts6-manager tslib/commands.ts. - -#include -#include -#include - -namespace Echoion::Protocol -{ - - // Escape / unescape a single token per the TS3 rules - // (\\ \/ \s \p \f \n \r \t \v). - std::string tsEscape(const std::string& str); - std::string tsUnescape(const std::string& str); - - // Ordered key/value params for a command. std::map keeps a stable order so - // serialization is deterministic (helpful for tests); the server does not - // care about ordering. - using CommandParams = std::map; - - struct ParsedCommand { - std::string name; - CommandParams params; // first group - std::vector groups; // all '|'-separated groups - }; - - // Serialize "name k=v k=v". Empty values are emitted as "k=". - std::string buildCommand(const std::string& name, - const CommandParams& params); - - // Parse a raw command / notify line into name + params (+ pipe groups). - ParsedCommand parseCommand(const std::string& raw); - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/include/echoion/protocol/Crypto.hpp b/EchoionProtocol/include/echoion/protocol/Crypto.hpp deleted file mode 100644 index c399691..0000000 --- a/EchoionProtocol/include/echoion/protocol/Crypto.hpp +++ /dev/null @@ -1,88 +0,0 @@ -#pragma once - -// Low-level cryptographic primitives for the TeamSpeak 3/6 full-client voice -// protocol. Ported byte-for-byte from ts6-manager's tslib/crypto.ts (MIT) so the -// on-wire behaviour is identical; implemented over OpenSSL EVP. -// -// The protocol uses AES-128-EAX for per-packet authenticated encryption. OpenSSL -// has no native EAX, so — exactly like the reference — we compose it from -// AES-128-CTR (confidentiality) and AES-128-CMAC / OMAC1 (authenticity). - -#include -#include -#include -#include -#include -#include - -namespace Echoion::Protocol::Crypto -{ - - using Bytes = std::vector; - using ByteView = std::span; - - inline constexpr size_t BLOCK_SIZE = 16; - inline constexpr size_t MAC_LEN = 8; - - // "TS3INIT1" — the fake/static MAC stamped on low-level init packets before a - // shared secret exists. - inline constexpr std::array INIT_MAC = {'T', 'S', '3', 'I', - 'N', 'I', 'T', '1'}; - - // "c:\\windows\\syste" / "m\\firewall32.cpl" — the fixed key/nonce used to - // (de)crypt command packets during the handshake, before key exchange. - inline constexpr std::array DUMMY_KEY = { - 'c', ':', '\\', 'w', 'i', 'n', 'd', 'o', - 'w', 's', '\\', 's', 'y', 's', 't', 'e'}; - inline constexpr std::array DUMMY_NONCE = { - 'm', '\\', 'f', 'i', 'r', 'e', 'w', 'a', - 'l', 'l', '3', '2', '.', 'c', 'p', 'l'}; - - // Client version signature used in clientinit (3.5.0 [Stable]). - inline constexpr uint32_t INIT_VERSION = 1566914096u; - - // --- Hashes ------------------------------------------------------------- - std::array sha1(ByteView data); - std::array sha256(ByteView data); - std::array sha512(ByteView data); - - // --- XOR helpers -------------------------------------------------------- - // out[i] = a[i] ^ b[i] for i in [0, min(a,b)). - Bytes xorBuffers(ByteView a, ByteView b); - // a[i] ^= b[i] for i in [0, len). Caller guarantees bounds. - void xorInto(std::span a, ByteView b, size_t len); - - // --- AES-128-CMAC (OMAC1) ---------------------------------------------- - // 16-byte MAC over `data` under the 16-byte `key`. - std::array cmac(ByteView key, ByteView data); - - // --- AES-128-EAX -------------------------------------------------------- - struct EaxResult { - Bytes ciphertext; - std::array mac; - }; - // Encrypt `plaintext` with 16-byte `key`, `nonce` and associated `header`. - EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header, - ByteView plaintext); - // Decrypt/verify; returns nullopt on MAC mismatch. - std::optional eaxDecrypt(ByteView key, ByteView nonce, - ByteView header, ByteView ciphertext, - ByteView mac); - - // --- Per-packet key/nonce derivation ----------------------------------- - struct KeyNonce { - std::array key; - std::array nonce; - }; - // Derive the packet key+nonce from the connection `ivStruct` (20 bytes for - // the SHA1 handshake secret, 64 bytes for the license path), keyed by - // direction, packet id, generation and packet type. - KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId, - uint32_t generationId, uint8_t packetType, - ByteView ivStruct); - - // --- Misc --------------------------------------------------------------- - // base64(sha1(utf8(password))); empty string for empty password. - std::string hashPassword(const std::string& password); - -} // namespace Echoion::Protocol::Crypto diff --git a/EchoionProtocol/include/echoion/protocol/Identity.hpp b/EchoionProtocol/include/echoion/protocol/Identity.hpp deleted file mode 100644 index 1a58bf4..0000000 --- a/EchoionProtocol/include/echoion/protocol/Identity.hpp +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -// TeamSpeak client identity: an ECDSA P-256 keypair plus the libtomcrypt-style -// public-key export ("omega"), the derived unique-id, and the hashcash -// key-offset that raises the identity's "security level". -// Ported from ts6-manager tslib/identity.ts. - -#include -#include -#include -#include -#include - -namespace Echoion::Protocol -{ - - class Identity - { - public: - - using Bytes = std::vector; - using ByteView = std::span; - - // Generate a fresh identity and raise it to at least `securityLevel` - // leading-zero bits (hashcash over the public key + offset). - static Identity generate(int securityLevel = 8); - - // Load / save the identity to a small text file: - // privateKeyPem, publicKeyString, keyOffset (one per line). - static Identity load(const std::string& path); - void save(const std::string& path) const; - - // libtomcrypt ASN.1 public key, base64 ("omega" in clientinitiv). - const std::string& publicKeyString() const { return publicKeyString_; } - // base64(sha1(ascii(publicKeyString))). - const std::string& uid() const { return uid_; } - uint64_t keyOffset() const { return keyOffset_; } - int securityLevel() const; - - // ECDSA sign `data` with SHA-256; returns the raw signature. - Bytes sign(ByteView data) const; - - // ECDH(this private key, server public key) → SHA-1 of the shared - // x-coordinate. `serverPublicKeyDer` is the libtomcrypt DER blob - // (base64-decoded "omega" from initivexpand). - Bytes sharedSecret(ByteView serverPublicKeyDer) const; - - private: - - Identity() = default; - - struct PKeyDeleter { - void operator()(void* p) const noexcept; - }; - // EVP_PKEY* held opaquely so this header stays OpenSSL-free. - std::shared_ptr pkey_; - std::string publicKeyString_; - std::string uid_; - uint64_t keyOffset_ = 0; - }; - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/include/echoion/protocol/License.hpp b/EchoionProtocol/include/echoion/protocol/License.hpp deleted file mode 100644 index 4891655..0000000 --- a/EchoionProtocol/include/echoion/protocol/License.hpp +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once - -// TeamSpeak license chain handling for the modern handshake (initivexpand2). -// The chain is walked with Ed25519 point arithmetic (scalar-mult + point-add), -// which OpenSSL does not expose, so this module uses libsodium. -// Ported from ts6-manager tslib/license.ts. - -#include -#include -#include -#include - -namespace Echoion::Protocol -{ - - using Bytes = std::vector; - using ByteView = std::span; - - struct LicenseBlock { - std::array key; - std::array hash; // first 32 bytes of SHA-512(content) - uint8_t type = 0; - }; - - struct TempKey { - std::array publicKey; - std::array privateKey; - }; - - // Parse the server license blob into its chain of blocks. - std::vector parseLicense(ByteView data); - - // Walk the chain from the root key to the final server public key (32 bytes). - std::array - deriveLicenseKey(const std::vector& blocks); - - // Generate an ephemeral Ed25519 keypair (clamped like the reference). - TempKey generateTemporaryKey(); - - // initivexpand2 shared secret: SHA-512( tempPriv * serverDerivedKey ), - // 64 bytes. Returns the raw digest. - std::array - getSharedSecret2(ByteView serverDerivedKey, ByteView tempPrivateKey); - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/include/echoion/protocol/QuickLz.hpp b/EchoionProtocol/include/echoion/protocol/QuickLz.hpp deleted file mode 100644 index dda4429..0000000 --- a/EchoionProtocol/include/echoion/protocol/QuickLz.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -// QuickLZ level-1 decompression, used to inflate compressed command packets. -// Clients send commands uncompressed, so only decompression is needed. -// Ported from ts6-manager tslib/quicklz.ts (itself from TSLib QuickerLz.cs). - -#include -#include -#include - -namespace Echoion::Protocol -{ - - using Bytes = std::vector; - using ByteView = std::span; - - uint32_t qlzDecompressedSize(ByteView data); - uint32_t qlzCompressedSize(ByteView data); - - // Throws std::runtime_error on malformed input or unsupported level. - Bytes qlzDecompress(ByteView data); - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/include/echoion/protocol/TsClient.hpp b/EchoionProtocol/include/echoion/protocol/TsClient.hpp deleted file mode 100644 index 704aa1b..0000000 --- a/EchoionProtocol/include/echoion/protocol/TsClient.hpp +++ /dev/null @@ -1,195 +0,0 @@ -#pragma once - -// Full-client connection to a TeamSpeak 3/6 server over the native UDP voice -// protocol. Owns the socket, handshake, per-packet crypto, resend/keepalive and -// voice send path. Ported from ts6-manager tslib/client.ts. -// -// Threading: a single background thread runs the receive + timer loop. Public -// send methods are thread-safe (guarded by an internal mutex) so the audio -// thread can call sendVoice() directly. Callbacks fire on the loop thread. - -#include "echoion/protocol/Command.hpp" -#include "echoion/protocol/Identity.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Echoion::Protocol -{ - - enum class PacketType : uint8_t { - Voice = 0, - VoiceWhisper = 1, - Command = 2, - CommandLow = 3, - Ping = 4, - Pong = 5, - Ack = 6, - AckLow = 7, - Init1 = 8, - }; - - enum class ClientState { - Disconnected, - Init, - Handshake, - Connected, - Disconnecting, - }; - - struct TsClientOptions { - std::string host; - uint16_t port = 9987; - const Identity* identity = nullptr; // not owned - std::string nickname = "EchoionBot"; - std::string serverPassword; - std::string defaultChannel; // channel id or name - std::string channelPassword; - }; - - // All callbacks fire on the internal loop thread. - struct TsClientCallbacks { - std::function onConnected; - std::function onDisconnected; - std::function onError; - std::function onCommand; - std::function onTextMessage; - std::function)> onVoice; - std::function onDebug; - }; - - class TsClient - { - public: - - TsClient(); - ~TsClient(); - - TsClient(const TsClient&) = delete; - TsClient& operator=(const TsClient&) = delete; - - void setCallbacks(TsClientCallbacks cb) { cb_ = std::move(cb); } - - // Begin connecting. Returns immediately; onConnected/onError fire - // asynchronously. Throws only on immediate socket setup failure. - void connect(const TsClientOptions& opts); - // Graceful: send clientdisconnect, then close. - void disconnect(); - // Immediate close, no disconnect command. - void forceClose(); - - ClientState state() const { return state_.load(); } - uint16_t clientId() const { return clientId_.load(); } - - // Send one already-Opus-encoded 20 ms frame to the current channel. - void sendVoice(std::span opus); - // Whisper the frame to the given channel/client targets. - void sendWhisper(std::span opus, - const std::vector& channelIds, - const std::vector& clientIds); - // End-of-voice marker (empty frame). - void sendVoiceStop(); - - // Send a raw pre-built TS3 command line (fragmented if large). - void sendCommand(const std::string& cmd); - - private: - - // ---- packet path ---- - void loopThread(); - void handleIncomingPacket(std::span raw); - void sendOutgoing(std::span data, PacketType type, - uint8_t extraFlags = 0); - std::vector buildRawPacket(std::span data, - PacketType type, - uint16_t packetId, - uint8_t flags); - void encryptPacket(std::vector& raw, PacketType type, - uint16_t packetId, uint32_t gen, uint8_t flags, - std::span data); - std::vector decryptPacket(std::span raw, - PacketType type, - uint16_t packetId, uint32_t gen, - uint8_t flags, bool& ok); - void sendRawLocked(const std::vector& raw); - void sendInitPacket(const std::vector& data); - - // ---- handshake / commands ---- - std::vector buildInit0(); - void handleInit(std::span data); - void handleCommandData(std::span data, uint8_t flags); - void processCommand(std::span data, uint8_t flags); - void handleInitIvExpand(const CommandParams& params); - void handleInitIvExpand2(const CommandParams& params); - void sendClientInit(); - void handleInitServer(const CommandParams& params); - void handleChannelList(const ParsedCommand& parsed); - void handleChannelListFinished(); - - void sendAck(uint16_t ackId, PacketType ackType); - void handlePing(uint16_t packetId); - void resendTick(); - void debug(const std::string& msg); - void cleanup(); - - // counters / crypto - struct Counter { - uint16_t id = 0; - uint32_t gen = 0; - }; - Counter getCounter(PacketType type); - void incCounter(PacketType type); - - TsClientOptions opts_; - TsClientCallbacks cb_; - - int sock_ = -1; - std::atomic state_{ClientState::Disconnected}; - std::atomic clientId_{0}; - - std::thread thread_; - std::atomic running_{false}; - // Recursive: command handlers running under the loop lock call - // sendCommand()/sendOutgoing() which re-lock. - mutable std::recursive_mutex mu_; - int64_t disconnectDeadline_ = 0; - - std::array packetCounter_{}; - std::array generationCounter_{}; - - bool cryptoInitComplete_ = false; - std::vector ivStruct_; - std::array fakeSignature_{}; - std::vector alphaTmp_; - - // resend tracking - struct Resend { - std::vector raw; - uint16_t packetId = 0; - int64_t firstSend = 0; - int64_t lastSend = 0; - }; - std::map resendMap_; - std::unique_ptr initResend_; - int64_t lastMessageTime_ = 0; - int64_t lastPing_ = 0; - int64_t connectStart_ = 0; - - // fragment reassembly - std::vector fragmentBuffer_; - bool fragmenting_ = false; - uint8_t fragmentFlags_ = 0; - - // channel map for auto-move - std::map channelMap_; - }; - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/include/echoion/protocol/Util.hpp b/EchoionProtocol/include/echoion/protocol/Util.hpp deleted file mode 100644 index 7a6125f..0000000 --- a/EchoionProtocol/include/echoion/protocol/Util.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -// Small dependency-free encoding helpers shared across the protocol modules. - -#include -#include -#include -#include - -namespace Echoion::Protocol::Util -{ - - using Bytes = std::vector; - using ByteView = std::span; - - // Standard base64 (RFC 4648) with '+' '/' and '=' padding. - std::string base64Encode(ByteView data); - Bytes base64Decode(const std::string& text); - - // Lowercase hex, no separators. - std::string toHex(ByteView data); - Bytes fromHex(const std::string& hex); - -} // namespace Echoion::Protocol::Util diff --git a/EchoionProtocol/src/Command.cpp b/EchoionProtocol/src/Command.cpp deleted file mode 100644 index 6b77518..0000000 --- a/EchoionProtocol/src/Command.cpp +++ /dev/null @@ -1,184 +0,0 @@ -#include "echoion/protocol/Command.hpp" - -#include -#include - -namespace Echoion::Protocol -{ - - std::string tsEscape(const std::string& str) - { - std::string out; - out.reserve(str.size()); - for (char c : str) { - switch (c) { - case '\\': - out += "\\\\"; - break; - case '/': - out += "\\/"; - break; - case ' ': - out += "\\s"; - break; - case '|': - out += "\\p"; - break; - case '\f': - out += "\\f"; - break; - case '\n': - out += "\\n"; - break; - case '\r': - out += "\\r"; - break; - case '\t': - out += "\\t"; - break; - case '\v': - out += "\\v"; - break; - default: - out.push_back(c); - } - } - return out; - } - - std::string tsUnescape(const std::string& str) - { - std::string out; - out.reserve(str.size()); - for (size_t i = 0; i < str.size(); ++i) { - if (str[i] == '\\') { - if (++i >= str.size()) { - throw std::runtime_error("invalid escape sequence"); - } - switch (str[i]) { - case '\\': - out.push_back('\\'); - break; - case '/': - out.push_back('/'); - break; - case 's': - out.push_back(' '); - break; - case 'p': - out.push_back('|'); - break; - case 'f': - out.push_back('\f'); - break; - case 'n': - out.push_back('\n'); - break; - case 'r': - out.push_back('\r'); - break; - case 't': - out.push_back('\t'); - break; - case 'v': - out.push_back('\v'); - break; - default: - throw std::runtime_error(std::string("unknown escape: \\") + - str[i]); - } - } else { - out.push_back(str[i]); - } - } - return out; - } - - std::string buildCommand(const std::string& name, - const CommandParams& params) - { - std::string cmd = tsEscape(name); - for (const auto& [key, value] : params) { - cmd += ' '; - cmd += key; - cmd += '='; - cmd += tsEscape(value); - } - return cmd; - } - - namespace - { - CommandParams parseGroup(const std::string& part) - { - CommandParams params; - std::istringstream iss(part); - std::string token; - while (std::getline(iss, token, ' ')) { - if (token.empty()) { - continue; - } - auto eq = token.find('='); - if (eq != std::string::npos) { - params[token.substr(0, eq)] = - tsUnescape(token.substr(eq + 1)); - } else { - params[token] = ""; - } - } - return params; - } - - std::string trim(const std::string& s) - { - size_t a = s.find_first_not_of(" \t\r\n"); - if (a == std::string::npos) { - return ""; - } - size_t b = s.find_last_not_of(" \t\r\n"); - return s.substr(a, b - a + 1); - } - } // namespace - - ParsedCommand parseCommand(const std::string& raw) - { - // Split on '|' into groups. - std::vector parts; - { - std::string cur; - for (char c : raw) { - if (c == '|') { - parts.push_back(cur); - cur.clear(); - } else { - cur.push_back(c); - } - } - parts.push_back(cur); - } - - ParsedCommand out; - std::string first = trim(parts[0]); - - // The command name is the first whitespace-delimited token. - std::string body; - auto sp = first.find(' '); - if (sp == std::string::npos) { - out.name = tsUnescape(first); - body = ""; - } else { - out.name = tsUnescape(first.substr(0, sp)); - body = first.substr(sp + 1); - } - out.params = parseGroup(body); - - if (parts.size() > 1) { - out.groups.push_back(out.params); - for (size_t g = 1; g < parts.size(); ++g) { - out.groups.push_back(parseGroup(trim(parts[g]))); - } - } - return out; - } - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/src/Crypto.cpp b/EchoionProtocol/src/Crypto.cpp deleted file mode 100644 index 362574c..0000000 --- a/EchoionProtocol/src/Crypto.cpp +++ /dev/null @@ -1,249 +0,0 @@ -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/Util.hpp" - -#include -#include - -#include -#include - -namespace Echoion::Protocol::Crypto -{ - namespace - { - // Raw single-block AES-128-ECB encryption (no padding). Used to build - // CMAC; matches the reference's aesEncryptBlock(). - std::array aesEncryptBlock( - ByteView key, std::span block) - { - EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); - if (!ctx) { - throw std::runtime_error("EVP_CIPHER_CTX_new failed"); - } - std::array out{}; - int len = 0; - if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), nullptr, key.data(), - nullptr) != 1 || - EVP_CIPHER_CTX_set_padding(ctx, 0) != 1 || - EVP_EncryptUpdate(ctx, out.data(), &len, block.data(), - static_cast(BLOCK_SIZE)) != 1) { - EVP_CIPHER_CTX_free(ctx); - throw std::runtime_error("AES-ECB block encrypt failed"); - } - EVP_CIPHER_CTX_free(ctx); - return out; - } - - // GF(2^128) left-shift-by-one with the 0x87 reduction polynomial. - std::array doubleBlock( - const std::array& buf) - { - std::array out{}; - uint8_t carry = 0; - for (int i = BLOCK_SIZE - 1; i >= 0; --i) { - uint16_t tmp = static_cast((buf[i] << 1) | carry); - out[i] = static_cast(tmp & 0xff); - carry = (buf[i] >> 7) & 1; - } - if (carry) { - out[BLOCK_SIZE - 1] ^= 0x87; - } - return out; - } - - // EAX OMAC over a tag byte prepended in a leading block, then `data`. - std::array eaxOmac(ByteView key, uint8_t tag, - ByteView data) - { - Bytes input(BLOCK_SIZE + data.size(), 0); - input[BLOCK_SIZE - 1] = tag; - std::memcpy(input.data() + BLOCK_SIZE, data.data(), data.size()); - return cmac(key, input); - } - - // AES-128-CTR keystream applied to `in`, IV = `nonce`. - Bytes aesCtr(ByteView key, std::span nonce, - ByteView in) - { - EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); - if (!ctx) { - throw std::runtime_error("EVP_CIPHER_CTX_new failed"); - } - Bytes out(in.size(), 0); - int len = 0; - int total = 0; - if (EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), nullptr, key.data(), - nonce.data()) != 1 || - EVP_EncryptUpdate(ctx, out.data(), &len, in.data(), - static_cast(in.size())) != 1) { - EVP_CIPHER_CTX_free(ctx); - throw std::runtime_error("AES-CTR failed"); - } - total = len; - if (EVP_EncryptFinal_ex(ctx, out.data() + total, &len) != 1) { - EVP_CIPHER_CTX_free(ctx); - throw std::runtime_error("AES-CTR final failed"); - } - EVP_CIPHER_CTX_free(ctx); - out.resize(static_cast(total) + len); - return out; - } - } // namespace - - std::array sha1(ByteView data) - { - std::array out{}; - ::SHA1(data.data(), data.size(), out.data()); - return out; - } - - std::array sha256(ByteView data) - { - std::array out{}; - ::SHA256(data.data(), data.size(), out.data()); - return out; - } - - std::array sha512(ByteView data) - { - std::array out{}; - ::SHA512(data.data(), data.size(), out.data()); - return out; - } - - Bytes xorBuffers(ByteView a, ByteView b) - { - size_t len = std::min(a.size(), b.size()); - Bytes out(len, 0); - for (size_t i = 0; i < len; ++i) { - out[i] = a[i] ^ b[i]; - } - return out; - } - - void xorInto(std::span a, ByteView b, size_t len) - { - for (size_t i = 0; i < len; ++i) { - a[i] ^= b[i]; - } - } - - std::array cmac(ByteView key, ByteView data) - { - const std::array zero{}; - auto L = aesEncryptBlock(key, std::span( - zero.data(), BLOCK_SIZE)); - auto K1 = doubleBlock(L); - auto K2 = doubleBlock(K1); - - const size_t n = data.size(); - const size_t numBlocks = n == 0 ? 1 : (n + BLOCK_SIZE - 1) / BLOCK_SIZE; - const bool lastComplete = n > 0 && n % BLOCK_SIZE == 0; - - std::array x{}; - for (size_t i = 0; i + 1 < numBlocks; ++i) { - std::array block{}; - std::memcpy(block.data(), data.data() + i * BLOCK_SIZE, BLOCK_SIZE); - for (size_t j = 0; j < BLOCK_SIZE; ++j) { - block[j] ^= x[j]; - } - x = aesEncryptBlock(key, std::span( - block.data(), BLOCK_SIZE)); - } - - std::array last{}; - const size_t off = (numBlocks - 1) * BLOCK_SIZE; - if (lastComplete) { - std::memcpy(last.data(), data.data() + off, BLOCK_SIZE); - for (size_t j = 0; j < BLOCK_SIZE; ++j) { - last[j] ^= K1[j]; - } - } else { - const size_t rem = n - off; - std::memcpy(last.data(), data.data() + off, rem); - last[rem] = 0x80; - for (size_t j = 0; j < BLOCK_SIZE; ++j) { - last[j] ^= K2[j]; - } - } - for (size_t j = 0; j < BLOCK_SIZE; ++j) { - last[j] ^= x[j]; - } - return aesEncryptBlock(key, std::span( - last.data(), BLOCK_SIZE)); - } - - EaxResult eaxEncrypt(ByteView key, ByteView nonce, ByteView header, - ByteView plaintext) - { - auto N = eaxOmac(key, 0, nonce); - auto H = eaxOmac(key, 1, header); - Bytes ciphertext = aesCtr( - key, std::span(N.data(), BLOCK_SIZE), - plaintext); - auto C = eaxOmac(key, 2, ciphertext); - - EaxResult res; - res.ciphertext = std::move(ciphertext); - for (size_t i = 0; i < MAC_LEN; ++i) { - res.mac[i] = N[i] ^ H[i] ^ C[i]; - } - return res; - } - - std::optional eaxDecrypt(ByteView key, ByteView nonce, - ByteView header, ByteView ciphertext, - ByteView mac) - { - auto N = eaxOmac(key, 0, nonce); - auto H = eaxOmac(key, 1, header); - auto C = eaxOmac(key, 2, ciphertext); - - std::array tag{}; - uint8_t diff = 0; - for (size_t i = 0; i < MAC_LEN; ++i) { - tag[i] = N[i] ^ H[i] ^ C[i]; - diff |= static_cast(tag[i] ^ (i < mac.size() ? mac[i] : 0)); - } - if (diff != 0 || mac.size() < MAC_LEN) { - return std::nullopt; - } - return aesCtr(key, - std::span(N.data(), BLOCK_SIZE), - ciphertext); - } - - KeyNonce deriveKeyNonce(bool fromServer, uint16_t packetId, - uint32_t generationId, uint8_t packetType, - ByteView ivStruct) - { - const size_t tmpLen = ivStruct.size() == 20 ? 26 : 70; - Bytes tmp(tmpLen, 0); - tmp[0] = fromServer ? 0x30 : 0x31; - tmp[1] = packetType; - tmp[2] = static_cast((generationId >> 24) & 0xff); - tmp[3] = static_cast((generationId >> 16) & 0xff); - tmp[4] = static_cast((generationId >> 8) & 0xff); - tmp[5] = static_cast(generationId & 0xff); - std::memcpy(tmp.data() + 6, ivStruct.data(), ivStruct.size()); - - auto kn = sha256(tmp); - KeyNonce out; - std::memcpy(out.key.data(), kn.data(), 16); - std::memcpy(out.nonce.data(), kn.data() + 16, 16); - out.key[0] ^= static_cast((packetId >> 8) & 0xff); - out.key[1] ^= static_cast(packetId & 0xff); - return out; - } - - std::string hashPassword(const std::string& password) - { - if (password.empty()) { - return ""; - } - auto digest = sha1(ByteView( - reinterpret_cast(password.data()), password.size())); - return Util::base64Encode(ByteView(digest.data(), digest.size())); - } - -} // namespace Echoion::Protocol::Crypto diff --git a/EchoionProtocol/src/Identity.cpp b/EchoionProtocol/src/Identity.cpp deleted file mode 100644 index 9359b1d..0000000 --- a/EchoionProtocol/src/Identity.cpp +++ /dev/null @@ -1,426 +0,0 @@ -#include "echoion/protocol/Identity.hpp" -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/Util.hpp" - -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace Echoion::Protocol -{ - namespace - { - using Bytes = std::vector; - - [[noreturn]] void fail(const char* what) - { - throw std::runtime_error(std::string("Identity: ") + what); - } - - EVP_PKEY* asPkey(const std::shared_ptr& p) - { - return static_cast(p.get()); - } - - // Minimal big-endian encoding of a BIGNUM (no leading zeros). - Bytes bnBytes(const BIGNUM* bn) - { - int n = BN_num_bytes(bn); - Bytes out(static_cast(n < 0 ? 0 : n), 0); - if (n > 0) { - BN_bn2bin(bn, out.data()); - } - return out; - } - - Bytes derLength(size_t len) - { - if (len < 0x80) { - return {static_cast(len)}; - } - if (len < 0x100) { - return {0x81, static_cast(len)}; - } - return {0x82, static_cast((len >> 8) & 0xff), - static_cast(len & 0xff)}; - } - - // DER INTEGER from a non-negative big-endian magnitude. - Bytes derInteger(Bytes mag) - { - if (mag.empty()) { - mag.push_back(0); - } - if (mag[0] & 0x80) { - mag.insert(mag.begin(), 0x00); - } - Bytes out; - out.push_back(0x02); - Bytes len = derLength(mag.size()); - out.insert(out.end(), len.begin(), len.end()); - out.insert(out.end(), mag.begin(), mag.end()); - return out; - } - - Bytes derIntegerFromU64(uint64_t v) - { - BIGNUM* bn = BN_new(); - BN_set_word(bn, v); - Bytes r = derInteger(bnBytes(bn)); - BN_free(bn); - return r; - } - - // libtomcrypt public key: SEQ{ BITSTRING(00 07 00), INT(32), INT(x), - // INT(y) }. The BITSTRING carries a leading "unused bits" byte (0x00) - // plus 0x07 0x00 in the reference; we reproduce it verbatim. - std::string buildPublicKeyString(const BIGNUM* x, const BIGNUM* y) - { - Bytes content; - const uint8_t bitStr[] = {0x03, 0x02, 0x07, 0x00}; - content.insert(content.end(), std::begin(bitStr), std::end(bitStr)); - Bytes i32 = derIntegerFromU64(32); - Bytes ix = derInteger(bnBytes(x)); - Bytes iy = derInteger(bnBytes(y)); - content.insert(content.end(), i32.begin(), i32.end()); - content.insert(content.end(), ix.begin(), ix.end()); - content.insert(content.end(), iy.begin(), iy.end()); - - Bytes der; - der.push_back(0x30); - Bytes len = derLength(content.size()); - der.insert(der.end(), len.begin(), len.end()); - der.insert(der.end(), content.begin(), content.end()); - return Util::base64Encode(Crypto::ByteView(der.data(), der.size())); - } - - // Uncompressed EC point (0x04 || x || y) from a public EVP_PKEY. - Bytes pubPoint(EVP_PKEY* pkey) - { - size_t len = 0; - if (EVP_PKEY_get_octet_string_param( - pkey, OSSL_PKEY_PARAM_PUB_KEY, nullptr, 0, &len) != 1) { - fail("cannot read public point length"); - } - Bytes buf(len, 0); - if (EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY, - buf.data(), len, &len) != 1) { - fail("cannot read public point"); - } - buf.resize(len); - return buf; - } - - int countLeadingZeroBits(Crypto::ByteView data) - { - int count = 0; - for (uint8_t b : data) { - if (b == 0) { - count += 8; - } else { - for (int bit = 0; bit < 8; ++bit) { - if ((b & (1 << bit)) == 0) { - ++count; - } else { - return count; - } - } - } - } - return count; - } - - int securityLevelFor(const std::string& pubKeyString, uint64_t offset) - { - std::string s = pubKeyString + std::to_string(offset); - auto h = Crypto::sha1(Crypto::ByteView( - reinterpret_cast(s.data()), s.size())); - return countLeadingZeroBits( - Crypto::ByteView(h.data(), h.size())); - } - - // libtomcrypt DER parse → the two public-key INTEGERs (x, y). See - // reference parseDerSequence: collected = [bitByte, 32, x, y]. - void parseServerPub(Crypto::ByteView der, BIGNUM** x, BIGNUM** y) - { - size_t pos = 0; - auto readLen = [&](size_t& p) -> size_t { - uint8_t first = der[p++]; - if (first < 0x80) { - return first; - } - int nb = first & 0x7f; - size_t len = 0; - for (int i = 0; i < nb; ++i) { - len = (len << 8) | der[p++]; - } - return len; - }; - if (der.empty() || der[pos++] != 0x30) { - fail("server key: expected SEQUENCE"); - } - readLen(pos); - std::vector ints; - while (pos < der.size()) { - uint8_t tag = der[pos++]; - size_t len = readLen(pos); - if (tag == 0x02) { - ints.push_back( - BN_bin2bn(der.data() + pos, static_cast(len), - nullptr)); - } - pos += len; - } - // ints = [32, x, y]; guard against short input. - if (ints.size() < 3) { - for (auto* b : ints) { - BN_free(b); - } - fail("server key: too few integers"); - } - *x = ints[1]; - *y = ints[2]; - for (size_t i = 0; i < ints.size(); ++i) { - if (i != 1 && i != 2) { - BN_free(ints[i]); - } - } - } - } // namespace - - void Identity::PKeyDeleter::operator()(void* p) const noexcept - { - EVP_PKEY_free(static_cast(p)); - } - - Identity Identity::generate(int securityLevel) - { - EVP_PKEY* pkey = nullptr; - EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr); - if (!ctx) { - fail("keygen ctx"); - } - if (EVP_PKEY_keygen_init(ctx) != 1) { - EVP_PKEY_CTX_free(ctx); - fail("keygen init"); - } - OSSL_PARAM params[2] = { - OSSL_PARAM_construct_utf8_string( - OSSL_PKEY_PARAM_GROUP_NAME, - const_cast("prime256v1"), 0), - OSSL_PARAM_construct_end()}; - EVP_PKEY_CTX_set_params(ctx, params); - if (EVP_PKEY_keygen(ctx, &pkey) != 1) { - EVP_PKEY_CTX_free(ctx); - fail("keygen"); - } - EVP_PKEY_CTX_free(ctx); - - Identity id; - id.pkey_ = std::shared_ptr(pkey, PKeyDeleter{}); - - Bytes point = pubPoint(pkey); - if (point.size() != 65 || point[0] != 0x04) { - fail("unexpected public point format"); - } - BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr); - BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr); - id.publicKeyString_ = buildPublicKeyString(x, y); - BN_free(x); - BN_free(y); - - auto uidHash = Crypto::sha1(Crypto::ByteView( - reinterpret_cast(id.publicKeyString_.data()), - id.publicKeyString_.size())); - id.uid_ = Util::base64Encode( - Crypto::ByteView(uidHash.data(), uidHash.size())); - - // Hashcash: find the offset giving the most leading-zero bits, up to - // the requested level. - if (securityLevel > 0) { - uint64_t offset = 0; - int best = securityLevelFor(id.publicKeyString_, offset); - uint64_t checked = 0; - while (best < securityLevel) { - ++checked; - int curr = securityLevelFor(id.publicKeyString_, checked); - if (curr > best) { - best = curr; - offset = checked; - } - } - id.keyOffset_ = offset; - } - return id; - } - - int Identity::securityLevel() const - { - return securityLevelFor(publicKeyString_, keyOffset_); - } - - Identity::Bytes Identity::sign(ByteView data) const - { - EVP_PKEY* pkey = asPkey(pkey_); - EVP_MD_CTX* md = EVP_MD_CTX_new(); - if (!md) { - fail("sign ctx"); - } - size_t siglen = 0; - if (EVP_DigestSignInit(md, nullptr, EVP_sha256(), nullptr, pkey) != 1 || - EVP_DigestSign(md, nullptr, &siglen, data.data(), data.size()) != - 1) { - EVP_MD_CTX_free(md); - fail("sign init"); - } - Bytes sig(siglen, 0); - if (EVP_DigestSign(md, sig.data(), &siglen, data.data(), data.size()) != - 1) { - EVP_MD_CTX_free(md); - fail("sign"); - } - sig.resize(siglen); - EVP_MD_CTX_free(md); - return sig; - } - - Identity::Bytes Identity::sharedSecret(ByteView serverPublicKeyDer) const - { - BIGNUM* x = nullptr; - BIGNUM* y = nullptr; - parseServerPub(serverPublicKeyDer, &x, &y); - - // Build uncompressed point 0x04 || x(32) || y(32). - Bytes point(65, 0); - point[0] = 0x04; - BN_bn2binpad(x, point.data() + 1, 32); - BN_bn2binpad(y, point.data() + 33, 32); - BN_free(x); - BN_free(y); - - EVP_PKEY* peer = nullptr; - { - OSSL_PARAM_BLD* bld = OSSL_PARAM_BLD_new(); - OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME, - "prime256v1", 0); - OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY, - point.data(), point.size()); - OSSL_PARAM* p = OSSL_PARAM_BLD_to_param(bld); - EVP_PKEY_CTX* pctx = - EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr); - if (!pctx || EVP_PKEY_fromdata_init(pctx) != 1 || - EVP_PKEY_fromdata(pctx, &peer, EVP_PKEY_PUBLIC_KEY, p) != 1) { - if (pctx) { - EVP_PKEY_CTX_free(pctx); - } - OSSL_PARAM_free(p); - OSSL_PARAM_BLD_free(bld); - fail("build peer key"); - } - EVP_PKEY_CTX_free(pctx); - OSSL_PARAM_free(p); - OSSL_PARAM_BLD_free(bld); - } - - EVP_PKEY_CTX* dctx = EVP_PKEY_CTX_new(asPkey(pkey_), nullptr); - size_t secretLen = 0; - if (!dctx || EVP_PKEY_derive_init(dctx) != 1 || - EVP_PKEY_derive_set_peer(dctx, peer) != 1 || - EVP_PKEY_derive(dctx, nullptr, &secretLen) != 1) { - if (dctx) { - EVP_PKEY_CTX_free(dctx); - } - EVP_PKEY_free(peer); - fail("ecdh derive init"); - } - Bytes secret(secretLen, 0); - if (EVP_PKEY_derive(dctx, secret.data(), &secretLen) != 1) { - EVP_PKEY_CTX_free(dctx); - EVP_PKEY_free(peer); - fail("ecdh derive"); - } - secret.resize(secretLen); - EVP_PKEY_CTX_free(dctx); - EVP_PKEY_free(peer); - - // Pad/truncate to 32 bytes, then SHA-1 (matches reference). - Bytes keyArr(32, 0); - if (secret.size() >= 32) { - std::copy(secret.end() - 32, secret.end(), keyArr.begin()); - } else { - std::copy(secret.begin(), secret.end(), - keyArr.begin() + (32 - secret.size())); - } - auto h = Crypto::sha1(Crypto::ByteView(keyArr.data(), keyArr.size())); - return Bytes(h.begin(), h.end()); - } - - void Identity::save(const std::string& path) const - { - EVP_PKEY* pkey = asPkey(pkey_); - BIO* mem = BIO_new(BIO_s_mem()); - if (!PEM_write_bio_PrivateKey(mem, pkey, nullptr, nullptr, 0, nullptr, - nullptr)) { - BIO_free(mem); - fail("serialize private key"); - } - char* data = nullptr; - long n = BIO_get_mem_data(mem, &data); - std::string pem(data, static_cast(n)); - BIO_free(mem); - - std::ofstream out(path, std::ios::trunc); - if (!out) { - fail("cannot open identity file for writing"); - } - out << "ECHOION_IDENTITY_V1\n"; - out << keyOffset_ << "\n"; - out << publicKeyString_ << "\n"; - out << "-----PRIVATE-----\n"; - out << pem; - } - - Identity Identity::load(const std::string& path) - { - std::ifstream in(path); - if (!in) { - fail("cannot open identity file"); - } - std::string magic; - std::getline(in, magic); - if (magic != "ECHOION_IDENTITY_V1") { - fail("bad identity file magic"); - } - std::string offsetLine; - std::getline(in, offsetLine); - Identity id; - id.keyOffset_ = std::stoull(offsetLine); - std::getline(in, id.publicKeyString_); - std::string sep; - std::getline(in, sep); // -----PRIVATE----- - std::string pem((std::istreambuf_iterator(in)), - std::istreambuf_iterator()); - - BIO* mem = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); - EVP_PKEY* pkey = PEM_read_bio_PrivateKey(mem, nullptr, nullptr, nullptr); - BIO_free(mem); - if (!pkey) { - fail("cannot parse private key"); - } - id.pkey_ = std::shared_ptr(pkey, PKeyDeleter{}); - - auto uidHash = Crypto::sha1(Crypto::ByteView( - reinterpret_cast(id.publicKeyString_.data()), - id.publicKeyString_.size())); - id.uid_ = Util::base64Encode( - Crypto::ByteView(uidHash.data(), uidHash.size())); - return id; - } - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/src/License.cpp b/EchoionProtocol/src/License.cpp deleted file mode 100644 index 735237a..0000000 --- a/EchoionProtocol/src/License.cpp +++ /dev/null @@ -1,171 +0,0 @@ -#include "echoion/protocol/License.hpp" -#include "echoion/protocol/Crypto.hpp" - -#include - -#include -#include -#include - -namespace Echoion::Protocol -{ - namespace - { - [[noreturn]] void fail(const char* what) - { - throw std::runtime_error(std::string("License: ") + what); - } - - void ensureSodium() - { - static std::once_flag once; - static bool ok = false; - std::call_once(once, [] { ok = sodium_init() >= 0; }); - if (!ok) { - fail("libsodium init failed"); - } - } - - // Ed25519 point compressed root key. - constexpr std::array LICENSE_ROOT_KEY = { - 0xcd, 0x0d, 0xe2, 0xae, 0xd4, 0x63, 0x45, 0x50, 0x9a, 0x7e, 0x3c, - 0xfd, 0x8f, 0x68, 0xb3, 0xdc, 0x75, 0x55, 0xb2, 0x9d, 0xcc, 0xec, - 0x73, 0xcd, 0x18, 0x75, 0x0f, 0x99, 0x38, 0x12, 0x40, 0x8a}; - - size_t findNullTerminator(ByteView data, size_t start) - { - for (size_t i = start; i < data.size(); ++i) { - if (data[i] == 0) { - return i - start; - } - } - fail("non-null-terminated string in license"); - } - } // namespace - - std::vector parseLicense(ByteView data) - { - if (data.size() < 1) { - fail("license too short"); - } - if (data[0] != 1) { - fail("unsupported license version"); - } - - std::vector blocks; - size_t pos = 1; - while (pos < data.size()) { - if (data.size() - pos < 42) { - fail("license block too short"); - } - if (data[pos] != 0) { - fail("wrong key kind"); - } - - LicenseBlock block; - std::memcpy(block.key.data(), data.data() + pos + 1, 32); - const uint8_t blockType = data[pos + 33]; - block.type = blockType; - - size_t extraLen = 0; - switch (blockType) { - case 0: // Intermediate - extraLen = findNullTerminator(data, pos + 46) + 5; - break; - case 2: // Server - extraLen = findNullTerminator(data, pos + 47) + 6; - break; - case 8: { // TS5 Server - size_t p = pos + 44; - const uint8_t propCount = data[pos + 43]; - for (uint8_t i = 0; i < propCount; ++i) { - const uint8_t propLen = data[p]; - p += 1 + propLen; - } - extraLen = p - (pos + 42); - break; - } - case 32: // Ephemeral - extraLen = 0; - break; - default: - fail("invalid license block type"); - } - - const size_t blockLen = 42 + extraLen; - if (pos + blockLen > data.size()) { - fail("license block overruns buffer"); - } - auto content = data.subspan(pos + 1, blockLen - 1); - auto h = Crypto::sha512(content); - std::memcpy(block.hash.data(), h.data(), 32); - - blocks.push_back(block); - pos += blockLen; - } - return blocks; - } - - std::array - deriveLicenseKey(const std::vector& blocks) - { - ensureSodium(); - std::array parentKey = LICENSE_ROOT_KEY; - - for (const auto& block : blocks) { - // Clamp the block hash into an Ed25519 scalar. - std::array scalar = block.hash; - scalar[0] &= 0xf8; - scalar[31] &= 0x3f; - scalar[31] |= 0x40; - - std::array mul{}; - if (crypto_scalarmult_ed25519_noclamp(mul.data(), scalar.data(), - block.key.data()) != 0) { - fail("ed25519 scalarmult failed"); - } - std::array sum{}; - if (crypto_core_ed25519_add(sum.data(), mul.data(), - parentKey.data()) != 0) { - fail("ed25519 point add failed"); - } - parentKey = sum; - } - return parentKey; - } - - TempKey generateTemporaryKey() - { - ensureSodium(); - TempKey out; - randombytes_buf(out.privateKey.data(), out.privateKey.size()); - out.privateKey[0] &= 248; - out.privateKey[31] &= 127; - out.privateKey[31] |= 64; - if (crypto_scalarmult_ed25519_base_noclamp(out.publicKey.data(), - out.privateKey.data()) != 0) { - fail("ed25519 base mult failed"); - } - return out; - } - - std::array getSharedSecret2(ByteView serverDerivedKey, - ByteView tempPrivateKey) - { - ensureSodium(); - if (serverDerivedKey.size() != 32 || tempPrivateKey.size() != 32) { - fail("bad key length for shared secret"); - } - std::array priv{}; - std::memcpy(priv.data(), tempPrivateKey.data(), 32); - priv[31] &= 0x7f; - - std::array mul{}; - if (crypto_scalarmult_ed25519_noclamp(mul.data(), priv.data(), - serverDerivedKey.data()) != 0) { - fail("ed25519 scalarmult failed"); - } - return Crypto::sha512(ByteView(mul.data(), mul.size())); - } - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/src/QuickLz.cpp b/EchoionProtocol/src/QuickLz.cpp deleted file mode 100644 index ceedc9f..0000000 --- a/EchoionProtocol/src/QuickLz.cpp +++ /dev/null @@ -1,158 +0,0 @@ -#include "echoion/protocol/QuickLz.hpp" - -#include -#include - -namespace Echoion::Protocol -{ - namespace - { - constexpr int TABLE_SIZE = 4096; - constexpr uint32_t MAX_DECOMPRESSED_SIZE = 1024 * 1024; - - uint32_t readU32LE(ByteView b, size_t off) - { - return static_cast(b[off]) | - (static_cast(b[off + 1]) << 8) | - (static_cast(b[off + 2]) << 16) | - (static_cast(b[off + 3]) << 24); - } - - int32_t readI32LE(ByteView b, size_t off) - { - return static_cast(readU32LE(b, off)); - } - - uint32_t read24(const Bytes& b, size_t off) - { - return static_cast(b[off]) | - (static_cast(b[off + 1]) << 8) | - (static_cast(b[off + 2]) << 16); - } - - int hashVal(uint32_t value) - { - return static_cast(((value >> 12) ^ value) & 0xfff); - } - } // namespace - - uint32_t qlzDecompressedSize(ByteView data) - { - return (data[0] & 0x02) != 0 - ? static_cast(readI32LE(data, 5)) - : data[2]; - } - - uint32_t qlzCompressedSize(ByteView data) - { - return (data[0] & 0x02) != 0 - ? static_cast(readI32LE(data, 1)) - : data[1]; - } - - Bytes qlzDecompress(ByteView data) - { - if (data.empty()) { - throw std::runtime_error("QuickLZ: empty input"); - } - const uint8_t flags = data[0]; - const int level = (flags >> 2) & 0x03; - if (level != 1) { - throw std::runtime_error("QuickLZ level not supported"); - } - - const size_t headerLen = (flags & 0x02) != 0 ? 9 : 3; - const uint32_t decompressedSize = qlzDecompressedSize(data); - if (decompressedSize > MAX_DECOMPRESSED_SIZE) { - throw std::runtime_error("QuickLZ: decompressed size exceeds max"); - } - - Bytes dest(decompressedSize, 0); - - if ((flags & 0x01) == 0) { - // Stored, not compressed. - if (headerLen + decompressedSize > data.size()) { - throw std::runtime_error("QuickLZ: truncated stored block"); - } - std::copy_n(data.begin() + headerLen, decompressedSize, - dest.begin()); - return dest; - } - - std::vector hashtable(TABLE_SIZE, 0); - uint32_t control = 1; - size_t sourcePos = headerLen; - size_t destPos = 0; - size_t nextHashed = 0; - - while (true) { - if (control == 1) { - control = readU32LE(data, sourcePos); - sourcePos += 4; - } - - if ((control & 1) != 0) { - control >>= 1; - const uint8_t next = data[sourcePos++]; - const int hashIdx = (next >> 4) | (data[sourcePos++] << 4); - - uint32_t matchLen = next & 0x0f; - if (matchLen != 0) { - matchLen += 2; - } else { - matchLen = data[sourcePos++]; - } - - const int32_t offset = hashtable[hashIdx]; - - dest[destPos] = dest[offset]; - dest[destPos + 1] = dest[offset + 1]; - dest[destPos + 2] = dest[offset + 2]; - for (uint32_t i = 3; i < matchLen; ++i) { - dest[destPos + i] = dest[offset + i]; - } - destPos += matchLen; - - const size_t end = destPos + 1 - matchLen; - if (nextHashed < end) { - uint32_t nxt = read24(dest, nextHashed); - hashtable[hashVal(nxt)] = static_cast(nextHashed); - for (size_t i = nextHashed + 1; i < end; ++i) { - nxt = (nxt >> 8) | - (static_cast(dest[i + 2]) << 16); - hashtable[hashVal(nxt)] = static_cast(i); - } - } - nextHashed = destPos; - } else if (destPos >= - std::max(decompressedSize, 10) - 10) { - while (destPos < decompressedSize) { - if (control == 1) { - sourcePos += 4; - } - control >>= 1; - dest[destPos++] = data[sourcePos++]; - } - break; - } else { - dest[destPos++] = data[sourcePos++]; - control >>= 1; - - const size_t end = destPos >= 2 ? destPos - 2 : 0; - if (nextHashed < end) { - uint32_t nxt = read24(dest, nextHashed); - hashtable[hashVal(nxt)] = static_cast(nextHashed); - for (size_t i = nextHashed + 1; i < end; ++i) { - nxt = (nxt >> 8) | - (static_cast(dest[i + 2]) << 16); - hashtable[hashVal(nxt)] = static_cast(i); - } - } - nextHashed = std::max(nextHashed, end); - } - } - - return dest; - } - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/src/TsClient.cpp b/EchoionProtocol/src/TsClient.cpp deleted file mode 100644 index c3a9be2..0000000 --- a/EchoionProtocol/src/TsClient.cpp +++ /dev/null @@ -1,980 +0,0 @@ -#include "echoion/protocol/TsClient.hpp" -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/License.hpp" -#include "echoion/protocol/QuickLz.hpp" -#include "echoion/protocol/Util.hpp" - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace Echoion::Protocol -{ - namespace - { - constexpr uint8_t FLAG_FRAGMENTED = 0x10; - constexpr uint8_t FLAG_NEWPROTOCOL = 0x20; - constexpr uint8_t FLAG_COMPRESSED = 0x40; - constexpr uint8_t FLAG_UNENCRYPTED = 0x80; - - constexpr size_t MAC_LEN = 8; - constexpr size_t C2S_HEADER_LEN = 5; // PId(2) + CId(2) + PT(1) - constexpr size_t S2C_HEADER_LEN = 3; // PId(2) + PT(1) - constexpr size_t MAX_PACKET_SIZE = 500; - constexpr size_t MAX_OUT_CONTENT = - MAX_PACKET_SIZE - MAC_LEN - C2S_HEADER_LEN; - - constexpr const char* VS_PLATFORM = "Linux"; - constexpr const char* VS_VERSION = "3.?.? [Build: 5680278000]"; - constexpr const char* VS_SIGN = - "Hjd+N58Gv3ENhoKmGYy2bNRBsNNgm5kpiaQWxOj5HN2DXttG6REjymSwJtpJ8muC2" - "gSwRuZi0R+8Laan5ts5CQ=="; - - int64_t nowMs() - { - return std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()) - .count(); - } - - void putU16BE(std::vector& b, size_t off, uint16_t v) - { - b[off] = static_cast((v >> 8) & 0xff); - b[off + 1] = static_cast(v & 0xff); - } - uint16_t getU16BE(std::span b, size_t off) - { - return static_cast((b[off] << 8) | b[off + 1]); - } - - // y = x^(2^level) mod n, all big-endian 64-byte. - std::vector rsaPuzzle(std::span x, - std::span n, int32_t level) - { - BN_CTX* ctx = BN_CTX_new(); - BIGNUM* bx = BN_bin2bn(x.data(), static_cast(x.size()), - nullptr); - BIGNUM* bn = BN_bin2bn(n.data(), static_cast(n.size()), - nullptr); - BIGNUM* exp = BN_new(); - BIGNUM* one = BN_new(); - BN_one(one); - BN_lshift(exp, one, level); // 2^level - BIGNUM* y = BN_new(); - BN_mod_exp(y, bx, exp, bn, ctx); - std::vector out(64, 0); - BN_bn2binpad(y, out.data(), 64); - BN_free(y); - BN_free(exp); - BN_free(one); - BN_free(bn); - BN_free(bx); - BN_CTX_free(ctx); - return out; - } - } // namespace - - TsClient::TsClient() = default; - - TsClient::~TsClient() - { - forceClose(); - if (thread_.joinable()) { - thread_.join(); - } - } - - void TsClient::debug(const std::string& msg) - { - if (cb_.onDebug) { - cb_.onDebug(msg); - } - } - - TsClient::Counter TsClient::getCounter(PacketType type) - { - if (type == PacketType::Init1) { - return {101, 0}; - } - auto i = static_cast(type); - return {packetCounter_[i], generationCounter_[i]}; - } - - void TsClient::incCounter(PacketType type) - { - if (type == PacketType::Init1) { - return; - } - auto i = static_cast(type); - if (++packetCounter_[i] == 0) { - ++generationCounter_[i]; - } - } - - void TsClient::connect(const TsClientOptions& opts) - { - std::lock_guard lock(mu_); - if (!opts.identity) { - throw std::runtime_error("TsClient: identity is required"); - } - opts_ = opts; - - // Resolve host and open a connected UDP socket. - addrinfo hints{}; - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_DGRAM; - hints.ai_protocol = IPPROTO_UDP; - addrinfo* res = nullptr; - std::string portStr = std::to_string(opts.port); - if (getaddrinfo(opts.host.c_str(), portStr.c_str(), &hints, &res) != 0 || - !res) { - throw std::runtime_error("TsClient: cannot resolve host " + - opts.host); - } - sock_ = ::socket(res->ai_family, res->ai_socktype, res->ai_protocol); - if (sock_ < 0) { - freeaddrinfo(res); - throw std::runtime_error("TsClient: socket() failed"); - } - if (::connect(sock_, res->ai_addr, res->ai_addrlen) != 0) { - freeaddrinfo(res); - ::close(sock_); - sock_ = -1; - throw std::runtime_error("TsClient: connect() failed"); - } - freeaddrinfo(res); - - // Reset all per-connection state. - state_ = ClientState::Init; - clientId_ = 0; - cryptoInitComplete_ = false; - ivStruct_.clear(); - fakeSignature_.fill(0); - alphaTmp_.clear(); - packetCounter_.fill(0); - generationCounter_.fill(0); - resendMap_.clear(); - initResend_.reset(); - fragmentBuffer_.clear(); - fragmenting_ = false; - fragmentFlags_ = 0; - channelMap_.clear(); - disconnectDeadline_ = 0; - lastMessageTime_ = nowMs(); - lastPing_ = nowMs(); - connectStart_ = nowMs(); - - // Reserve command counter (old clientinitiv behaviour), then Init0. - incCounter(PacketType::Command); - sendInitPacket(buildInit0()); - - running_ = true; - thread_ = std::thread([this] { loopThread(); }); - } - - void TsClient::loopThread() - { - while (running_.load()) { - pollfd pfd{}; - pfd.fd = sock_; - pfd.events = POLLIN; - int rc = ::poll(&pfd, 1, 100); - if (!running_.load()) { - break; - } - std::lock_guard lock(mu_); - if (rc > 0 && (pfd.revents & POLLIN)) { - uint8_t buf[2048]; - ssize_t n = ::recv(sock_, buf, sizeof(buf), 0); - if (n > 0) { - handleIncomingPacket( - std::span(buf, static_cast(n))); - } - } - resendTick(); - } - std::lock_guard lock(mu_); - if (sock_ >= 0) { - ::close(sock_); - sock_ = -1; - } - } - - // ---- Outgoing ---------------------------------------------------------- - - std::vector TsClient::buildInit0() - { - std::vector buf(4 + 1 + 4 + 4 + 8, 0); - putU16BE(buf, 0, static_cast((Crypto::INIT_VERSION >> 16))); - putU16BE(buf, 2, static_cast(Crypto::INIT_VERSION & 0xffff)); - buf[4] = 0x00; // step 0 - uint32_t ts = static_cast( - std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()) - .count()); - buf[5] = (ts >> 24) & 0xff; - buf[6] = (ts >> 16) & 0xff; - buf[7] = (ts >> 8) & 0xff; - buf[8] = ts & 0xff; - RAND_bytes(buf.data() + 9, 4); - return buf; - } - - void TsClient::sendInitPacket(const std::vector& data) - { - auto raw = buildRawPacket(data, PacketType::Init1, 101, - FLAG_UNENCRYPTED); - std::memcpy(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN); - initResend_ = std::make_unique( - Resend{raw, 101, nowMs(), nowMs()}); - sendRawLocked(raw); - } - - std::vector TsClient::buildRawPacket(std::span data, - PacketType type, - uint16_t packetId, - uint8_t flags) - { - std::vector raw(MAC_LEN + C2S_HEADER_LEN + data.size(), 0); - putU16BE(raw, MAC_LEN, packetId); - putU16BE(raw, MAC_LEN + 2, clientId_.load()); - raw[MAC_LEN + 4] = - static_cast((flags & 0xf0) | - (static_cast(type) & 0x0f)); - std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, data.data(), - data.size()); - return raw; - } - - void TsClient::encryptPacket(std::vector& raw, PacketType type, - uint16_t packetId, uint32_t gen, uint8_t flags, - std::span data) - { - if (type == PacketType::Init1) { - std::memcpy(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN); - return; - } - if (flags & FLAG_UNENCRYPTED) { - std::memcpy(raw.data(), fakeSignature_.data(), MAC_LEN); - return; - } - - Crypto::KeyNonce kn; - if (!cryptoInitComplete_ || ivStruct_.empty()) { - std::memcpy(kn.key.data(), Crypto::DUMMY_KEY.data(), 16); - std::memcpy(kn.nonce.data(), Crypto::DUMMY_NONCE.data(), 16); - } else { - kn = Crypto::deriveKeyNonce( - false, packetId, gen, static_cast(type), - Crypto::ByteView(ivStruct_.data(), ivStruct_.size())); - } - - Crypto::ByteView header(raw.data() + MAC_LEN, C2S_HEADER_LEN); - auto enc = Crypto::eaxEncrypt( - Crypto::ByteView(kn.key.data(), 16), - Crypto::ByteView(kn.nonce.data(), 16), header, data); - std::memcpy(raw.data(), enc.mac.data(), MAC_LEN); - std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, enc.ciphertext.data(), - enc.ciphertext.size()); - } - - void TsClient::sendOutgoing(std::span dataIn, PacketType type, - uint8_t extraFlags) - { - auto ctr = getCounter(type); - incCounter(type); - - std::vector data(dataIn.begin(), dataIn.end()); - uint8_t flags = extraFlags; - switch (type) { - case PacketType::Voice: - case PacketType::VoiceWhisper: - if (data.size() >= 2) { - putU16BE(data, 0, ctr.id); - } - break; - case PacketType::Command: - case PacketType::CommandLow: - flags |= FLAG_NEWPROTOCOL; - break; - case PacketType::Ping: - case PacketType::Pong: - flags |= FLAG_UNENCRYPTED; - break; - default: - break; - } - - auto raw = buildRawPacket(data, type, ctr.id, flags); - encryptPacket(raw, type, ctr.id, ctr.gen, flags, data); - - if (type == PacketType::Command || type == PacketType::CommandLow) { - resendMap_[ctr.id] = Resend{raw, ctr.id, nowMs(), nowMs()}; - } - sendRawLocked(raw); - } - - void TsClient::sendRawLocked(const std::vector& raw) - { - if (sock_ < 0) { - return; - } - ::send(sock_, raw.data(), raw.size(), 0); - } - - void TsClient::sendCommand(const std::string& cmd) - { - std::lock_guard lock(mu_); - std::span data( - reinterpret_cast(cmd.data()), cmd.size()); - if (data.size() <= MAX_OUT_CONTENT) { - sendOutgoing(data, PacketType::Command); - return; - } - // Fragment: FLAG_FRAGMENTED on first and last fragment only. - size_t total = data.size(); - size_t count = (total + MAX_OUT_CONTENT - 1) / MAX_OUT_CONTENT; - for (size_t i = 0, idx = 0; i < total; i += MAX_OUT_CONTENT, ++idx) { - size_t len = std::min(MAX_OUT_CONTENT, total - i); - bool first = idx == 0; - bool last = idx == count - 1; - uint8_t extra = (first || last) ? FLAG_FRAGMENTED : 0; - sendOutgoing(data.subspan(i, len), PacketType::Command, extra); - } - } - - void TsClient::sendVoice(std::span opus) - { - std::lock_guard lock(mu_); - if (state_.load() != ClientState::Connected) { - return; - } - std::vector buf(3 + opus.size(), 0); - buf[2] = 5; // CODEC_OPUS_MUSIC - std::memcpy(buf.data() + 3, opus.data(), opus.size()); - sendOutgoing(buf, PacketType::Voice); - } - - void TsClient::sendVoiceStop() - { - std::lock_guard lock(mu_); - if (state_.load() != ClientState::Connected) { - return; - } - std::vector buf(3, 0); - buf[2] = 5; - sendOutgoing(buf, PacketType::Voice); - } - - void TsClient::sendWhisper(std::span opus, - const std::vector& channelIds, - const std::vector& clientIds) - { - std::lock_guard lock(mu_); - if (state_.load() != ClientState::Connected) { - return; - } - if (channelIds.empty() && clientIds.empty()) { - sendVoice(opus); - return; - } - // VoiceWhisper C2S: voiceId(2) + codec(1) + nChan(1) + nClient(1) - // + channelIds(u64 BE each) + clientIds(u16 BE each) - // + opus. voiceId filled by sendOutgoing. - std::vector buf; - buf.resize(3 + 2 + channelIds.size() * 8 + clientIds.size() * 2 + - opus.size()); - size_t p = 0; - p += 2; // voiceId placeholder - buf[p++] = 5; // codec - buf[p++] = static_cast(channelIds.size()); - buf[p++] = static_cast(clientIds.size()); - for (uint64_t cid : channelIds) { - for (int s = 56; s >= 0; s -= 8) { - buf[p++] = static_cast((cid >> s) & 0xff); - } - } - for (uint16_t clid : clientIds) { - buf[p++] = static_cast((clid >> 8) & 0xff); - buf[p++] = static_cast(clid & 0xff); - } - std::memcpy(buf.data() + p, opus.data(), opus.size()); - sendOutgoing(buf, PacketType::VoiceWhisper); - } - - // ---- Incoming ---------------------------------------------------------- - - std::vector TsClient::decryptPacket(std::span raw, - PacketType type, - uint16_t packetId, - uint32_t gen, uint8_t flags, - bool& ok) - { - ok = false; - if (type == PacketType::Init1) { - if (std::memcmp(raw.data(), Crypto::INIT_MAC.data(), MAC_LEN) != 0) { - return {}; - } - ok = true; - return std::vector(raw.begin() + MAC_LEN + S2C_HEADER_LEN, - raw.end()); - } - if (flags & FLAG_UNENCRYPTED) { - if (cryptoInitComplete_ && - std::memcmp(raw.data(), fakeSignature_.data(), MAC_LEN) != 0) { - return {}; - } - ok = true; - return std::vector(raw.begin() + MAC_LEN + S2C_HEADER_LEN, - raw.end()); - } - - Crypto::ByteView header(raw.data() + MAC_LEN, S2C_HEADER_LEN); - Crypto::ByteView mac(raw.data(), MAC_LEN); - Crypto::ByteView ct(raw.data() + MAC_LEN + S2C_HEADER_LEN, - raw.size() - MAC_LEN - S2C_HEADER_LEN); - - for (bool dummy : {!cryptoInitComplete_, cryptoInitComplete_}) { - Crypto::KeyNonce kn; - if (dummy || ivStruct_.empty()) { - std::memcpy(kn.key.data(), Crypto::DUMMY_KEY.data(), 16); - std::memcpy(kn.nonce.data(), Crypto::DUMMY_NONCE.data(), 16); - } else { - kn = Crypto::deriveKeyNonce( - true, packetId, gen, static_cast(type), - Crypto::ByteView(ivStruct_.data(), ivStruct_.size())); - } - auto dec = Crypto::eaxDecrypt(Crypto::ByteView(kn.key.data(), 16), - Crypto::ByteView(kn.nonce.data(), 16), - header, ct, mac); - if (dec) { - ok = true; - return *dec; - } - } - return {}; - } - - void TsClient::handleIncomingPacket(std::span raw) - { - if (raw.size() < MAC_LEN + S2C_HEADER_LEN) { - return; - } - uint16_t packetId = getU16BE(raw, MAC_LEN); - uint8_t ptByte = raw[MAC_LEN + 2]; - auto type = static_cast(ptByte & 0x0f); - uint8_t flags = ptByte & 0xf0; - lastMessageTime_ = nowMs(); - - bool ok = false; - auto data = decryptPacket(raw, type, packetId, 0, flags, ok); - if (!ok) { - debug("failed to decrypt packet"); - return; - } - std::span d(data.data(), data.size()); - - switch (type) { - case PacketType::Init1: - handleInit(d); - break; - case PacketType::Command: - case PacketType::CommandLow: - sendAck(packetId, type == PacketType::Command ? PacketType::Ack - : PacketType::AckLow); - handleCommandData(d, flags); - break; - case PacketType::Ack: - if (data.size() >= 2) { - resendMap_.erase(getU16BE(d, 0)); - } - break; - case PacketType::Ping: - handlePing(packetId); - break; - case PacketType::Voice: - case PacketType::VoiceWhisper: - if (cb_.onVoice) { - cb_.onVoice(d); - } - break; - default: - break; - } - } - - void TsClient::sendAck(uint16_t ackId, PacketType ackType) - { - std::vector buf(2, 0); - putU16BE(buf, 0, ackId); - sendOutgoing(buf, ackType); - } - - void TsClient::handlePing(uint16_t packetId) - { - std::vector buf(2, 0); - putU16BE(buf, 0, packetId); - sendOutgoing(buf, PacketType::Pong); - } - - // ---- Handshake --------------------------------------------------------- - - void TsClient::handleInit(std::span data) - { - if (data.empty()) { - return; - } - uint8_t step = data[0]; - debug("init step " + std::to_string(step)); - - if (step == 1) { - if (data.size() < 21) { - return; - } - std::vector init2(4 + 1 + 16 + 4, 0); - putU16BE(init2, 0, - static_cast(Crypto::INIT_VERSION >> 16)); - putU16BE(init2, 2, - static_cast(Crypto::INIT_VERSION & 0xffff)); - init2[4] = 0x02; - std::memcpy(init2.data() + 5, data.data() + 1, 20); - initResend_.reset(); - sendInitPacket(init2); - } else if (step == 3) { - if (data.size() < 1 + 64 + 64 + 4 + 100) { - return; - } - state_ = ClientState::Handshake; - initResend_.reset(); - - std::span x = data.subspan(1, 64); - std::span n = data.subspan(65, 64); - int32_t level = static_cast( - (data[129] << 24) | (data[130] << 16) | (data[131] << 8) | - data[132]); - std::span serverData = data.subspan(133, 100); - debug("RSA puzzle level=" + std::to_string(level)); - - auto y = rsaPuzzle(x, n, level); - - // alpha = 10 random bytes (base64); omega = identity pubkey string. - alphaTmp_.assign(10, 0); - RAND_bytes(alphaTmp_.data(), 10); - std::string alpha = Util::base64Encode( - Crypto::ByteView(alphaTmp_.data(), alphaTmp_.size())); - - CommandParams p; - p["alpha"] = alpha; - p["omega"] = opts_.identity->publicKeyString(); - p["ot"] = "1"; - p["ip"] = ""; - std::string initAdd = buildCommand("clientinitiv", p); - std::span textBytes( - reinterpret_cast(initAdd.data()), - initAdd.size()); - - std::vector init4(4 + 1 + 64 + 64 + 4 + 100 + 64 + - textBytes.size(), - 0); - putU16BE(init4, 0, - static_cast(Crypto::INIT_VERSION >> 16)); - putU16BE(init4, 2, - static_cast(Crypto::INIT_VERSION & 0xffff)); - init4[4] = 0x04; - std::memcpy(init4.data() + 5, x.data(), 64); - std::memcpy(init4.data() + 69, n.data(), 64); - init4[133] = (level >> 24) & 0xff; - init4[134] = (level >> 16) & 0xff; - init4[135] = (level >> 8) & 0xff; - init4[136] = level & 0xff; - std::memcpy(init4.data() + 137, serverData.data(), 100); - std::memcpy(init4.data() + 237, y.data(), 64); - std::memcpy(init4.data() + 301, textBytes.data(), textBytes.size()); - - sendInitPacket(init4); - } else if (step == 0x7f) { - debug("server requested restart"); - initResend_.reset(); - sendInitPacket(buildInit0()); - } - } - - void TsClient::handleCommandData(std::span data, - uint8_t flags) - { - if (flags & FLAG_FRAGMENTED) { - if (!fragmenting_) { - fragmenting_ = true; - fragmentFlags_ = flags; - fragmentBuffer_.assign(data.begin(), data.end()); - } else { - fragmentBuffer_.insert(fragmentBuffer_.end(), data.begin(), - data.end()); - uint8_t saved = fragmentFlags_; - fragmenting_ = false; - fragmentFlags_ = 0; - auto merged = std::move(fragmentBuffer_); - fragmentBuffer_.clear(); - processCommand( - std::span(merged.data(), merged.size()), - saved); - } - return; - } - if (fragmenting_) { - fragmentBuffer_.insert(fragmentBuffer_.end(), data.begin(), - data.end()); - return; - } - processCommand(data, flags); - } - - void TsClient::processCommand(std::span data, uint8_t flags) - { - std::vector decompressed; - if (flags & FLAG_COMPRESSED) { - try { - decompressed = qlzDecompress(data); - data = std::span(decompressed.data(), - decompressed.size()); - } catch (const std::exception& e) { - debug(std::string("decompression failed: ") + e.what()); - return; - } - } - - std::string cmdStr(reinterpret_cast(data.data()), - data.size()); - auto parsed = parseCommand(cmdStr); - if (cb_.onCommand) { - cb_.onCommand(parsed); - } - - const std::string& name = parsed.name; - if (name == "initivexpand") { - handleInitIvExpand(parsed.params); - } else if (name == "initivexpand2") { - handleInitIvExpand2(parsed.params); - } else if (name == "initserver") { - handleInitServer(parsed.params); - } else if (name == "channellist") { - handleChannelList(parsed); - } else if (name == "channellistfinished") { - handleChannelListFinished(); - } else if (name == "notifyclientleftview") { - auto it = parsed.params.find("clid"); - if (it != parsed.params.end() && - static_cast(std::stoul(it->second)) == - clientId_.load()) { - cleanup(); - } - } else if (name == "notifytextmessage") { - if (cb_.onTextMessage) { - cb_.onTextMessage(parsed.params); - } - } else if (name == "error") { - int errId = 0; - auto it = parsed.params.find("id"); - if (it != parsed.params.end()) { - errId = std::stoi(it->second); - } - if (errId == 2568 || errId == 3329 || errId == 1796) { - std::string msg = "unknown error"; - auto m = parsed.params.find("msg"); - if (m != parsed.params.end()) { - msg = m->second; - } - if (cb_.onError) { - cb_.onError("TS3 error " + std::to_string(errId) + ": " + - msg); - } - disconnect(); - } - } - } - - void TsClient::handleInitIvExpand(const CommandParams& params) - { - initResend_.reset(); - auto ai = params.find("alpha"); - auto bi = params.find("beta"); - auto oi = params.find("omega"); - if (ai == params.end() || bi == params.end() || oi == params.end()) { - if (cb_.onError) { - cb_.onError("missing initivexpand parameters"); - } - return; - } - auto beta = Util::base64Decode(bi->second); - auto omega = Util::base64Decode(oi->second); - auto sharedKey = opts_.identity->sharedSecret( - Crypto::ByteView(omega.data(), omega.size())); - - ivStruct_.assign(10 + beta.size(), 0); - for (size_t i = 0; i < 10; ++i) { - ivStruct_[i] = sharedKey[i] ^ alphaTmp_[i]; - } - for (size_t i = 0; i < beta.size(); ++i) { - ivStruct_[10 + i] = sharedKey[10 + i] ^ beta[i]; - } - auto sig = Crypto::sha1( - Crypto::ByteView(ivStruct_.data(), ivStruct_.size())); - std::memcpy(fakeSignature_.data(), sig.data(), MAC_LEN); - cryptoInitComplete_ = true; - alphaTmp_.clear(); - sendClientInit(); - } - - void TsClient::handleInitIvExpand2(const CommandParams& params) - { - if (cryptoInitComplete_ || alphaTmp_.empty()) { - return; - } - initResend_.reset(); - auto li = params.find("l"); - auto bi = params.find("beta"); - auto oi = params.find("omega"); - if (li == params.end() || bi == params.end() || oi == params.end()) { - if (cb_.onError) { - cb_.onError("missing initivexpand2 parameters"); - } - return; - } - try { - auto beta = Util::base64Decode(bi->second); - auto license = Util::base64Decode(li->second); - auto blocks = - parseLicense(ByteView(license.data(), license.size())); - auto serverKey = deriveLicenseKey(blocks); - auto temp = generateTemporaryKey(); - - std::string ek = Util::base64Encode( - Crypto::ByteView(temp.publicKey.data(), 32)); - std::vector toSign(temp.publicKey.begin(), - temp.publicKey.end()); - toSign.insert(toSign.end(), beta.begin(), beta.end()); - auto sigBuf = opts_.identity->sign( - Crypto::ByteView(toSign.data(), toSign.size())); - std::string proof = Util::base64Encode( - Crypto::ByteView(sigBuf.data(), sigBuf.size())); - - CommandParams ck; - ck["ek"] = ek; - ck["proof"] = proof; - sendCommand(buildCommand("clientek", ck)); - - auto shared = getSharedSecret2( - ByteView(serverKey.data(), serverKey.size()), - ByteView(temp.privateKey.data(), 32)); - - ivStruct_.assign(shared.begin(), shared.end()); - for (size_t i = 0; i < 10 && i < ivStruct_.size(); ++i) { - ivStruct_[i] ^= alphaTmp_[i]; - } - for (size_t i = 0; i < beta.size() && (10 + i) < ivStruct_.size(); - ++i) { - ivStruct_[10 + i] ^= beta[i]; - } - auto sig = Crypto::sha1( - Crypto::ByteView(ivStruct_.data(), ivStruct_.size())); - std::memcpy(fakeSignature_.data(), sig.data(), MAC_LEN); - cryptoInitComplete_ = true; - alphaTmp_.clear(); - sendClientInit(); - } catch (const std::exception& e) { - if (cb_.onError) { - cb_.onError(std::string("initivexpand2 failed: ") + e.what()); - } - } - } - - void TsClient::sendClientInit() - { - debug("sending clientinit"); - CommandParams p; - p["client_nickname"] = opts_.nickname; - p["client_version"] = VS_VERSION; - p["client_platform"] = VS_PLATFORM; - p["client_input_hardware"] = "1"; - p["client_output_hardware"] = "1"; - p["client_default_channel"] = opts_.defaultChannel; - p["client_default_channel_password"] = - opts_.channelPassword.empty() - ? "" - : Crypto::hashPassword(opts_.channelPassword); - p["client_server_password"] = - opts_.serverPassword.empty() - ? "" - : Crypto::hashPassword(opts_.serverPassword); - p["client_meta_data"] = ""; - p["client_version_sign"] = VS_SIGN; - p["client_key_offset"] = std::to_string(opts_.identity->keyOffset()); - p["client_nickname_phonetic"] = ""; - p["client_default_token"] = ""; - p["hwid"] = ""; - sendCommand(buildCommand("clientinit", p)); - } - - void TsClient::handleInitServer(const CommandParams& params) - { - auto it = params.find("aclid"); - uint16_t id = 0; - if (it != params.end()) { - id = static_cast(std::stoul(it->second)); - } - clientId_ = id; - state_ = ClientState::Connected; - lastPing_ = nowMs(); - debug("connected, clientId=" + std::to_string(id)); - if (cb_.onConnected) { - cb_.onConnected(); - } - } - - void TsClient::handleChannelList(const ParsedCommand& parsed) - { - const auto& entries = - parsed.groups.empty() - ? std::vector{parsed.params} - : parsed.groups; - for (const auto& e : entries) { - auto ci = e.find("cid"); - auto ni = e.find("channel_name"); - if (ci != e.end() && ni != e.end()) { - channelMap_[ni->second] = - static_cast(std::stoull(ci->second)); - } - } - } - - void TsClient::handleChannelListFinished() - { - const std::string& target = opts_.defaultChannel; - if (target.empty() || clientId_.load() == 0) { - return; - } - uint64_t cid = 0; - bool numeric = !target.empty() && - target.find_first_not_of("0123456789") == - std::string::npos; - if (numeric) { - cid = std::stoull(target); - } else { - auto it = channelMap_.find(target); - if (it != channelMap_.end()) { - cid = it->second; - } - } - if (cid == 0) { - debug("default channel not found: " + target); - return; - } - CommandParams p; - p["cid"] = std::to_string(cid); - p["clid"] = std::to_string(clientId_.load()); - p["cpw"] = opts_.channelPassword; - sendCommand(buildCommand("clientmove", p)); - } - - // ---- Timers / teardown ------------------------------------------------- - - void TsClient::resendTick() - { - int64_t now = nowMs(); - - if (disconnectDeadline_ != 0 && now >= disconnectDeadline_) { - cleanup(); - return; - } - - if (initResend_) { - if (now - initResend_->firstSend > 30000) { - if (cb_.onError) { - cb_.onError("init timeout"); - } - cleanup(); - return; - } - if (now - initResend_->lastSend > 1000) { - initResend_->lastSend = now; - sendRawLocked(initResend_->raw); - } - } - - for (auto& [id, pkt] : resendMap_) { - if (now - pkt.firstSend > 30000) { - if (cb_.onError) { - cb_.onError("packet " + std::to_string(id) + " timeout"); - } - cleanup(); - return; - } - if (now - pkt.lastSend > 1000) { - pkt.lastSend = now; - sendRawLocked(pkt.raw); - } - } - - if (state_.load() == ClientState::Connected && - now - lastPing_ >= 1000) { - lastPing_ = now; - std::vector empty; - sendOutgoing(empty, PacketType::Ping); - } - - if (now - lastMessageTime_ > 30000) { - if (cb_.onError) { - cb_.onError("connection timeout - no response"); - } - cleanup(); - } - } - - void TsClient::disconnect() - { - std::lock_guard lock(mu_); - if (state_.load() == ClientState::Connected) { - state_ = ClientState::Disconnecting; - CommandParams p; - p["reasonid"] = "8"; - p["reasonmsg"] = "leaving"; - sendCommand(buildCommand("clientdisconnect", p)); - } - disconnectDeadline_ = nowMs() + 500; - } - - void TsClient::forceClose() - { - std::lock_guard lock(mu_); - if (state_.load() == ClientState::Disconnected && !running_.load()) { - return; - } - state_ = ClientState::Disconnected; - running_ = false; - if (sock_ >= 0) { - ::shutdown(sock_, SHUT_RDWR); - } - } - - void TsClient::cleanup() - { - if (state_.load() == ClientState::Disconnected) { - return; - } - state_ = ClientState::Disconnected; - running_ = false; - if (cb_.onDisconnected) { - cb_.onDisconnected(); - } - } - -} // namespace Echoion::Protocol diff --git a/EchoionProtocol/src/Util.cpp b/EchoionProtocol/src/Util.cpp deleted file mode 100644 index 07eb3b0..0000000 --- a/EchoionProtocol/src/Util.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include "echoion/protocol/Util.hpp" - -#include -#include - -namespace Echoion::Protocol::Util -{ - namespace - { - constexpr char kEnc[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - std::array makeDecodeTable() - { - std::array t{}; - t.fill(-1); - for (int i = 0; i < 64; ++i) { - t[static_cast(kEnc[i])] = static_cast(i); - } - return t; - } - const std::array kDec = makeDecodeTable(); - } // namespace - - std::string base64Encode(ByteView data) - { - std::string out; - out.reserve((data.size() + 2) / 3 * 4); - size_t i = 0; - for (; i + 3 <= data.size(); i += 3) { - uint32_t n = (static_cast(data[i]) << 16) | - (static_cast(data[i + 1]) << 8) | - static_cast(data[i + 2]); - out.push_back(kEnc[(n >> 18) & 0x3f]); - out.push_back(kEnc[(n >> 12) & 0x3f]); - out.push_back(kEnc[(n >> 6) & 0x3f]); - out.push_back(kEnc[n & 0x3f]); - } - const size_t rem = data.size() - i; - if (rem == 1) { - uint32_t n = static_cast(data[i]) << 16; - out.push_back(kEnc[(n >> 18) & 0x3f]); - out.push_back(kEnc[(n >> 12) & 0x3f]); - out.push_back('='); - out.push_back('='); - } else if (rem == 2) { - uint32_t n = (static_cast(data[i]) << 16) | - (static_cast(data[i + 1]) << 8); - out.push_back(kEnc[(n >> 18) & 0x3f]); - out.push_back(kEnc[(n >> 12) & 0x3f]); - out.push_back(kEnc[(n >> 6) & 0x3f]); - out.push_back('='); - } - return out; - } - - Bytes base64Decode(const std::string& text) - { - Bytes out; - out.reserve(text.size() / 4 * 3); - uint32_t buf = 0; - int bits = 0; - for (char c : text) { - if (c == '=' || c == '\n' || c == '\r' || c == ' ') { - continue; - } - int8_t v = kDec[static_cast(c)]; - if (v < 0) { - throw std::runtime_error("invalid base64 character"); - } - buf = (buf << 6) | static_cast(v); - bits += 6; - if (bits >= 8) { - bits -= 8; - out.push_back(static_cast((buf >> bits) & 0xff)); - } - } - return out; - } - - std::string toHex(ByteView data) - { - static const char* h = "0123456789abcdef"; - std::string out; - out.reserve(data.size() * 2); - for (uint8_t b : data) { - out.push_back(h[b >> 4]); - out.push_back(h[b & 0x0f]); - } - return out; - } - - Bytes fromHex(const std::string& hex) - { - auto nib = [](char c) -> int { - if (c >= '0' && c <= '9') - return c - '0'; - if (c >= 'a' && c <= 'f') - return c - 'a' + 10; - if (c >= 'A' && c <= 'F') - return c - 'A' + 10; - throw std::runtime_error("invalid hex character"); - }; - if (hex.size() % 2 != 0) { - throw std::runtime_error("odd-length hex string"); - } - Bytes out; - out.reserve(hex.size() / 2); - for (size_t i = 0; i < hex.size(); i += 2) { - out.push_back(static_cast((nib(hex[i]) << 4) | - nib(hex[i + 1]))); - } - return out; - } - -} // namespace Echoion::Protocol::Util diff --git a/EchoionProtocol/tests/CMakeLists.txt b/EchoionProtocol/tests/CMakeLists.txt deleted file mode 100644 index b610293..0000000 --- a/EchoionProtocol/tests/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Unit tests for EchoionProtocol. Uses a tiny header-only harness (check.hpp), -# no external test framework required. - -file(GLOB ECHOIONPROTOCOL_TEST_SOURCES CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/test_*.cpp") - -add_executable(echoion_protocol_tests ${ECHOIONPROTOCOL_TEST_SOURCES}) -target_link_libraries(echoion_protocol_tests PRIVATE EchoionProtocol) -target_include_directories(echoion_protocol_tests PRIVATE - "${CMAKE_CURRENT_SOURCE_DIR}") - -add_test(NAME echoion_protocol_tests COMMAND echoion_protocol_tests) diff --git a/EchoionProtocol/tests/check.hpp b/EchoionProtocol/tests/check.hpp deleted file mode 100644 index 0c81a5f..0000000 --- a/EchoionProtocol/tests/check.hpp +++ /dev/null @@ -1,82 +0,0 @@ -#pragma once - -// Minimal dependency-free test harness. Tests register cases with TEST_CASE and -// assert with CHECK / CHECK_EQ; main() runs them and reports a non-zero exit on -// any failure so ctest treats it as a failing test. - -#include -#include -#include -#include - -namespace echotest -{ - struct Case { - std::string name; - std::function fn; - }; - - inline std::vector& registry() - { - static std::vector cases; - return cases; - } - - inline int& failures() - { - static int f = 0; - return f; - } - - struct Registrar { - Registrar(const std::string& name, std::function fn) - { - registry().push_back({name, std::move(fn)}); - } - }; - - inline int run() - { - int failed = 0; - for (auto& c : registry()) { - int before = failures(); - try { - c.fn(); - } catch (const std::exception& e) { - std::printf(" [THROW] %s: %s\n", c.name.c_str(), e.what()); - ++failures(); - } - if (failures() > before) { - std::printf("[FAIL] %s\n", c.name.c_str()); - ++failed; - } else { - std::printf("[ok] %s\n", c.name.c_str()); - } - } - std::printf("\n%zu cases, %d failed\n", registry().size(), failed); - return failed == 0 ? 0 : 1; - } -} // namespace echotest - -#define TEST_CASE(name) \ - static void name(); \ - static echotest::Registrar reg_##name(#name, name); \ - static void name() - -#define CHECK(cond) \ - do { \ - if (!(cond)) { \ - std::printf(" CHECK failed: %s (%s:%d)\n", #cond, __FILE__, \ - __LINE__); \ - ++echotest::failures(); \ - } \ - } while (0) - -#define CHECK_EQ(a, b) \ - do { \ - if (!((a) == (b))) { \ - std::printf(" CHECK_EQ failed: %s == %s (%s:%d)\n", #a, #b, \ - __FILE__, __LINE__); \ - ++echotest::failures(); \ - } \ - } while (0) diff --git a/EchoionProtocol/tests/test_command.cpp b/EchoionProtocol/tests/test_command.cpp deleted file mode 100644 index 6be30ab..0000000 --- a/EchoionProtocol/tests/test_command.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include "check.hpp" -#include "echoion/protocol/Command.hpp" - -using namespace Echoion::Protocol; - -TEST_CASE(escape_roundtrip) -{ - std::string raw = "hello world|pipe/slash\ttab\nnl\\back"; - auto esc = tsEscape(raw); - // Spaces and specials must be escaped (no raw space/pipe left). - CHECK(esc.find(' ') == std::string::npos); - CHECK(esc.find('|') == std::string::npos); - CHECK_EQ(tsUnescape(esc), raw); -} - -TEST_CASE(escape_known) -{ - CHECK_EQ(tsEscape("a b"), std::string("a\\sb")); - CHECK_EQ(tsEscape("a|b"), std::string("a\\pb")); - CHECK_EQ(tsEscape("a/b"), std::string("a\\/b")); - CHECK_EQ(tsUnescape("a\\sb"), std::string("a b")); -} - -TEST_CASE(build_command) -{ - CommandParams p; - p["client_nickname"] = "My Bot"; - p["cid"] = "5"; - auto cmd = buildCommand("clientmove", p); - // Params are ordered by key (map): cid before client_nickname. - CHECK_EQ(cmd, std::string("clientmove cid=5 client_nickname=My\\sBot")); -} - -TEST_CASE(parse_notify) -{ - auto pc = parseCommand( - "notifytextmessage targetmode=2 msg=hello\\sworld invokerid=7 " - "invokername=Alice"); - CHECK_EQ(pc.name, std::string("notifytextmessage")); - CHECK_EQ(pc.params["targetmode"], std::string("2")); - CHECK_EQ(pc.params["msg"], std::string("hello world")); - CHECK_EQ(pc.params["invokername"], std::string("Alice")); -} - -TEST_CASE(parse_pipe_groups) -{ - auto pc = parseCommand("channellist cid=1 channel_name=Default|cid=2 " - "channel_name=Talk"); - CHECK_EQ(pc.name, std::string("channellist")); - CHECK_EQ(pc.groups.size(), size_t(2)); - CHECK_EQ(pc.groups[0]["cid"], std::string("1")); - CHECK_EQ(pc.groups[0]["channel_name"], std::string("Default")); - CHECK_EQ(pc.groups[1]["cid"], std::string("2")); - CHECK_EQ(pc.groups[1]["channel_name"], std::string("Talk")); -} diff --git a/EchoionProtocol/tests/test_crypto.cpp b/EchoionProtocol/tests/test_crypto.cpp deleted file mode 100644 index 7a45ce2..0000000 --- a/EchoionProtocol/tests/test_crypto.cpp +++ /dev/null @@ -1,123 +0,0 @@ -#include "check.hpp" -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/Util.hpp" - -#include - -using namespace Echoion::Protocol; -using Crypto::ByteView; - -namespace -{ - Crypto::Bytes hex(const std::string& h) { return Util::fromHex(h); } - std::string hx(ByteView b) { return Util::toHex(b); } - std::string hx(const std::vector& b) - { - return Util::toHex(ByteView(b.data(), b.size())); - } - template std::string hx(const std::array& b) - { - return Util::toHex(ByteView(b.data(), b.size())); - } -} // namespace - -// RFC 4493 AES-128-CMAC known-answer vectors. -TEST_CASE(cmac_rfc4493) -{ - auto key = hex("2b7e151628aed2a6abf7158809cf4f3c"); - - // Example 1: empty message. - CHECK_EQ(hx(Crypto::cmac(key, {})), - std::string("bb1d6929e95937287fa37d129b756746")); - - // Example 2: 16-byte message. - auto m2 = hex("6bc1bee22e409f96e93d7e117393172a"); - CHECK_EQ(hx(Crypto::cmac(key, m2)), - std::string("070a16b46b4d4144f79bdd9dd04a287c")); - - // Example 3: 40-byte message. - auto m3 = hex("6bc1bee22e409f96e93d7e117393172a" - "ae2d8a571e03ac9c9eb76fac45af8e51" - "30c81c46a35ce411"); - CHECK_EQ(hx(Crypto::cmac(key, m3)), - std::string("dfa66747de9ae63030ca32611497c827")); - - // Example 4: 64-byte message. - auto m4 = hex("6bc1bee22e409f96e93d7e117393172a" - "ae2d8a571e03ac9c9eb76fac45af8e51" - "30c81c46a35ce411e5fbc1191a0a52ef" - "f69f2445df4f9b17ad2b417be66c3710"); - CHECK_EQ(hx(Crypto::cmac(key, m4)), - std::string("51f0bebf7e3b9d92fc49741779363cfe")); -} - -// EAX specification test vectors (Bellare/Rogaway/Wagner). The EAX output is -// ciphertext||tag where tag is the full 16-byte value; TeamSpeak truncates the -// MAC to 8 bytes, so we compare against the first 8 tag bytes. -TEST_CASE(eax_spec_vectors) -{ - // Empty message. - { - auto key = hex("233952dee4d5ed5f9b9c6d6ff80ff478"); - auto nonce = hex("62ec67f9c3a4a407fcb2a8c49031a8b3"); - auto hdr = hex("6bfb914fd07eae6b"); - auto res = Crypto::eaxEncrypt(key, nonce, hdr, {}); - CHECK(res.ciphertext.empty()); - CHECK_EQ(hx(res.mac), std::string("e037830e8389f27b")); - // Round-trip. - auto dec = Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, res.mac); - CHECK(dec.has_value()); - CHECK(dec && dec->empty()); - } - - // 2-byte message F7FB. - { - auto key = hex("91945d3f4dcbee0bf45ef52255f095a4"); - auto nonce = hex("becaf043b0a23d843194ba972c66debd"); - auto hdr = hex("fa3bfd4806eb53fa"); - auto msg = hex("f7fb"); - auto res = Crypto::eaxEncrypt(key, nonce, hdr, msg); - CHECK_EQ(hx(res.ciphertext), std::string("19dd")); - CHECK_EQ(hx(res.mac), std::string("5c4c9331049d0bda")); - auto dec = Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, res.mac); - CHECK(dec.has_value()); - CHECK(dec && hx(*dec) == std::string("f7fb")); - // Tamper → reject. - auto bad = res.mac; - bad[0] ^= 0x01; - CHECK(!Crypto::eaxDecrypt(key, nonce, hdr, res.ciphertext, bad)); - } -} - -TEST_CASE(sha_and_base64) -{ - // sha1("abc") = a9993e364706816aba3e25717850c26c9cd0d89d - std::string abc = "abc"; - auto s1 = Crypto::sha1( - ByteView(reinterpret_cast(abc.data()), abc.size())); - CHECK_EQ(hx(s1), - std::string("a9993e364706816aba3e25717850c26c9cd0d89d")); - - // base64 round-trip + known value. - CHECK_EQ(Util::base64Encode(ByteView( - reinterpret_cast("foobar"), 6)), - std::string("Zm9vYmFy")); - auto dec = Util::base64Decode("Zm9vYmFy"); - CHECK_EQ(std::string(dec.begin(), dec.end()), std::string("foobar")); -} - -// deriveKeyNonce: verify the packetId XOR into key[0..1] and the deterministic -// structure. Uses a fixed 20-byte ivStruct. -TEST_CASE(derive_key_nonce) -{ - auto iv = hex("000102030405060708090a0b0c0d0e0f10111213"); // 20 bytes - auto a = Crypto::deriveKeyNonce(false, 0, 0, 2, iv); - auto b = Crypto::deriveKeyNonce(false, 0x0102, 0, 2, iv); - // key[0] ^= pid>>8, key[1] ^= pid&0xff; nonce unchanged. - CHECK_EQ(a.key[0] ^ 0x01, b.key[0]); - CHECK_EQ(a.key[1] ^ 0x02, b.key[1]); - CHECK_EQ(hx(a.nonce), hx(b.nonce)); - // Direction changes the derivation. - auto c = Crypto::deriveKeyNonce(true, 0, 0, 2, iv); - CHECK(hx(a.key) != hx(c.key)); -} diff --git a/EchoionProtocol/tests/test_identity.cpp b/EchoionProtocol/tests/test_identity.cpp deleted file mode 100644 index 452bdf4..0000000 --- a/EchoionProtocol/tests/test_identity.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include "check.hpp" -#include "echoion/protocol/Crypto.hpp" -#include "echoion/protocol/Identity.hpp" -#include "echoion/protocol/Util.hpp" - -#include -#include - -using namespace Echoion::Protocol; - -TEST_CASE(identity_generate_uid_and_level) -{ - auto id = Identity::generate(8); - - // uid must equal base64(sha1(ascii(publicKeyString))). - auto h = Crypto::sha1(Crypto::ByteView( - reinterpret_cast(id.publicKeyString().data()), - id.publicKeyString().size())); - CHECK_EQ(id.uid(), - Util::base64Encode(Crypto::ByteView(h.data(), h.size()))); - - // publicKeyString is valid base64 of a DER SEQUENCE (starts with 0x30). - auto der = Util::base64Decode(id.publicKeyString()); - CHECK(!der.empty()); - CHECK_EQ(der[0], uint8_t(0x30)); - - // Security level actually reached the requested threshold. - CHECK(id.securityLevel() >= 8); -} - -TEST_CASE(identity_sign_verifiable_length) -{ - auto id = Identity::generate(0); - std::string msg = "hello"; - auto sig = id.sign(Crypto::ByteView( - reinterpret_cast(msg.data()), msg.size())); - // DER ECDSA signature over P-256 is ~70-72 bytes; never empty. - CHECK(!sig.empty()); - CHECK(sig[0] == 0x30); // DER SEQUENCE -} - -TEST_CASE(identity_save_load_roundtrip) -{ - auto id = Identity::generate(0); - std::string path = "/tmp/echoion_identity_test.txt"; - id.save(path); - auto loaded = Identity::load(path); - CHECK_EQ(loaded.publicKeyString(), id.publicKeyString()); - CHECK_EQ(loaded.uid(), id.uid()); - CHECK_EQ(loaded.keyOffset(), id.keyOffset()); - std::remove(path.c_str()); -} diff --git a/EchoionProtocol/tests/test_main.cpp b/EchoionProtocol/tests/test_main.cpp deleted file mode 100644 index 9c8670f..0000000 --- a/EchoionProtocol/tests/test_main.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "check.hpp" - -int main() -{ - return echotest::run(); -} diff --git a/EchoionProtocol/tests/test_quicklz.cpp b/EchoionProtocol/tests/test_quicklz.cpp deleted file mode 100644 index 04044f8..0000000 --- a/EchoionProtocol/tests/test_quicklz.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include "check.hpp" -#include "echoion/protocol/QuickLz.hpp" - -using namespace Echoion::Protocol; - -// QuickLZ level-1 "stored" (uncompressed) block: header byte with level=1 -// (bits 2-3 = 01 -> 0x04), compressed bit (bit0) = 0, short size form -// (bit1 = 0) -> 3-byte header: [flags, compressedSize, decompressedSize]. -TEST_CASE(qlz_stored_block) -{ - Bytes payload = {'h', 'e', 'l', 'l', 'o'}; - Bytes buf; - buf.push_back(0x04); // flags: level 1, not compressed, short header - buf.push_back(static_cast(3 + payload.size())); // compressed size - buf.push_back(static_cast(payload.size())); // decompressed size - buf.insert(buf.end(), payload.begin(), payload.end()); - - CHECK_EQ(qlzDecompressedSize(buf), uint32_t(payload.size())); - CHECK_EQ(qlzCompressedSize(buf), uint32_t(3 + payload.size())); - - auto out = qlzDecompress(buf); - CHECK_EQ(out.size(), payload.size()); - CHECK(out == payload); -} - -TEST_CASE(qlz_rejects_bad_level) -{ - Bytes buf = {0x00, 0x03, 0x00}; // level 0 -> unsupported - bool threw = false; - try { - qlzDecompress(buf); - } catch (const std::exception&) { - threw = true; - } - CHECK(threw); -} diff --git a/EchoionStandalone/CMakeLists.txt b/EchoionStandalone/CMakeLists.txt index 5733ceb..2cd6d53 100644 --- a/EchoionStandalone/CMakeLists.txt +++ b/EchoionStandalone/CMakeLists.txt @@ -1,9 +1,7 @@ # EchoionStandalone — the daemon that runs Core without a TeamSpeak client. # -# It reuses the plugin's (TeamSpeak-independent) CoreLoader/FileWatcher to load -# and hot-reload Core, but implements IPluginInterface with EchoionProtocol's -# native UDP client. Built with PLUGIN=1 so it shares the plugin's minimal-API -# ABI contract with Core (self-contained ServerConfig, no ConfigTypes). +# 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) project(EchoionStandalone VERSION 1.0.0 LANGUAGES CXX) @@ -12,41 +10,72 @@ set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -# dylib for the Core hot-reload loader (same version the plugin uses). -CPMAddPackage( - NAME dylib - GITHUB_REPOSITORY martin-olivier/dylib - GIT_TAG "v3.0.1" -) - find_package(PkgConfig REQUIRED) -pkg_check_modules(SWRESAMPLE REQUIRED IMPORTED_TARGET libswresample libavutil) +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(PLUGIN_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../EchoionPlugin") +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 - # Reused, TeamSpeak-independent loader from the plugin (transition shim; - # a shared EchoionHostCommon lib can extract these later). - "${PLUGIN_DIR}/src/CoreLoader.cpp" - "${PLUGIN_DIR}/src/FileWatcher.cpp" + src/MessageChunker.cpp + src/ReleaseManifest.cpp + src/RuntimePaths.cpp + src/EventCallbackGate.cpp + src/UpdateService.cpp ) -# PLUGIN=1 gives the self-contained ServerConfig + minimal API, matching the -# ABI Core was built against for the plugin path. -target_compile_definitions(EchoionStandalone PRIVATE PLUGIN=1) - target_include_directories(EchoionStandalone PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/include" - "${PLUGIN_DIR}/include" + "${CMAKE_CURRENT_BINARY_DIR}/generated" ) target_link_libraries(EchoionStandalone PRIVATE - Echoion::Protocol + Void::TeamSpeak + Echoion::Host Echoion::ApiBase Echoion::ApiPlugin Echoion::ApiOpaque @@ -54,12 +83,19 @@ target_link_libraries(EchoionStandalone PRIVATE Echoion::ApiCoreInterface Echoion::ApiLogger Void::Data + Void::Core Void::Log + Void::System Void::Stacktrace - dylib + Void::Archive + Void::Crypto + Void::Net + Void::Plugin + Void::Update Threads::Threads PkgConfig::SWRESAMPLE PkgConfig::OPUS + OpenSSL::Crypto ) set_target_properties(EchoionStandalone PROPERTIES @@ -68,3 +104,99 @@ set_target_properties(EchoionStandalone PROPERTIES ) install(TARGETS EchoionStandalone RUNTIME DESTINATION bin) + +if(BUILD_TESTS) + 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) + + 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/EventCallbackGate.hpp b/EchoionStandalone/include/echoion/standalone/EventCallbackGate.hpp new file mode 100644 index 0000000..ed484f3 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/EventCallbackGate.hpp @@ -0,0 +1,29 @@ +#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 new file mode 100644 index 0000000..4b224b2 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/MessageChunker.hpp @@ -0,0 +1,13 @@ +#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 new file mode 100644 index 0000000..553230d --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/ReleaseManifest.hpp @@ -0,0 +1,41 @@ +#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 new file mode 100644 index 0000000..88122a1 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/RuntimePaths.hpp @@ -0,0 +1,39 @@ +#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::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 index 8910b06..a8a3a7d 100644 --- a/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp +++ b/EchoionStandalone/include/echoion/standalone/StandaloneClientInterface.hpp @@ -1,21 +1,21 @@ #pragma once -// Implements Echoion's IPluginInterface against the native TeamSpeak UDP -// protocol (EchoionProtocol) instead of the TS3 Client Plugin SDK. This is the -// single seam that lets the whole Core run as a standalone application: Core -// only ever talks to IPluginInterface, so swapping this implementation in for -// the plugin drops the TeamSpeak-client dependency entirely. +// 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/protocol/Identity.hpp" -#include "echoion/protocol/TsClient.hpp" +#include "echoion/standalone/EventCallbackGate.hpp" +#include #include +#include #include #include #include #include +#include #include namespace Echoion::Standalone @@ -28,6 +28,7 @@ namespace Echoion::Standalone // required. struct StandaloneSettings { std::string identityPath; // where to load/persist the TS identity + std::string avatarCachePath; int securityLevel = 8; int opusBitrate = 96000; }; @@ -48,16 +49,55 @@ namespace Echoion::Standalone 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 @@ -83,35 +123,51 @@ namespace Echoion::Standalone Api::Result reconnect() override; // Events - void - registerEventCallback(const Api::EventCallback& cb) override; - void - unregisterEventCallback(const Api::EventCallback& cb) override; + 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 onCommand(const Protocol::ParsedCommand& parsed); - void onTextMessage(const Protocol::CommandParams& params); void broadcast(const Api::PluginEvent& event); - void upsertClientGroup(const Protocol::CommandParams& p, - bool emitConnected); + void loadInitialSnapshot(); + [[nodiscard]] Api::Result commandResult( + const Void::Result::Result& + result) const; StandaloneSettings settings_; - std::unique_ptr identity_; - std::unique_ptr client_; + 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::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_; - std::mutex cbMutex_; - std::vector callbacks_; + EventCallbackGate eventCallbacks_; }; } // namespace Echoion::Standalone diff --git a/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in b/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in new file mode 100644 index 0000000..975eeb0 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/UpdateBuildDefaults.hpp.in @@ -0,0 +1,17 @@ +#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 new file mode 100644 index 0000000..76dac97 --- /dev/null +++ b/EchoionStandalone/include/echoion/standalone/UpdateService.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Echoion::Standalone +{ + // 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_; + }; +} // namespace Echoion::Standalone diff --git a/EchoionStandalone/src/EventCallbackGate.cpp b/EchoionStandalone/src/EventCallbackGate.cpp new file mode 100644 index 0000000..ddf6f45 --- /dev/null +++ b/EchoionStandalone/src/EventCallbackGate.cpp @@ -0,0 +1,42 @@ +#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 new file mode 100644 index 0000000..00c65cd --- /dev/null +++ b/EchoionStandalone/src/MessageChunker.cpp @@ -0,0 +1,86 @@ +#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 new file mode 100644 index 0000000..f39ff7a --- /dev/null +++ b/EchoionStandalone/src/ReleaseManifest.cpp @@ -0,0 +1,650 @@ +#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 new file mode 100644 index 0000000..7996086 --- /dev/null +++ b/EchoionStandalone/src/RuntimePaths.cpp @@ -0,0 +1,178 @@ +#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) { + return packagedDirectory; + } + + error.clear(); + if (std::filesystem::is_regular_file( + executableDirectory / "web" / "index.html", error) && + !error) { + return executableDirectory; + } + return std::nullopt; + } + + 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 index 5104807..beb05bf 100644 --- a/EchoionStandalone/src/StandaloneClientInterface.cpp +++ b/EchoionStandalone/src/StandaloneClientInterface.cpp @@ -1,12 +1,16 @@ -#include "echoion/standalone/StandaloneClientInterface.hpp" #include "echoion/standalone/AudioEncoder.hpp" - -#include "echoion/protocol/Command.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 { @@ -14,20 +18,89 @@ namespace Echoion::Standalone { constexpr const char* LOG = "Standalone"; - uint64_t toU64(const std::string& s) + Api::Error teamSpeakError(const Void::TeamSpeak::Error& error) { - try { - return std::stoull(s); - } catch (...) { - return 0; + 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::string get(const Protocol::CommandParams& p, const char* k) + std::optional checkedClientId(uint64_t value) { - auto it = p.find(k); - return it == p.end() ? std::string{} : it->second; + 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( @@ -47,7 +120,7 @@ namespace Echoion::Standalone return {}; } encoder_ = std::make_unique(settings_.opusBitrate); - client_ = std::make_unique(); + client_ = std::make_unique(); Void::Log::info(LOG, "Standalone client interface initialized"); return {}; } @@ -58,7 +131,13 @@ namespace Echoion::Standalone return {}; } if (client_) { - client_->forceClose(); + client_->close(); + } + if (snapshotThread_.joinable()) { + snapshotThread_.request_stop(); + snapshotThread_.join(); + } + if (client_) { client_.reset(); } encoder_.reset(); @@ -67,8 +146,8 @@ namespace Echoion::Standalone // ---- Connection -------------------------------------------------------- - Api::Result - StandaloneClientInterface::connectToServer(const Api::ServerConfig& config) + Api::Result StandaloneClientInterface::connectToServer( + const Api::ServerConfig& config) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, @@ -80,16 +159,17 @@ namespace Echoion::Standalone try { std::filesystem::path idPath(settings_.identityPath); if (!idPath.empty() && std::filesystem::exists(idPath)) { - identity_ = std::make_unique( - Protocol::Identity::load(idPath.string())); + 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_unique( - Protocol::Identity::generate(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()); @@ -104,21 +184,19 @@ namespace Echoion::Standalone wireCallbacks(); - Protocol::TsClientOptions opts; + Void::TeamSpeak::ConnectOptions opts; opts.host = config.address; opts.port = config.port ? config.port : 9987; - opts.identity = identity_.get(); - opts.nickname = config.nickname.empty() ? "EchoionBot" : config.nickname; + opts.identity = identity_; + opts.nickname = + config.nickname.empty() ? "EchoionBot" : config.nickname; opts.serverPassword = config.serverPassword; - opts.defaultChannel = - config.defaultChannelId.value_or(std::string{}); + opts.defaultChannel = config.defaultChannelId.value_or(std::string{}); opts.channelPassword = config.channelPassword.value_or(std::string{}); - try { - client_->connect(opts); - } catch (const std::exception& e) { + if (auto connected = client_->connect(opts); !connected) { return Api::fail(Api::ErrorCode::NetworkError, - std::string("connect failed: ") + e.what()); + "connect failed: " + connected.error().message); } Void::Log::info(LOG, "Connecting to {}:{} as {}", opts.host, opts.port, opts.nickname); @@ -127,31 +205,301 @@ namespace Echoion::Standalone void StandaloneClientInterface::wireCallbacks() { - Protocol::TsClientCallbacks cb; - cb.onConnected = [this] { - // Ask the server to reveal all clients so the presence mirror fills. - client_->sendCommand("channelsubscribeall"); - Api::PluginEvent ev; - ev.type = Api::PluginEventType::ConnectionEstablished; - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); + Void::TeamSpeak::Events cb; + cb.connected = [this] { + if (snapshotThread_.joinable()) { + snapshotThread_.request_stop(); + snapshotThread_.join(); + } + snapshotThread_ = std::jthread([this] { loadInitialSnapshot(); }); }; - cb.onDisconnected = [this] { + 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.onError = [](const std::string& msg) { - Void::Log::error(LOG, "Protocol error: {}", msg); + cb.error = [](const Void::TeamSpeak::Error& error) { + Void::Log::error(LOG, "Protocol error: {}", error.message); }; - cb.onCommand = [this](const Protocol::ParsedCommand& p) { - onCommand(p); + 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.onTextMessage = [this](const Protocol::CommandParams& p) { - onTextMessage(p); + 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.onDebug = [](const std::string& msg) { + 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); }; - client_->setCallbacks(std::move(cb)); + 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() @@ -165,7 +513,7 @@ namespace Echoion::Standalone bool StandaloneClientInterface::isConnected() const { return client_ && - client_->state() == Protocol::ClientState::Connected; + client_->state() == Void::TeamSpeak::ConnectionState::Connected; } Api::Result StandaloneClientInterface::reconnect() @@ -174,275 +522,649 @@ namespace Echoion::Standalone return connectToServer(currentConfig_); } - // ---- Event mirror ------------------------------------------------------ - - void StandaloneClientInterface::upsertClientGroup( - const Protocol::CommandParams& p, bool emitConnected) - { - uint64_t clid = toU64(get(p, "clid")); - if (clid == 0) { - return; - } - Api::ClientInfo info; - { - std::lock_guard lock(mirrorMutex_); - info = clients_[clid]; - info.id = clid; - if (auto n = get(p, "client_nickname"); !n.empty()) { - info.nickname = n; - } - if (auto u = get(p, "client_unique_identifier"); !u.empty()) { - info.uniqueIdentifier = u; - } - if (auto c = get(p, "ctid"); !c.empty()) { - info.channelId = toU64(c); - } else if (auto cid = get(p, "cid"); !cid.empty()) { - info.channelId = toU64(cid); - } - clients_[clid] = info; - } - if (emitConnected) { - Api::PluginEvent ev; - ev.type = Api::PluginEventType::ClientConnected; - ev.clientId = clid; - ev.clientName = info.nickname; - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); - } - } - - void StandaloneClientInterface::onCommand(const Protocol::ParsedCommand& p) - { - const auto& groups = - p.groups.empty() - ? std::vector{p.params} - : p.groups; - - if (p.name == "notifycliententerview") { - for (const auto& g : groups) { - upsertClientGroup(g, true); - } - } else if (p.name == "notifyclientleftview") { - for (const auto& g : groups) { - uint64_t clid = toU64(get(g, "clid")); - if (clid == 0) { - continue; - } - std::string name; - { - std::lock_guard lock(mirrorMutex_); - auto it = clients_.find(clid); - if (it != clients_.end()) { - name = it->second.nickname; - clients_.erase(it); - } - } - Api::PluginEvent ev; - ev.type = Api::PluginEventType::ClientDisconnected; - ev.clientId = clid; - ev.clientName = name; - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); - } - } else if (p.name == "notifyclientmoved") { - for (const auto& g : groups) { - uint64_t clid = toU64(get(g, "clid")); - uint64_t ctid = toU64(get(g, "ctid")); - if (clid == 0) { - continue; - } - { - std::lock_guard lock(mirrorMutex_); - clients_[clid].id = clid; - clients_[clid].channelId = ctid; - } - Api::PluginEvent ev; - ev.type = Api::PluginEventType::ClientMoved; - ev.clientId = clid; - ev.targetChannelId = ctid; - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); - } - } else if (p.name == "channellist" || p.name == "notifychannellist") { - std::lock_guard lock(mirrorMutex_); - for (const auto& g : groups) { - uint64_t cid = toU64(get(g, "cid")); - if (cid == 0) { - continue; - } - Api::ChannelInfo ch = channels_[cid]; - ch.id = cid; - if (auto n = get(g, "channel_name"); !n.empty()) { - ch.name = n; - } - if (auto pid = get(g, "pid"); !pid.empty()) { - ch.parentId = toU64(pid); - } - channels_[cid] = ch; - } - } - } - - void StandaloneClientInterface::onTextMessage( - const Protocol::CommandParams& params) - { - uint64_t invoker = toU64(get(params, "invokerid")); - if (client_ && invoker == client_->clientId()) { - return; // ignore our own messages - } - Api::PluginEvent ev; - ev.type = Api::PluginEventType::TextMessageReceived; - ev.clientId = invoker; - ev.clientName = get(params, "invokername"); - ev.message = get(params, "msg"); - if (auto t = get(params, "target"); !t.empty()) { - ev.targetChannelId = toU64(t); - } - ev.timestamp = std::chrono::system_clock::now(); - broadcast(ev); - } - + // 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) { - std::vector cbs; - { - std::lock_guard lock(cbMutex_); - cbs = callbacks_; - } - for (const auto& cb : cbs) { - cb(event); - } + eventCallbacks_.dispatch(event); } // ---- Clients / channels ------------------------------------------------ Api::Result> - StandaloneClientInterface::getClients() + StandaloneClientInterface::getClients() { std::lock_guard lock(mirrorMutex_); std::vector out; out.reserve(clients_.size()); for (const auto& [id, c] : clients_) { - out.push_back(c); + (void)id; + out.push_back(apiClient(c)); } return out; } Api::Result> - StandaloneClientInterface::getClient(uint64_t clientId) + 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{it->second}; + 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 + StandaloneClientInterface::getChannels() const { std::lock_guard lock(mirrorMutex_); std::vector out; out.reserve(channels_.size()); for (const auto& [id, c] : channels_) { - out.push_back(c); + 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 + StandaloneClientInterface::getChannel(uint64_t channelId) const { std::lock_guard lock(mirrorMutex_); auto it = channels_.find(channelId); if (it == channels_.end()) { return std::optional{}; } - return std::optional{it->second}; + 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) + Api::Result StandaloneClientInterface::moveClient(uint64_t clientId, + uint64_t channelId) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - Protocol::CommandParams p; - p["clid"] = std::to_string(clientId); - p["cid"] = std::to_string(channelId); - client_->sendCommand(Protocol::buildCommand("clientmove", p)); - return {}; + 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) + StandaloneClientInterface::kickClient(uint64_t clientId, + const std::string& reason) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - Protocol::CommandParams p; - p["clid"] = std::to_string(clientId); - p["reasonid"] = "5"; // kick from server - p["reasonmsg"] = reason; - client_->sendCommand(Protocol::buildCommand("clientkick", p)); - return {}; + 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) + StandaloneClientInterface::sendTextMessage(uint64_t targetId, + const std::string& message) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - Protocol::CommandParams p; - p["targetmode"] = "1"; // client - p["target"] = std::to_string(targetId); - p["msg"] = message; - client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); + 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) + Api::Result StandaloneClientInterface::sendChannelMessage( + uint64_t channelId, const std::string& message) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - Protocol::CommandParams p; - p["targetmode"] = "2"; // channel - p["target"] = std::to_string(channelId); - p["msg"] = message; - client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); - return {}; + return commandResult(client_->sendChannelMessage( + Void::TeamSpeak::ChannelId{channelId}, message)); } Api::Result - StandaloneClientInterface::sendServerMessage(const std::string& message) + StandaloneClientInterface::sendServerMessage(const std::string& message) { if (!client_) { return Api::fail(Api::ErrorCode::NotInitialized, "not connected"); } - Protocol::CommandParams p; - p["targetmode"] = "3"; // server - p["msg"] = message; - client_->sendCommand(Protocol::buildCommand("sendtextmessage", p)); - return {}; + return commandResult(client_->sendServerMessage(message)); } // ---- Audio ------------------------------------------------------------- - Api::Result - StandaloneClientInterface::sendAudioData(const std::span& data) + Api::Result StandaloneClientInterface::sendAudioData( + const std::span& data) { if (!client_ || !encoder_ || - client_->state() != Protocol::ClientState::Connected) { - return {}; + client_->state() != Void::TeamSpeak::ConnectionState::Connected) { + return Api::fail(Api::ErrorCode::ServiceUnavailable, + "not connected"); } std::vector whisper; { @@ -452,14 +1174,21 @@ namespace Echoion::Standalone auto frames = encoder_->encode(data); for (const auto& f : frames) { if (whisper.empty()) { - client_->sendVoice(f); + if (auto sent = client_->sendVoice(f); !sent) { + return Api::fail(Api::ErrorCode::NetworkError, + sent.error().message); + } } else { - std::vector clients; - clients.reserve(whisper.size()); + Void::TeamSpeak::WhisperTargets targets; + targets.clients.reserve(whisper.size()); for (uint64_t c : whisper) { - clients.push_back(static_cast(c)); + 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); } - client_->sendWhisper(f, {}, clients); } } return {}; @@ -468,6 +1197,12 @@ namespace Echoion::Standalone 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 {}; @@ -478,8 +1213,7 @@ namespace Echoion::Standalone void StandaloneClientInterface::registerEventCallback( const Api::EventCallback& cb) { - std::lock_guard lock(cbMutex_); - callbacks_.push_back(cb); + eventCallbacks_.add(cb); } void StandaloneClientInterface::unregisterEventCallback( @@ -488,8 +1222,35 @@ namespace Echoion::Standalone // 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. - std::lock_guard lock(cbMutex_); - callbacks_.clear(); + 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 new file mode 100644 index 0000000..d3afda3 --- /dev/null +++ b/EchoionStandalone/src/UpdateService.cpp @@ -0,0 +1,3221 @@ +#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); + } + + 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 index f40cff7..b9e4c23 100644 --- a/EchoionStandalone/src/main.cpp +++ b/EchoionStandalone/src/main.cpp @@ -1,39 +1,352 @@ -// Standalone Echoion host. -// -// Replaces the TeamSpeak-client + plugin sandwich: loads the same hot-reloadable -// Core shared library via the (TeamSpeak-independent) CoreLoader, but backs -// IPluginInterface with a native TeamSpeak UDP protocol client instead of the -// TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no -// TeamSpeak client, no Weston/RDP, no plugin directory. +// 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/plugin/CoreLoader.hpp" +#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 +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif namespace { - std::atomic g_stop{false}; - std::condition_variable g_cv; - std::mutex g_mu; + std::atomic g_updateRequested{false}; - void onSignal(int) + void requestUpdate() { g_updateRequested = true; } + + std::optional argumentValue(int argc, char** argv, + std::string_view name) { - g_stop = true; - g_cv.notify_all(); + 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]] std::filesystem::path + reconcileManagedCore(const std::filesystem::path& stateDirectory, + const std::filesystem::path& fallback) + { + Void::Update::VersionStore store(stateDirectory / "updates" / + "components" / "core"); + if (auto initialized = store.initialize(); !initialized) { + Void::Log::warn("main", "Cannot initialize managed Core store: {}", + initialized.error().message()); + return fallback; + } + if (auto reconciled = store.reconcile(); !reconciled) { + Void::Log::warn("main", "Cannot reconcile managed Core store: {}", + reconciled.error().message()); + return fallback; + } + auto current = store.currentVersion(); + if (!current || !*current) { + return fallback; + } + const auto managed = store.versionPath(**current) / fallback.filename(); + return std::filesystem::is_regular_file(managed) ? managed : fallback; + } + + [[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() @@ -47,6 +360,79 @@ namespace 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); @@ -66,19 +452,62 @@ namespace } } - // Locate the Core shared library ("Echoion.ts"). - std::filesystem::path corePath() + int importIdentity(int argc, char** argv, + const std::filesystem::path& defaultIdentityPath) { - if (const char* p = std::getenv("ECHOION_CORE_PATH")) { - return p; - } - for (const char* c : - {"./Echoion.ts", "./bin/Echoion.ts", "./plugins/Echoion.ts"}) { - if (std::filesystem::exists(c)) { - return c; + 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; } } - return "./Echoion.ts"; + 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 @@ -90,38 +519,166 @@ int main(int argc, char** argv) std::abort(); }); - std::filesystem::path cfgDir = configDir(); - std::filesystem::path cfgPath = cfgDir / "config.json"; - // Optional CLI: --config - for (int i = 1; i + 1 < argc; ++i) { - if (std::string(argv[i]) == "--config") { - cfgPath = argv[i + 1]; + 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; + } + 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 = - envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()); + 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); + 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::Plugin::CoreLoader loader; + Echoion::Host::CoreLoader loader; loader.setConfigPath(cfgPath); - auto corePathResolved = corePath(); + 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"); + const auto corePathResolved = + customCoreOverride + ? configuredCorePath + : reconcileManagedCore(stateDirectory, configuredCorePath); + 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) { @@ -130,9 +687,12 @@ int main(int argc, char** argv) } core->setPluginInterface(interface); - interface->registerEventCallback([core](const Echoion::Api::PluginEvent& ev) { - std::ignore = core->onPluginEvent(ev); - }); + 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()) { @@ -145,22 +705,287 @@ int main(int argc, char** argv) } }); - core->triggerAutoConnect(); - loader.enableAutoReload(); - - std::signal(SIGINT, onSignal); - std::signal(SIGTERM, onSignal); - Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop."); - - { - std::unique_lock lock(g_mu); - g_cv.wait(lock, [] { return g_stop.load(); }); + const auto updaterExecutable = + runningExecutable->parent_path() / "echoion-updater"; + auto updateService = std::make_unique( + 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( + [service = updateService.get()](const std::string& method, + const std::string& request) { + return service->handle(method, request); + }); } - Void::Log::info("main", "Shutting down..."); + 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 new file mode 100644 index 0000000..f3b75ef --- /dev/null +++ b/EchoionStandalone/tests/test_core_loader_reload.cpp @@ -0,0 +1,153 @@ +#include "echoion/host/CoreLoader.hpp" + +#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 ytDlp = root / ".local/share/echoion/yt-dlp/yt-dlp"; + std::filesystem::create_directories(ytDlp.parent_path()); + { + std::ofstream output{ytDlp}; + output << "#!/bin/sh\necho 2026.01.01\n"; + } + 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 new file mode 100644 index 0000000..6bedd97 --- /dev/null +++ b/EchoionStandalone/tests/test_event_callback_gate.cpp @@ -0,0 +1,59 @@ +#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 new file mode 100644 index 0000000..c880af1 --- /dev/null +++ b/EchoionStandalone/tests/test_message_chunker.cpp @@ -0,0 +1,41 @@ +#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 new file mode 100644 index 0000000..43de15c --- /dev/null +++ b/EchoionStandalone/tests/test_release_manifest.cpp @@ -0,0 +1,289 @@ +#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 new file mode 100644 index 0000000..053451f --- /dev/null +++ b/EchoionStandalone/tests/test_runtime_paths.cpp @@ -0,0 +1,144 @@ +#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 / "share" / "echoion", + "packaged web root did not select share/echoion as working directory"); + 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 new file mode 100755 index 0000000..c57a4d1 --- /dev/null +++ b/EchoionStandalone/tests/test_stage_release.sh @@ -0,0 +1,62 @@ +#!/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/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" +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_service.cpp b/EchoionStandalone/tests/test_update_service.cpp new file mode 100644 index 0000000..8ed9f99 --- /dev/null +++ b/EchoionStandalone/tests/test_update_service.cpp @@ -0,0 +1,691 @@ +#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; + 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 index ff9a06b..e21039f 100644 --- a/EchoionWeb/CMakeLists.txt +++ b/EchoionWeb/CMakeLists.txt @@ -16,18 +16,17 @@ 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. -if(NOT TARGET Boost::beast) - find_package(Boost 1.87 CONFIG QUIET) - 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() -endif() +# 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) @@ -37,12 +36,12 @@ target_link_libraries(EchoionWeb Void::Data Void::Log Void::Async - Void::Net PRIVATE Threads::Threads Boost::beast Boost::asio Boost::system + Boost::url ) if(MSVC) @@ -56,7 +55,17 @@ endif() # 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). -option(ECHOION_BUILD_WEB "Build the React web frontend with npm/vite" ON) +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") @@ -72,9 +81,12 @@ if(ECHOION_BUILD_WEB) # 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_srcs CONFIGURE_DEPENDS + file(GLOB_RECURSE _web_tree_srcs CONFIGURE_DEPENDS + LIST_DIRECTORIES FALSE "${_web_frontend}/src/*" - "${_web_frontend}/public/*" + "${_web_frontend}/public/*") + set(_web_srcs + ${_web_tree_srcs} "${_web_frontend}/index.html" "${_web_frontend}/package.json" "${_web_frontend}/package-lock.json" @@ -83,8 +95,9 @@ if(ECHOION_BUILD_WEB) add_custom_command( OUTPUT "${_web_dist}/index.html" - # `npm ci` when the lockfile is newer than node_modules keeps installs - # reproducible; the stamp check avoids reinstalling on every build. + # 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}" diff --git a/EchoionWeb/frontend/package-lock.json b/EchoionWeb/frontend/package-lock.json index 21c8beb..b234a9a 100644 --- a/EchoionWeb/frontend/package-lock.json +++ b/EchoionWeb/frontend/package-lock.json @@ -894,9 +894,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -911,9 +908,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -928,9 +922,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -945,9 +936,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -962,9 +950,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -979,9 +964,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -996,9 +978,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1013,9 +992,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1030,9 +1006,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1047,9 +1020,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1064,9 +1034,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1081,9 +1048,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1098,9 +1062,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ diff --git a/EchoionWeb/frontend/public/manifest.webmanifest b/EchoionWeb/frontend/public/manifest.webmanifest index c8a0df9..ae42602 100644 --- a/EchoionWeb/frontend/public/manifest.webmanifest +++ b/EchoionWeb/frontend/public/manifest.webmanifest @@ -1,7 +1,7 @@ { "name": "Echoion Music Bot", "short_name": "Echoion", - "description": "Control the Echoion TeamSpeak music bot — play, queue, search and watch together.", + "description": "Control the Echoion TeamSpeak music bot and view live server activity.", "start_url": "/", "scope": "/", "display": "standalone", diff --git a/EchoionWeb/frontend/public/sw.js b/EchoionWeb/frontend/public/sw.js index 531d95e..ee099dc 100644 --- a/EchoionWeb/frontend/public/sw.js +++ b/EchoionWeb/frontend/public/sw.js @@ -1,12 +1,12 @@ // 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 and /ws (WebSockets aren't interceptable anyway), -// /config.json, /avatar/*, /emoji/* all fall through to the network so the UI -// never shows stale identity/config. +// 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-v2'; +const CACHE = 'echoion-shell-v4'; const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg']; self.addEventListener('install', (event) => { @@ -48,10 +48,9 @@ self.addEventListener('fetch', (event) => { // Never intercept the live control/config/media surfaces. if ( url.pathname === '/config.json' || + url.pathname.startsWith('/api/') || url.pathname.startsWith('/rpc') || - url.pathname.startsWith('/ws') || - url.pathname.startsWith('/avatar') || - url.pathname.startsWith('/emoji') + url.pathname.startsWith('/avatar') ) { return; } diff --git a/EchoionWeb/frontend/scripts/i18n-check.mjs b/EchoionWeb/frontend/scripts/i18n-check.mjs index f5051b0..c870d08 100644 --- a/EchoionWeb/frontend/scripts/i18n-check.mjs +++ b/EchoionWeb/frontend/scripts/i18n-check.mjs @@ -5,11 +5,8 @@ // - 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: -// - watch.ts state strings rendered via t(w.playerEmpty) // - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label) // - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub) -// - server-sent watch.denied reasons (grep sendDenied in -// EchoionWeb/src/WatchSession.cpp) rendered via t(msg.reason) // Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC // list below suppresses the ones we know about. // @@ -25,17 +22,6 @@ const ruFile = join(srcDir, 'i18n', 'ru.ts'); // Keys reached through variables (see header); keep in sync by hand. const KNOWN_DYNAMIC = new Set([ - // watch.ts playerEmpty / state strings - 'Nothing loaded — paste a URL above', - 'Twitch embeds require HTTPS — open the site via its https:// domain', - // server-sent watch.denied reasons (grep sendDenied in WatchSession.cpp) - 'Sign in to control playback', - 'Only the host controls playback', - 'Watch queue is full', - 'Watch queue is empty', - 'Live stream — cannot seek', - 'That viewer is no longer here', - 'Only signed-in viewers can host', // connection state rendered via t(s.connection) in Sidebar.tsx 'connected', 'disconnected', @@ -48,8 +34,8 @@ const KNOWN_DYNAMIC = new Set([ 'Focus search', 'This help', // HEADS view titles/subtitles (App.tsx) - 'Now Playing', - 'What Echoion is streaming to the channel', + 'Dashboard', + 'Live playback and TeamSpeak server activity', 'Queue', 'Reorder and manage upcoming tracks', 'Search', @@ -58,10 +44,10 @@ const KNOWN_DYNAMIC = new Set([ 'Your favorites and saved playlists', 'History & Stats', 'Playback history and server insights', - 'Watch Together', - 'Synced viewing room — everyone in step', '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 diff --git a/EchoionWeb/frontend/src/App.tsx b/EchoionWeb/frontend/src/App.tsx index 4981d18..3872007 100644 --- a/EchoionWeb/frontend/src/App.tsx +++ b/EchoionWeb/frontend/src/App.tsx @@ -1,6 +1,5 @@ import { useEffect } from 'react'; -import { appStore, boot, getStoredToken, toast } from './lib/app'; -import { initWatch } from './lib/watch'; +import { appStore, boot } from './lib/app'; import { initRouter } from './lib/router'; import { initShortcuts } from './lib/shortcuts'; import { initMediaSession } from './lib/mediaSession'; @@ -11,23 +10,23 @@ import { Sidebar } from './components/Sidebar'; import { MiniPlayer } from './components/MiniPlayer'; import { DialogHost } from './components/DialogHost'; import { ShortcutsHelp } from './components/ShortcutsHelp'; -import { NowView } from './views/NowView'; +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 { WatchView } from './views/WatchView'; import { ServerView } from './views/ServerView'; +import { UpdatesView } from './views/UpdatesView'; import { RpcView } from './views/RpcView'; const HEADS: Record = { - now: ['Now Playing', 'What Echoion is streaming to the channel'], + 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'], - watch: ['Watch Together', 'Synced viewing room — everyone in step'], server: ['Server & Admin', 'Manage subscribers and broadcast'], + updates: ['Updates', 'Runtime, Core, and plugin release control'], rpc: ['RPC / API', 'Connect to Echoion programmatically'], }; @@ -37,20 +36,12 @@ export function App() { useEffect(() => { boot(); - initWatch({ - getName: () => - (appStore.get().identity && - appStore.get().identity!.nickname) || - null, - getToken: getStoredToken, - toast, - }); initRouter(); initShortcuts(); initMediaSession(); }, []); - const [title, sub] = HEADS[s.view] || HEADS.now; + const [title, sub] = HEADS[s.view] || HEADS.dashboard; return (
@@ -82,7 +73,7 @@ export function App() {
- {s.onlineCount} {t('listening')} + {s.onlineCount} {t('online')} -
-
- {custom.map((c) => ( -
- {c.name} - :{c.name}: - -
- ))} -
-
- ); -} diff --git a/EchoionWeb/frontend/src/components/EmojiPicker.tsx b/EchoionWeb/frontend/src/components/EmojiPicker.tsx deleted file mode 100644 index 37d8a2c..0000000 --- a/EchoionWeb/frontend/src/components/EmojiPicker.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { useEffect, useRef } from 'react'; -import { useStore } from '../lib/store'; -import { - EMOJI_CATEGORIES, - emojiStore, - rememberEmoji, -} from '../lib/emoji'; -import { t } from '../i18n'; - -// A popover emoji picker: recently-used, curated Unicode categories, and the -// server's custom image emojis. `onPick` receives either a unicode char or a -// :shortcode: for a custom emoji. -export function EmojiPicker(props: { - onPick: (token: string) => void; - onClose: () => void; -}) { - const { custom, recent } = useStore(emojiStore); - const ref = useRef(null); - - useEffect(() => { - const onDoc = (e: MouseEvent) => { - if (ref.current && !ref.current.contains(e.target as Node)) { - props.onClose(); - } - }; - // Defer so the opening click doesn't immediately close it. - const id = setTimeout( - () => document.addEventListener('mousedown', onDoc), - 0 - ); - return () => { - clearTimeout(id); - document.removeEventListener('mousedown', onDoc); - }; - }, [props]); - - const pick = (token: string) => { - rememberEmoji(token); - props.onPick(token); - }; - - return ( -
- {recent.length > 0 && ( -
-
{t('Recent')}
-
- {recent.map((token, i) => - token.startsWith(':') ? ( - - ) : ( - - ) - )} -
-
- )} - {custom.length > 0 && ( -
-
{t('Custom')}
-
- {custom.map((c) => ( - - ))} -
-
- )} - {EMOJI_CATEGORIES.map((cat) => ( -
-
{cat.label}
-
- {cat.emoji.map((e) => ( - - ))} -
-
- ))} -
- ); -} diff --git a/EchoionWeb/frontend/src/components/MiniPlayer.tsx b/EchoionWeb/frontend/src/components/MiniPlayer.tsx index cd635da..08a6e01 100644 --- a/EchoionWeb/frontend/src/components/MiniPlayer.tsx +++ b/EchoionWeb/frontend/src/components/MiniPlayer.tsx @@ -14,7 +14,7 @@ async function togglePlay() { // Mini player mirrors the current track on views other than Now Playing. export function MiniPlayer() { const s = useStore(appStore); - if (s.view === 'now' || !s.current) return null; + if (s.view === 'dashboard' || !s.current) return null; const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused); const canForceSkip = !!( s.identity && diff --git a/EchoionWeb/frontend/src/components/Modal.test.tsx b/EchoionWeb/frontend/src/components/Modal.test.tsx new file mode 100644 index 0000000..7c54542 --- /dev/null +++ b/EchoionWeb/frontend/src/components/Modal.test.tsx @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { Modal } from './Modal'; + +describe('Modal accessibility', () => { + it('labels the dialog and exposes a named close control', () => { + const html = renderToStaticMarkup( + {}}> +

Review the candidate.

+
+ ); + expect(html).toContain('role="dialog"'); + expect(html).toContain('aria-modal="true"'); + expect(html).toContain('aria-labelledby='); + expect(html).toContain('aria-label="Close"'); + }); +}); diff --git a/EchoionWeb/frontend/src/components/Modal.tsx b/EchoionWeb/frontend/src/components/Modal.tsx index 61f4cda..60df469 100644 --- a/EchoionWeb/frontend/src/components/Modal.tsx +++ b/EchoionWeb/frontend/src/components/Modal.tsx @@ -1,5 +1,6 @@ -import type { ReactNode } from 'react'; +import { useEffect, useId, useRef, type KeyboardEvent, type ReactNode } from 'react'; import { CloseIcon } from './icons'; +import { t } from '../i18n'; export function Modal(props: { title: string; @@ -8,15 +9,60 @@ export function Modal(props: { footer?: ReactNode; wide?: boolean; }) { + const titleId = useId(); + const modalRef = useRef(null); + + useEffect(() => { + const previous = document.activeElement as HTMLElement | null; + const focusable = modalRef.current?.querySelector( + 'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])' + ); + focusable?.focus(); + return () => previous?.focus(); + }, []); + + function onKeyDown(event: KeyboardEvent) { + if (event.key === 'Escape') { + event.preventDefault(); + props.onClose(); + return; + } + if (event.key !== 'Tab' || !modalRef.current) return; + const focusable = Array.from( + modalRef.current.querySelectorAll( + 'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])' + ) + ); + if (!focusable.length) return; + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + } + return (
e.stopPropagation()} >
-

{props.title}

-
diff --git a/EchoionWeb/frontend/src/components/PlayerControls.tsx b/EchoionWeb/frontend/src/components/PlayerControls.tsx index df6591a..04e3564 100644 --- a/EchoionWeb/frontend/src/components/PlayerControls.tsx +++ b/EchoionWeb/frontend/src/components/PlayerControls.tsx @@ -11,11 +11,9 @@ import { } from './icons'; import { t } from '../i18n'; -// The one custom player control bar, shared by Watch Together (room /ws -// protocol) and Now Playing (bot RPC). Purely presentational: the two sync -// channels differ only in the callbacks the views pass in. Embedded players -// (YouTube/Twitch/HTML5) always run with native controls hidden; this bar is -// the only playback UI. +// Dashboard playback controls. This component is presentational; authenticated +// RPC callbacks are supplied by the dashboard while visitors receive a +// disabled, read-only transport surface. export function PlayerControls(props: { playing: boolean; positionMs: number; @@ -45,7 +43,7 @@ export function PlayerControls(props: { : 0; return (
-
+
- {open && ( -
- {local.length > 0 && ( -
-
{t('Local')}
- {local.map(renderControl)} -
- )} - {hasRoom && ( -
-
{t('Room')}
- {props.rateOptions && ( - - )} - {room.map(renderControl)} -
- )} -
- )} -
- ); -} diff --git a/EchoionWeb/frontend/src/components/Sidebar.tsx b/EchoionWeb/frontend/src/components/Sidebar.tsx index 09046ed..1a109d6 100644 --- a/EchoionWeb/frontend/src/components/Sidebar.tsx +++ b/EchoionWeb/frontend/src/components/Sidebar.tsx @@ -20,18 +20,19 @@ import { QueueIcon, SearchIcon, StatsIcon, + UpdateIcon, WatchIcon, } from './icons'; import { t, useLanguage } from '../i18n'; const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [ - { view: 'now', icon: , label: 'Now Playing' }, + { view: 'dashboard', icon: , label: 'Dashboard' }, { view: 'queue', icon: , label: 'Queue' }, { view: 'search', icon: , label: 'Search' }, { view: 'library', icon: , label: 'Library' }, { view: 'stats', icon: , label: 'History & Stats' }, - { view: 'watch', icon: , label: 'Watch Together' }, { view: 'server', icon: , label: 'Server & Admin' }, + { view: 'updates', icon: , label: 'Updates' }, { view: 'rpc', icon: , label: 'RPC / API' }, ]; @@ -67,18 +68,22 @@ export function Sidebar() {
diff --git a/EchoionWeb/frontend/src/components/TeamSpeakAdmin.tsx b/EchoionWeb/frontend/src/components/TeamSpeakAdmin.tsx new file mode 100644 index 0000000..ceeed3a --- /dev/null +++ b/EchoionWeb/frontend/src/components/TeamSpeakAdmin.tsx @@ -0,0 +1,472 @@ +import { useCallback, useEffect, useState } from 'react'; +import { safeCall, toast } from '../lib/app'; +import type { RpcMethodName } from '../lib/rpc'; +import { confirmDialog, promptDialog } from '../lib/dialog'; +import { EmptyRow } from './TrackRow'; +import { t, tf } from '../i18n'; + +interface AdminClient { + id: number; + databaseId: number | null; + uid: string | null; + nickname: string; + channelId: number; + talking: boolean; + muted: boolean; + deafened: boolean; + away: boolean; + groups: number[]; +} + +interface AdminChannel { + id: number; + name: string; + parentId: number | null; + default: boolean; + password: boolean; + maxClients: number; + currentClients: number; + clients: AdminClient[]; + channels: AdminChannel[]; +} + +interface DirectoryResponse { + server: { + name: string; + connected: boolean; + clientCount: number; + maxClients: number; + }; + channels: AdminChannel[]; +} + +interface Ban { + id: number; + uid: string | null; + nickname: string | null; + reason: string; + createdAt: number; + durationSeconds: number; +} + +interface ServerGroup { + id: number; + name: string; + default: boolean; +} + +export function TeamSpeakAdmin() { + const [directory, setDirectory] = useState(null); + const [bans, setBans] = useState([]); + const [groups, setGroups] = useState([]); + const [loading, setLoading] = useState(false); + + const refresh = useCallback(async () => { + setLoading(true); + const [nextDirectory, nextBans, nextGroups] = await Promise.all([ + safeCall('GetTeamSpeakDirectory'), + safeCall<{ bans?: Ban[] }>('GetTeamSpeakBans'), + safeCall<{ groups?: ServerGroup[] }>('GetTeamSpeakServerGroups'), + ]); + if (nextDirectory) setDirectory(nextDirectory); + if (nextBans) setBans(nextBans.bans || []); + if (nextGroups) setGroups(nextGroups.groups || []); + setLoading(false); + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const mutate = useCallback( + async ( + method: RpcMethodName, + params: Record, + message: string + ) => { + const result = await safeCall(method, params); + if (!result) return false; + toast(message); + await refresh(); + return true; + }, + [refresh] + ); + + async function sendServerMessage() { + const message = await promptDialog({ + title: t('Server message'), + message: t('Message sent to every connected TeamSpeak client:'), + confirmLabel: t('Send'), + }); + if (message) { + await mutate( + 'SendTeamSpeakServerMessage', + { message }, + t('Server message sent') + ); + } + } + + async function createChannel(parentId = 0) { + const name = await promptDialog({ + title: t('Create channel'), + message: t('Channel name:'), + confirmLabel: t('Create'), + }); + if (name) { + await mutate( + 'CreateTeamSpeakChannel', + { name, parentId, permanent: true }, + t('Channel created') + ); + } + } + + function ClientRow({ client }: { client: AdminClient }) { + return ( +
+
+ + {client.nickname} + #{client.id} + {client.away && {t('away')}} + {client.muted && {t('muted')}} + {client.deafened && {t('deafened')}} +
+
+ UID: {client.uid || '—'} + DB: {client.databaseId || '—'} + {t('Groups')}: {client.groups.join(', ') || '—'} +
+
+ + + {client.databaseId && ( + + )} + {client.databaseId && client.groups.length > 0 && ( + + )} + + +
+
+ ); + } + + function Channel({ channel, depth = 0 }: { channel: AdminChannel; depth?: number }) { + return ( +
+
+ {channel.name} + #{channel.id} + + {channel.currentClients}/{channel.maxClients || '∞'} + + + + + + {!channel.default && ( + + )} +
+ {channel.clients.map((client) => ( + + ))} + {channel.channels.map((child) => ( + + ))} +
+ ); + } + + return ( +
+
+
+
+

{directory?.server.name || t('TeamSpeak')}

+
+ {directory?.server.connected ? t('Connected') : t('Disconnected')} + {' · '} + {directory?.server.clientCount || 0}/{directory?.server.maxClients || '∞'} +
+
+
+ + + +
+
+
+ {directory?.channels.length ? ( + directory.channels.map((channel) => ( + + )) + ) : ( + + )} +
+
+ +
+
+

{t('Bans')}

+ {bans.length} +
+
+ {bans.length ? ( + bans.map((ban) => ( +
+
+ {ban.nickname || ban.uid || `#${ban.id}`} +
{ban.reason || t('No reason')}
+
+ + {ban.durationSeconds ? `${ban.durationSeconds}s` : t('Permanent')} + + +
+ )) + ) : ( + + )} +
+
+
+ ); +} diff --git a/EchoionWeb/frontend/src/components/WatchSearch.tsx b/EchoionWeb/frontend/src/components/WatchSearch.tsx deleted file mode 100644 index 6c27894..0000000 --- a/EchoionWeb/frontend/src/components/WatchSearch.tsx +++ /dev/null @@ -1,145 +0,0 @@ -import { useState } from 'react'; -import { rpc } from '../lib/rpc'; -import { send, watchStore } from '../lib/watch'; -import { toast } from '../lib/app'; -import { useStore } from '../lib/store'; -import { thumbFor } from '../lib/format'; -import type { Track } from '../lib/types'; -import { t, tf } from '../i18n'; - -// Normalize a Twitch channel entry: accept a bare login name, an @handle, or a -// full twitch.tv URL, and reduce it to the channel login the embed player -// expects. Numeric ids pass through (best effort — resolving them to a login -// would need the Helix API, which isn't wired up). -function normalizeTwitchChannel(input: string): string { - let s = input.trim(); - const m = s.match(/twitch\.tv\/([^/?#]+)/i); - if (m) s = m[1]; - s = s.replace(/^@/, ''); - return s.toLowerCase().replace(/[^a-z0-9_]/g, ''); -} - -// Add tracks to a watch room from inside it. YouTube uses the unauthenticated -// SearchTracks RPC (results added by title + thumbnail); Twitch has no search -// backend, so it offers an add-by-channel-name/id field instead. -export function WatchSearch({ disabled }: { disabled: boolean }) { - const w = useStore(watchStore); - const [query, setQuery] = useState(''); - const [channel, setChannel] = useState(''); - const [results, setResults] = useState([]); - const [open, setOpen] = useState(false); - - if (w.sourceChoice === 'twitch') { - return ( -
-
{ - e.preventDefault(); - const ch = normalizeTwitchChannel(channel); - if (!ch) return; - send({ - type: 'watch.queue.add', - source: 'twitch', - url: ch, - title: ch, - }); - toast(tf('Added “{0}” to queue', ch)); - setChannel(''); - }} - > - setChannel(e.target.value)} - placeholder={t( - 'Twitch channel name or id to queue…' - )} - autoComplete="off" - disabled={disabled} - /> - -
-
- ); - } - - return ( -
-
{ - e.preventDefault(); - const q = query.trim(); - if (!q) return; - try { - const res = await rpc.call<{ tracks?: Track[] }>( - 'SearchTracks', - { query: q } - ); - setResults((res && res.tracks) || []); - setOpen(true); - } catch (err) { - toast((err as { message?: string }).message || 'error'); - } - }} - > - setQuery(e.target.value)} - placeholder={t('Search YouTube to queue…')} - autoComplete="off" - disabled={disabled} - /> - -
- {open && results.length > 0 && ( -
- {results.slice(0, 8).map((tr, i) => ( - - ))} -
- )} -
- ); -} diff --git a/EchoionWeb/frontend/src/components/icons.tsx b/EchoionWeb/frontend/src/components/icons.tsx index ee82d0a..9669754 100644 --- a/EchoionWeb/frontend/src/components/icons.tsx +++ b/EchoionWeb/frontend/src/components/icons.tsx @@ -57,9 +57,15 @@ export const StatsIcon = makeIcon( export const WatchIcon = makeIcon( 'M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12zM9.5 8.5l7 3.5-7 3.5v-7z' ); +export const RoomsIcon = makeIcon( + 'M4 4h6v6H4V4zm10 0h6v6h-6V4zM4 14h6v6H4v-6zm10 0h6v6h-6v-6z' +); export const GearIcon = makeIcon( 'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z' ); +export const UpdateIcon = makeIcon( + 'M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.96-.69 2.8l1.46 1.46A7.93 7.93 0 0020 12c0-4.42-3.58-8-8-8zm-5.31 5.2L5.23 7.74A7.93 7.93 0 004 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3c-3.31 0-6-2.69-6-6 0-1.01.25-1.96.69-2.8z' +); export const CodeIcon = makeIcon( 'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z' ); @@ -76,6 +82,8 @@ export const RefreshIcon = makeIcon( 'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z' ); export const PlusIcon = makeIcon('M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z'); +export const ArrowUpIcon = makeIcon('M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z'); +export const ArrowDownIcon = makeIcon('M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.59-5.58L4 12l8 8 8-8z'); export const VolumeIcon = makeIcon( 'M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z' ); diff --git a/EchoionWeb/frontend/src/i18n/ru.ts b/EchoionWeb/frontend/src/i18n/ru.ts index e703aa3..9544bce 100644 --- a/EchoionWeb/frontend/src/i18n/ru.ts +++ b/EchoionWeb/frontend/src/i18n/ru.ts @@ -4,13 +4,14 @@ export const ru: Record = { // Sidebar / navigation - 'Now Playing': 'Сейчас играет', + 'Dashboard': 'Панель', 'Queue': 'Очередь', 'Search': 'Поиск', 'Library': 'Библиотека', 'History & Stats': 'История и статистика', 'Watch Together': 'Совместный просмотр', 'Server & Admin': 'Сервер и админ', + 'Updates': 'Обновления', 'RPC / API': 'RPC / API', 'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3', 'Connect': 'Подключиться', @@ -23,18 +24,161 @@ export const ru: Record = { 'connected': 'подключено', 'disconnected': 'отключено', 'error': 'ошибка', - 'listening': 'слушают', // View headers - 'What Echoion is streaming to the channel': 'Что Echoion стримит в канал', + 'Live playback and TeamSpeak server activity': + 'Текущее воспроизведение и активность сервера TeamSpeak', 'Reorder and manage upcoming tracks': 'Управляйте порядком предстоящих треков', 'Find tracks across YouTube and Yandex Music': 'Ищите треки на YouTube и в Яндекс Музыке', 'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты', 'Playback history and server insights': 'История воспроизведения и статистика сервера', - 'Synced viewing room — everyone in step': 'Синхронный просмотр — все в ногу', 'Manage subscribers and broadcast': 'Управление подписчиками и объявления', + 'Runtime, Core, and plugin release control': + 'Управление выпусками среды, ядра и плагинов', 'Connect to Echoion programmatically': 'Подключение к Echoion из кода', + // Updates + 'Runtime bundle': 'Среда выполнения', + 'Core': 'Ядро', + 'Plugins': 'Плагины', + 'default source': 'источник по умолчанию', + 'stable': 'стабильный', + 'Idle': 'Ожидание', + 'Installed': 'Установлено', + 'Available': 'Доступно', + 'Up to date': 'Актуальная версия', + 'Candidate attributes': 'Свойства кандидата', + 'Unsigned': 'Без подписи', + 'Signed': 'Подписано', + 'Downgrade': 'Понижение версии', + 'Incompatible': 'Несовместимо', + 'Restart required': 'Нужен перезапуск', + 'Apply {0}': 'Применить {0}', + 'No update': 'Нет обновления', + 'Rollback to {0}': 'Откатить до {0}', + 'No rollback': 'Откат недоступен', + 'Enabled': 'Включено', + 'Source': 'Источник', + 'Channel': 'Канал', + '{0} source': 'Источник: {0}', + '{0} channel': 'Канал: {0}', + 'Auto-apply': 'Применять автоматически', + 'Build default': 'Встроенное значение', + 'Feed URL': 'URL ленты', + 'Empty uses the release build default': + 'Пустое поле использует адрес из сборки выпуска', + 'Bearer token environment variable': 'Переменная окружения с Bearer-токеном', + 'Secret is present in the service environment': + 'Секрет присутствует в окружении службы', + 'Secret is missing from the service environment': + 'Секрет отсутствует в окружении службы', + 'Secret presence was not reported': 'Наличие секрета не сообщено службой', + 'No bearer token configured': 'Bearer-токен не настроен', + 'Permit manual unsigned staging': + 'Разрешить ручную подготовку обновлений без подписи', + 'Ed25519 trust keys': 'Доверенные ключи Ed25519', + 'Only public verification keys belong here.': + 'Здесь должны находиться только открытые ключи проверки.', + 'Add key': 'Добавить ключ', + 'Key ID': 'ID ключа', + 'Public key': 'Открытый ключ', + 'Remove key {0}': 'Удалить ключ {0}', + 'No custom keys; the build-injected keyring is used when available.': + 'Пользовательских ключей нет; используется встроенное в сборку хранилище ключей.', + 'Remove source': 'Удалить источник', + 'Managed': 'Управляемый', + 'Unmanaged': 'Неуправляемый', + 'Apply': 'Применить', + 'Rollback': 'Откатить', + 'Never': 'Никогда', + 'Automatic updates armed': 'Автоматические обновления активны', + 'Automatic updates paused': 'Автоматические обновления приостановлены', + 'Last check: {0}': 'Последняя проверка: {0}', + 'Next: {0}': 'Следующая: {0}', + 'Check now': 'Проверить сейчас', + 'Checking…': 'Проверка…', + 'Loading update state…': 'Загрузка состояния обновлений…', + 'Installed plugins': 'Установленные плагины', + 'Only managed plugins participate in update activation.': + 'В активации обновлений участвуют только управляемые плагины.', + 'managed': 'управляемых', + 'No installed plugins reported': 'Установленные плагины не обнаружены', + 'Update history': 'История обновлений', + 'Checks, staging, activation, and rollback outcomes': + 'Результаты проверок, подготовки, активации и откатов', + 'When': 'Когда', + 'Target': 'Цель', + 'Action': 'Действие', + 'Result': 'Результат', + 'Recorded': 'Записано', + 'No update history yet': 'История обновлений пока пуста', + 'POLICY DECK': 'ПАНЕЛЬ ПОЛИТИКИ', + 'Automation and trust': 'Автоматизация и доверие', + 'Configure timing, independent channels, feeds, and public trust roots.': + 'Настройте расписание, независимые каналы, ленты и открытые корни доверия.', + 'Discard changes': 'Отменить изменения', + 'Save policy': 'Сохранить политику', + 'Saving…': 'Сохранение…', + 'Enable the update scheduler': 'Включить планировщик обновлений', + 'Check interval': 'Интервал проверки', + 'Schedule jitter': 'Разброс расписания', + 'Maintenance start (UTC)': 'Начало обслуживания (UTC)', + 'Maintenance duration': 'Длительность обслуживания', + 'Maximum runtime deferral': 'Максимальная отсрочка среды', + 'Previous healthy versions retained': 'Хранимые предыдущие исправные версии', + 'Component channels': 'Каналы компонентов', + 'Selections remain independent; incompatible cohorts stay staged.': + 'Выбор остаётся независимым; несовместимые наборы остаются подготовленными.', + 'Never modify loose local plugin files': + 'Никогда не изменять отдельные локальные файлы плагинов', + 'Plugin channel overrides': 'Переопределения каналов плагинов', + 'Pin individual managed plugins to another source or channel.': + 'Назначьте отдельным управляемым плагинам другой источник или канал.', + 'Add override': 'Добавить переопределение', + 'No plugin overrides': 'Переопределений плагинов нет', + 'Sources and trust roots': 'Источники и корни доверия', + 'Secret values stay in the service environment and are never returned here.': + 'Значения секретов остаются в окружении службы и никогда не возвращаются сюда.', + 'Add source': 'Добавить источник', + 'Confirm unsigned update': 'Подтвердите обновление без подписи', + 'This artifact has no trusted signature. Type {0} to authorize this exact candidate.': + 'У этого артефакта нет доверенной подписи. Введите {0}, чтобы разрешить именно этот кандидат.', + 'Authorize unsigned candidate': 'Разрешить кандидат без подписи', + 'Confirm downgrade': 'Подтвердите понижение версии', + 'A downgrade may make saved state incompatible. Type DOWNGRADE to continue.': + 'Понижение версии может сделать сохранённое состояние несовместимым. Введите DOWNGRADE для продолжения.', + 'Continue with downgrade': 'Продолжить понижение версии', + 'Restart Echoion': 'Перезапустить Echoion', + 'Applying this update restarts Echoion after it becomes idle. Continue?': + 'После перехода в режим ожидания Echoion будет перезапущен для применения обновления. Продолжить?', + 'Apply and restart': 'Применить и перезапустить', + '{0} update queued': 'Обновление {0} поставлено в очередь', + 'Confirm rollback': 'Подтвердите откат', + 'Roll back {0} to {1}?': 'Откатить {0} до {1}?', + 'Rollback queued': 'Откат поставлен в очередь', + 'Enable unsigned update policy': 'Разрешить политику обновлений без подписи', + 'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.': + 'Подготовка без подписи будет разрешена для: {0}. Введите ENABLE UNSIGNED, чтобы сохранить политику.', + 'Save unsafe policy': 'Сохранить небезопасную политику', + 'Update policy saved': 'Политика обновлений сохранена', + 'Add update source': 'Добавить источник обновлений', + 'Use a short ID made from letters, numbers, dots, dashes, or underscores.': + 'Используйте короткий ID из букв, цифр, точек, дефисов или подчёркиваний.', + 'Invalid source ID': 'Недопустимый ID источника', + 'That source already exists': 'Такой источник уже существует', + 'Move every component off this source before removing it': + 'Перед удалением переведите все компоненты на другой источник', + 'Remove update source': 'Удалить источник обновлений', + 'Remove source {0} and its public keys?': + 'Удалить источник {0} и его открытые ключи?', + 'Add plugin channel override': 'Добавить переопределение канала плагина', + 'Enter the exact managed plugin ID.': 'Введите точный ID управляемого плагина.', + 'That plugin override already exists': + 'Переопределение для этого плагина уже существует', + 'Update check completed': 'Проверка обновлений завершена', + 'Update policy, trust keys, and activation controls are restricted to administrators.': + 'Политика обновлений, доверенные ключи и активация доступны только администраторам.', + // Now playing 'Nothing playing': 'Ничего не играет', 'Up Next': 'Далее', @@ -122,75 +266,31 @@ export const ru: Record = { '{0}% skip rate': '{0}% пропусков', '{0} requests': '{0} запросов', - // Watch together - 'Nothing loaded — paste a URL above': 'Ничего не загружено — вставьте ссылку выше', - 'Twitch embeds require HTTPS — open the site via its https:// domain': - 'Встраивание Twitch требует HTTPS — откройте сайт по его https:// адресу', - 'YouTube URL to watch together': 'Ссылка YouTube для совместного просмотра', - 'Twitch channel or URL to watch together': 'Канал или ссылка Twitch для совместного просмотра', - 'Video URL': 'Видео по ссылке', - 'Embed': 'Встраивание', - 'Direct video or .m3u8 URL to watch together': - 'Прямая ссылка на видео или .m3u8 для совместного просмотра', - 'Embed URL (Kodik, etc.) to watch together': - 'Ссылка для встраивания (Kodik и др.) для совместного просмотра', + // Shared playback and action labels 'Load': 'Загрузить', - '+ Queue': '+ В очередь', - 'Add to the watch queue': 'Добавить в очередь просмотра', - 'Guest — sign in to control': 'Гость — войдите, чтобы управлять', - 'You are hosting': 'Вы ведущий', - 'Viewer': 'Зритель', - 'Synced': 'Синхронно', - 'Resync': 'Синхронизировать', - 'Resynced to room': 'Синхронизировано с комнатой', - 'Live stream — cannot seek': 'Прямой эфир — перемотка недоступна', - 'LIVE': 'ЭФИР', - 'In the room': 'В комнате', - 'Room chat': 'Чат комнаты', - 'Say something…': 'Скажите что-нибудь…', - 'Send': 'Отправить', - 'Host': 'Ведущий', - 'Host only': 'Только ведущий', 'Play next': 'Следующее', - '(you)': '(вы)', - 'Buffering…': 'Буферизация…', - 'In sync': 'Синхронно', - 'Nothing queued — paste a URL and hit “+ Queue”': 'Очередь пуста — вставьте ссылку и нажмите «+ В очередь»', - 'Remove from queue': 'Убрать из очереди', - 'added by {0}': 'добавил {0}', + 'LIVE': 'ЭФИР', + 'Send': 'Отправить', 'Fullscreen': 'Во весь экран', - 'Fullscreen unavailable': 'Полноэкранный режим недоступен', - 'Playback quality (best effort — YouTube may keep auto)': - 'Качество (по возможности — YouTube может оставить авто)', - 'Auto': 'Авто', - 'Not allowed': 'Недостаточно прав', - // Watch Together protocol extensions (items 3, 4, 5) - 'New room name…': 'Название новой комнаты…', - 'Create / join': 'Создать / войти', - 'Make host': 'Назначить ведущим', - 'That viewer is no longer here': 'Этого зрителя уже нет', - 'Only signed-in viewers can host': 'Вести может только вошедший зритель', - // Watch player & UX (items 7, 8, 16, 20) - 'Playback speed': 'Скорость воспроизведения', - 'Search YouTube to queue…': 'Найти на YouTube для очереди…', - 'Recent': 'Недавние', - 'Custom': 'Свои', - 'Custom emojis': 'Свои эмодзи', - 'Add emoji': 'Добавить эмодзи', - 'Emoji added': 'Эмодзи добавлено', - 'Emoji removed': 'Эмодзи удалено', - 'shortcode (a-z0-9_)': 'код (a-z0-9_)', - 'Choose an image file': 'Выберите файл изображения', - 'Emoji name must be 1-32 chars of a-z, 0-9, _': 'Имя: 1–32 символа a-z, 0-9, _', - 'Emoji image too large (max ~64KB)': 'Изображение слишком большое (макс ~64КБ)', // Server & admin + 'Administration': 'Администрирование', + 'Administrator authentication required': 'Требуется вход администратора', + 'Sign in with an account in a configured TeamSpeak admin group.': + 'Войдите под учётной записью, входящей в настроенную группу администраторов TeamSpeak.', + 'TeamSpeak': 'TeamSpeak', + 'Echoion service': 'Служба Echoion', + 'Bot messaging and runtime operations': + 'Сообщения бота и управление службой', 'Subscribers': 'Подписчики', + 'Emojis': 'Эмодзи', + 'Audit history': 'Журнал действий', + 'Room emojis moved to VoidWatch and are managed from its administration page.': + 'Эмодзи комнат перенесены в VoidWatch и управляются на его странице администрирования.', + 'Open VoidWatch admin ↗': 'Открыть панель VoidWatch ↗', 'Announce…': 'Объявление…', 'Reload config': 'Перезагрузить конфиг', 'Restart web UI': 'Перезапустить веб-интерфейс', - 'Stop and start the web server without touching the bot': - 'Остановить и запустить веб-сервер, не трогая бота', 'Unsub all': 'Отписать всех', 'No subscribers': 'Нет подписчиков', 'Nobody online right now': 'Сейчас никого нет в сети', @@ -198,7 +298,6 @@ export const ru: Record = { 'Offline': 'Не в сети', 'Unsub': 'Отписать', 'Unsubscribe {0}?': 'Отписать {0}?', - 'Unsubscribed {0}': '{0} отписан', 'Announcement to all subscribers:': 'Объявление всем подписчикам:', 'Announcement sent': 'Объявление отправлено', 'Configuration reloaded': 'Конфигурация перезагружена', @@ -210,11 +309,92 @@ export const ru: Record = { 'Удалить ВСЕ подписки? Это нельзя отменить.', 'All subscriptions removed': 'Все подписки удалены', 'Listening': 'Слушает', - 'Audit log': 'Журнал аудита', 'Refresh': 'Обновить', 'No audit entries yet': 'Записей аудита пока нет', 'client #{0}': 'клиент №{0}', + // Public TeamSpeak directory + 'TeamSpeak server': 'Сервер TeamSpeak', + 'Complete channel directory': 'Полное дерево каналов', + 'Connected': 'Подключено', + 'Disconnected': 'Отключено', + 'No channels available': 'Нет доступных каналов', + 'Password protected': 'Защищён паролем', + 'Talking': 'Говорит', + 'Away': 'Отошёл', + 'Muted': 'Микрофон выключен', + 'Deafened': 'Звук выключен', + 'clients': 'клиентов', + 'channels': 'каналов', + 'capacity': 'вместимость', + 'online': 'в сети', + 'default': 'по умолчанию', + 'locked': 'закрыт', + 'away': 'отошёл', + 'muted': 'микрофон выкл.', + 'deafened': 'звук выкл.', + + // TeamSpeak administration + 'No TeamSpeak topology available': 'Дерево TeamSpeak недоступно', + 'Message': 'Сообщение', + 'Message {0}': 'Сообщение для {0}', + 'Private message:': 'Личное сообщение:', + 'Channel message:': 'Сообщение в канал:', + 'Message sent': 'Сообщение отправлено', + 'Server message': 'Сообщение серверу', + 'Message sent to every connected TeamSpeak client:': + 'Сообщение всем подключённым клиентам TeamSpeak:', + 'Server message sent': 'Сообщение серверу отправлено', + 'Move': 'Переместить', + 'Move {0}': 'Переместить {0}', + 'Destination channel ID:': 'ID целевого канала:', + 'Client moved': 'Клиент перемещён', + 'Kick': 'Выгнать', + 'Kick {0}': 'Выгнать {0}', + 'Kick this client from the server?': 'Выгнать этого клиента с сервера?', + 'Client kicked': 'Клиент выгнан', + 'Ban': 'Заблокировать', + 'Ban {0}': 'Заблокировать {0}', + 'Duration in seconds (0 = permanent):': + 'Срок в секундах (0 = бессрочно):', + 'Apply this ban now?': 'Заблокировать этого клиента сейчас?', + 'Client banned': 'Клиент заблокирован', + 'Bans': 'Блокировки', + 'No bans': 'Блокировок нет', + 'No reason': 'Без причины', + 'Permanent': 'Бессрочно', + 'Remove ban': 'Снять блокировку', + 'Remove this TeamSpeak ban?': 'Снять эту блокировку TeamSpeak?', + 'Unban': 'Разблокировать', + 'Ban removed': 'Блокировка снята', + 'Groups': 'Группы', + 'Current groups': 'Текущие группы', + 'Server group ID:': 'ID серверной группы:', + 'Add server group': 'Добавление в серверную группу', + 'Add group': 'Добавить в группу', + 'Group added': 'Клиент добавлен в группу', + 'Remove server group': 'Удаление из серверной группы', + 'Remove group': 'Удалить из группы', + 'Group removed': 'Клиент удалён из группы', + 'Create channel': 'Создать канал', + 'Channel name:': 'Название канала:', + 'Create': 'Создать', + 'Channel created': 'Канал создан', + 'Add child': 'Добавить подканал', + 'Rename channel': 'Переименовать канал', + 'Edit': 'Изменить', + 'Channel updated': 'Канал обновлён', + 'Reorder': 'Переместить', + 'Reorder channel': 'Переместить канал', + 'Parent channel ID (0 = root):': 'ID родительского канала (0 = корень):', + 'Previous sibling channel ID (0 = first):': + 'ID предыдущего канала на этом уровне (0 = первый):', + 'Channel reordered': 'Канал перемещён', + 'Delete channel': 'Удалить канал', + 'Delete {0} and its contents?': 'Удалить {0} вместе с содержимым?', + 'Channel deleted': 'Канал удалён', + 'Continue': 'Продолжить', + // RPC view 'Connect programmatically': 'Программное подключение', 'Copy snippet': 'Скопировать пример', @@ -259,22 +439,7 @@ export const ru: Record = { 'Menu': 'Меню', 'Back 10 seconds': 'Назад на 10 секунд', 'Forward 10 seconds': 'Вперёд на 10 секунд', - 'Leave room': 'Покинуть комнату', - 'Leave this room': 'Покинуть эту комнату', - 'Room': 'Комната', - 'Watch together': 'Смотреть вместе', - 'Refresh rooms': 'Обновить список комнат', - 'Join a room to watch in sync, or create your own.': - 'Войдите в комнату для синхронного просмотра или создайте свою.', - 'No active rooms yet — create one below.': - 'Активных комнат пока нет — создайте свою ниже.', - '{0} watching': '{0} смотрят', - 'Tap to unmute': 'Нажмите, чтобы включить звук', - 'Add channel': 'Добавить канал', - 'Twitch channel name or id to queue…': 'Имя или ID Twitch-канала для очереди…', 'Clear queue': 'Очистить очередь', - 'Watch queue is full': 'Очередь просмотра заполнена', - 'Watch queue is empty': 'Очередь просмотра пуста', 'Confirm': 'Подтвердить', 'OK': 'ОК', 'Save': 'Сохранить', @@ -286,17 +451,5 @@ export const ru: Record = { 'Playlist name': 'Название плейлиста', 'Save playlist': 'Сохранить плейлист', - // Controllable embeds (Kodik / Playerjs) - 'Embed synced': 'Встраиваемый плеер синхронизирован', - 'Embed is view-only': 'Встраиваемый плеер — только просмотр', - 'Settings': 'Настройки', - 'Local': 'Локально', - 'Quality': 'Качество', - 'Speed': 'Скорость', - 'Voiceover': 'Озвучка', - 'Episode': 'Серия', - 'Subtitles': 'Субтитры', - 'Off': 'Выкл.', - 'Choose': 'Выбрать', - 'Only the host can change this': 'Изменять может только ведущий', + 'Add': 'Добавить', }; diff --git a/EchoionWeb/frontend/src/lib/app.ts b/EchoionWeb/frontend/src/lib/app.ts index c8b1d1f..28fee36 100644 --- a/EchoionWeb/frontend/src/lib/app.ts +++ b/EchoionWeb/frontend/src/lib/app.ts @@ -5,10 +5,9 @@ import { rpc, type RpcMethodName } from './rpc'; import { Store } from './store'; import { t, tf, setLanguage, getLanguage } from '../i18n'; -import { setWatchName } from './watch'; -import { loadCustomEmojis } from './emoji'; import type { Identity, + PublicDashboard, QueueEntry, ServerInfo, Status, @@ -17,13 +16,13 @@ import type { } from './types'; export type ViewName = - | 'now' + | 'dashboard' | 'queue' | 'search' | 'library' | 'stats' - | 'watch' | 'server' + | 'updates' | 'rpc'; export interface AppState { @@ -41,6 +40,8 @@ export interface AppState { durationMs: number; onlineCount: number; listeners: Subscriber[]; + publicDashboard: PublicDashboard | null; + watchUrl: string; toast: string | null; // Server-wide switch for the Now Playing video preview (item 11), from // /config.json; users can still disable it locally. @@ -50,10 +51,14 @@ export interface AppState { // Sidebar drawer on small screens (hamburger in the header); ignored by // CSS on desktop widths where the sidebar is always visible. sidebarOpen: boolean; + capabilities: { + plugins: boolean; + webExtensions: boolean; + }; } export const appStore = new Store({ - view: 'now', + view: 'dashboard', connection: 'disconnected', identity: null, status: null, @@ -67,10 +72,16 @@ export const appStore = new Store({ durationMs: 0, onlineCount: 0, listeners: [], + publicDashboard: null, + watchUrl: '', toast: null, nowPlayingVideoAllowed: true, shortcutsOpen: false, sidebarOpen: false, + capabilities: { + plugins: false, + webExtensions: false, + }, }); // ── toast ──────────────────────────────────────────────────────────────────── @@ -123,9 +134,7 @@ export async function changeLanguage(language: 'en' | 'ru') { export function applyIdentity(auth: Identity | null) { appStore.set({ identity: auth }); if (auth) { - setWatchName(auth.nickname || null); void loadUserPrefs(); - void loadCustomEmojis(); } } @@ -175,6 +184,7 @@ export async function connectWithToken(tokenInput: string) { const auth = (await rpc.authenticate(token)) as Identity; localStorage.setItem('echoion.token', token); applyIdentity(auth); + await loadCapabilities(); toast(tf('Welcome, {0}!', auth.nickname || t('friend'))); } refreshAll(); @@ -209,9 +219,6 @@ export function showView(view: ViewName) { // Navigation closes the mobile drawer. appStore.set({ view, sidebarOpen: false }); // Reflect the selection in the URL for back/forward + shareable links. - // The watch view owns its own #watch/ hash (see watch.ts), so a - // re-selection never clobbers an existing room deep link. - if (view === 'watch' && location.hash.startsWith('#watch')) return; const target = `#${view}`; if (location.hash !== target) location.hash = target; } @@ -274,6 +281,47 @@ export async function loadFavorites() { // ── boot ───────────────────────────────────────────────────────────────────── let booted = false; +let dashboardEtag = ''; + +export async function refreshPublicDashboard() { + try { + const response = await fetch('/api/public/dashboard', { + headers: dashboardEtag ? { 'If-None-Match': dashboardEtag } : {}, + cache: 'no-cache', + }); + if (response.status === 304) return; + if (!response.ok) return; + const dashboard = (await response.json()) as PublicDashboard; + dashboardEtag = response.headers.get('ETag') || ''; + const state = appStore.get(); + const publicTrack = dashboard.playback.track; + const sameTrack = + publicTrack && state.current && publicTrack.id === state.current.id; + const current = publicTrack + ? { + ...(sameTrack ? state.current! : {}), + ...publicTrack, + duration: + publicTrack.durationMs ?? publicTrack.duration ?? 0, + } + : null; + appStore.set({ + publicDashboard: dashboard, + current, + status: { + ...(state.status || {}), + isPlaying: dashboard.playback.isPlaying, + isPaused: dashboard.playback.isPaused, + volume: dashboard.playback.volume, + }, + positionMs: dashboard.playback.positionMs, + durationMs: current?.duration || 0, + onlineCount: dashboard.server.clientCount, + }); + } catch { + /* The RPC login remains usable if the public snapshot is unavailable. */ + } +} export function boot() { if (booted) return; @@ -282,24 +330,29 @@ export function boot() { // Apply the persisted language before anything renders text. setLanguage(getLanguage(), false); - // Server config: the Now Playing video preview can be disabled globally. + // Server config: the video preview policy and external VoidWatch link. fetch('/config.json') .then((r) => r.json()) .then((cfg) => { - if (cfg && cfg.nowPlayingVideo === false) { - appStore.set({ nowPlayingVideoAllowed: false }); - } + appStore.set({ + nowPlayingVideoAllowed: cfg?.nowPlayingVideo !== false, + watchUrl: + typeof cfg?.watchUrl === 'string' ? cfg.watchUrl : '', + }); }) .catch(() => { /* keep the default (allowed) */ }); rpc.onState = (s) => appStore.set({ connection: s }); + void refreshPublicDashboard(); + setInterval(() => void refreshPublicDashboard(), 5000); // After an automatic reconnect, restore the authenticated session from // the stored token (or autologin) and pull fresh state. rpc.onReconnected = async () => { await restoreSession(); + await loadCapabilities(); refreshAll(); toast(t('Reconnected')); }; @@ -334,6 +387,9 @@ export function boot() { }); } }); + rpc.on('plugins.updated', () => { + if (appStore.get().capabilities.webExtensions) void loadWebExtensions(); + }); // Local 1s ticker keeps the progress bar moving between server updates. setInterval(() => { @@ -360,6 +416,92 @@ export function boot() { // Session restore is independent of the connection: even if auth fails // we still refresh so guests see live state instead of a blank app. await restoreSession(); + await loadCapabilities(); refreshAll(); })(); } + +async function loadCapabilities() { + const capabilities = await safeCall( + 'GetCapabilities' + ); + if (capabilities) { + appStore.set({ capabilities }); + if (capabilities.webExtensions) await loadWebExtensions(); + } +} + +interface PluginWebAsset { + id: string; + javascript: string; + css: string; +} + +interface LoadedWebExtension { + signature: string; + cleanup?: () => void; +} + +const loadedWebExtensions = new Map(); + +function unloadWebExtension(id: string) { + const loaded = loadedWebExtensions.get(id); + if (!loaded) return; + try { + loaded.cleanup?.(); + } catch (error) { + console.error(`Echoion plugin web asset ${id} cleanup failed`, error); + } + document + .querySelectorAll(`style[data-echoion-plugin="${CSS.escape(id)}"]`) + .forEach((style) => style.remove()); + loadedWebExtensions.delete(id); +} + +async function loadWebExtensions() { + const response = await safeCall<{ assets?: PluginWebAsset[] }>( + 'GetPluginExtensions' + ); + if (!response) return; + const assets = response.assets || []; + const currentIds = new Set(assets.map((asset) => asset.id).filter(Boolean)); + for (const id of loadedWebExtensions.keys()) { + if (!currentIds.has(id)) unloadWebExtension(id); + } + for (const asset of assets) { + if (!asset.id) continue; + const signature = `${asset.javascript}\0${asset.css}`; + if (loadedWebExtensions.get(asset.id)?.signature === signature) continue; + unloadWebExtension(asset.id); + let style: HTMLStyleElement | undefined; + if (asset.css) { + style = document.createElement('style'); + style.dataset.echoionPlugin = asset.id; + style.textContent = asset.css; + document.head.appendChild(style); + } + try { + const host = { + call: async (plugin: string, method: string, params: unknown = {}) => + rpc.call('PluginCall', { + plugin, + method, + params: JSON.stringify(params), + }), + store: appStore, + toast, + }; + const cleanup = new Function( + 'Echoion', + `'use strict';\n${asset.javascript}` + )(host); + loadedWebExtensions.set(asset.id, { + signature, + cleanup: typeof cleanup === 'function' ? cleanup : undefined, + }); + } catch (error) { + style?.remove(); + console.error(`Echoion plugin web asset ${asset.id} failed`, error); + } + } +} diff --git a/EchoionWeb/frontend/src/lib/auditMethods.test.ts b/EchoionWeb/frontend/src/lib/auditMethods.test.ts new file mode 100644 index 0000000..6c5f38e --- /dev/null +++ b/EchoionWeb/frontend/src/lib/auditMethods.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from 'vitest'; +import { auditMethodName } from './auditMethods'; + +describe('audit RPC method mapping', () => { + it('keeps removed room audit slots and newer methods aligned', () => { + expect(auditMethodName(53)).toBe('Reserved53'); + expect(auditMethodName(66)).toBe('Reserved66'); + expect(auditMethodName(67)).toBe('GetCapabilities'); + expect(auditMethodName(72)).toBe('Reserved72'); + expect(auditMethodName(73)).toBe('GetTeamSpeakDirectory'); + expect(auditMethodName(88)).toBe('SendTeamSpeakServerMessage'); + expect(auditMethodName(89)).toBe('GetUpdateStatus'); + expect(auditMethodName(95)).toBe('ConfirmUnsignedUpdate'); + }); +}); diff --git a/EchoionWeb/frontend/src/lib/auditMethods.ts b/EchoionWeb/frontend/src/lib/auditMethods.ts index a85c36b..3fb3813 100644 --- a/EchoionWeb/frontend/src/lib/auditMethods.ts +++ b/EchoionWeb/frontend/src/lib/auditMethods.ts @@ -54,10 +54,53 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [ 'ToggleAutoplay', 'GetUserPrefs', 'SetUserPrefs', - 'GetCustomEmojis', - 'AddCustomEmoji', // 50 - 'RemoveCustomEmoji', + 'Reserved49', + 'Reserved50', + 'Reserved51', 'GetLyrics', + 'Reserved53', + 'Reserved54', + 'Reserved55', + 'Reserved56', + 'Reserved57', + 'Reserved58', + 'Reserved59', + 'Reserved60', + 'Reserved61', + 'Reserved62', + 'Reserved63', + 'Reserved64', + 'Reserved65', + 'Reserved66', + 'GetCapabilities', + 'GetPluginExtensions', + 'PluginCall', + 'Reserved70', + 'Reserved71', + 'Reserved72', + 'GetTeamSpeakDirectory', + 'MoveTeamSpeakClient', + 'KickTeamSpeakClient', + 'BanTeamSpeakClient', + 'GetTeamSpeakBans', + 'UnbanTeamSpeakClient', + 'CreateTeamSpeakChannel', + 'EditTeamSpeakChannel', + 'ReorderTeamSpeakChannel', + 'DeleteTeamSpeakChannel', + 'GetTeamSpeakServerGroups', + 'AddTeamSpeakServerGroupMember', + 'RemoveTeamSpeakServerGroupMember', + 'SendTeamSpeakPrivateMessage', + 'SendTeamSpeakChannelMessage', + 'SendTeamSpeakServerMessage', + 'GetUpdateStatus', // 89 + 'GetUpdateConfig', + 'SetUpdateConfig', + 'CheckForUpdates', + 'ApplyUpdate', + 'RollbackUpdate', + 'ConfirmUnsignedUpdate', // 95 ]; export function auditMethodName(method: number): string { diff --git a/EchoionWeb/frontend/src/lib/embedProtocols.test.ts b/EchoionWeb/frontend/src/lib/embedProtocols.test.ts deleted file mode 100644 index a70c3f4..0000000 --- a/EchoionWeb/frontend/src/lib/embedProtocols.test.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { EMBED_PROTOCOLS, prepareEmbedUrl } from './embedProtocols'; - -const byName = (name: string) => EMBED_PROTOCOLS.find((p) => p.name === name)!; -const kodik = byName('kodik'); -const playerjs = byName('playerjs'); -const alloha = byName('alloha'); -const vimeo = byName('vimeo'); -const playerjsSpec = byName('player.js'); -const rutube = byName('rutube'); -const dailymotion = byName('dailymotion'); -const vk = byName('vk'); - -describe('kodik parse', () => { - it('parses JSON-string time updates', () => { - expect( - kodik.parse( - JSON.stringify({ key: 'kodik_player_time_update', value: 42.5 }) - ) - ).toEqual({ kind: 'time', seconds: 42.5 }); - }); - - it('parses duration and play/pause/ended state', () => { - expect( - kodik.parse({ key: 'kodik_player_duration_update', value: 1440 }) - ).toEqual({ kind: 'duration', seconds: 1440 }); - expect(kodik.parse({ key: 'kodik_player_play' })).toEqual({ kind: 'play' }); - expect(kodik.parse({ key: 'kodik_player_pause' })).toEqual({ - kind: 'pause', - }); - expect(kodik.parse({ key: 'kodik_player_video_ended' })).toEqual({ - kind: 'ended', - }); - }); - - it('rejects everything else', () => { - expect(kodik.parse('garbage')).toBeNull(); - expect(kodik.parse('{"broken json')).toBeNull(); - expect(kodik.parse({ event: 'time', answer: 3 })).toBeNull(); - expect(kodik.parse(null)).toBeNull(); - expect(kodik.parse(42)).toBeNull(); - }); - - it('is hostname-pinned and seeks by reloading with start_from', () => { - expect(kodik.matchUrl!('https://kodikplayer.com/seria/1/hash/720p')).toBe( - true - ); - expect(kodik.matchUrl!('https://kodik.info/video/1/hash/720p')).toBe(true); - expect(kodik.matchUrl!('https://youtube.com/x')).toBe(false); - // start_from is set (overwritten) while signed params are preserved. - const seeked = kodik.reloadSeek!( - 'https://kodikplayer.com/seria/1/hash/720p?d_sign=abc&start_from=5', - 42.9 - ); - expect(seeked).toContain('start_from=42'); - expect(seeked).toContain('d_sign=abc'); - expect(seeked).not.toContain('start_from=5'); - }); -}); - -describe('playerjs.com parse', () => { - it('parses object and JSON-string events', () => { - expect(playerjs.parse({ event: 'time', answer: 12 })).toEqual({ - kind: 'time', - seconds: 12, - }); - expect( - playerjs.parse(JSON.stringify({ event: 'duration', answer: 600 })) - ).toEqual({ kind: 'duration', seconds: 600 }); - expect(playerjs.parse({ event: 'end' })).toEqual({ kind: 'ended' }); - }); - - it('does not lock on player.js-spec or unknown shapes', () => { - expect(playerjs.parse({ context: 'player.js', event: 'play' })).toBeNull(); - expect(playerjs.parse({ event: 'infoDelivery' })).toBeNull(); - expect(playerjs.parse({ key: 'kodik_player_play' })).toBeNull(); - }); - - it('normalizes quality, voiceover and subtitle capabilities', () => { - expect( - playerjs.parse({ - event: 'qualities', - answer: [{ id: '720', name: '720p' }, '1080p'], - }) - ).toMatchObject({ - kind: 'extraList', - control: { id: 'quality', scope: 'local' }, - }); - expect( - playerjs.parse({ - event: 'audiotracks', - answer: { ru: 'Russian', en: 'English' }, - }) - ).toMatchObject({ - kind: 'extraList', - control: { id: 'audiotrack', scope: 'synced' }, - }); - expect(playerjs.parse({ event: 'subtitle', answer: 1 })).toEqual({ - kind: 'extraCurrent', - id: 'subtitle', - value: '1', - }); - }); -}); - -describe('alloha detection', () => { - it('pins known Alloha player hosts', () => { - expect(alloha.matchUrl!('https://alloha.tv/embed/123')).toBe(true); - expect(alloha.matchUrl!('https://cdn.allarknow.online/player')).toBe(true); - expect(alloha.matchUrl!('https://example.com/player')).toBe(false); - }); -}); - -describe('vimeo parse', () => { - it('parses timeupdate with bundled duration and the getDuration reply', () => { - expect( - vimeo.parse({ event: 'timeupdate', data: { seconds: 10, duration: 200 } }) - ).toEqual({ kind: 'time', seconds: 10, duration: 200 }); - expect(vimeo.parse({ method: 'getDuration', value: 200 })).toEqual({ - kind: 'duration', - seconds: 200, - }); - expect(vimeo.parse({ event: 'play' })).toEqual({ kind: 'play' }); - }); - - it('does not lock on a playerjs.com message (has `answer`) or garbage', () => { - expect(vimeo.parse({ event: 'play', answer: 1 })).toBeNull(); - expect(vimeo.parse('garbage')).toBeNull(); - expect(vimeo.parse({ event: 'infoDelivery' })).toBeNull(); - }); - - it('matchUrl selects vimeo hosts only', () => { - expect(vimeo.matchUrl!('https://player.vimeo.com/video/123')).toBe(true); - expect(vimeo.matchUrl!('https://vimeo.com/123')).toBe(true); - expect(vimeo.matchUrl!('https://youtube.com/watch?v=x')).toBe(false); - }); - - it('prepareUrl hides native chrome', () => { - const p = vimeo.prepareUrl!('https://player.vimeo.com/video/123'); - expect(p).toContain('controls=0'); - expect(p).toContain('title=0'); - }); -}); - -describe('player.js (embedly spec) parse', () => { - it('parses context-tagged events', () => { - expect( - playerjsSpec.parse({ - context: 'player.js', - event: 'timeupdate', - value: { seconds: 5, duration: 100 }, - }) - ).toEqual({ kind: 'time', seconds: 5, duration: 100 }); - expect( - playerjsSpec.parse({ context: 'player.js', event: 'pause' }) - ).toEqual({ kind: 'pause' }); - expect(playerjsSpec.parse({ context: 'player.js', event: 'ready' })).toEqual( - { kind: 'hello' } - ); - }); - - it('rejects messages without the player.js context', () => { - expect(playerjsSpec.parse({ event: 'play' })).toBeNull(); - expect(playerjsSpec.parse('garbage')).toBeNull(); - }); -}); - -describe('rutube parse + matchUrl', () => { - it('parses player:* events', () => { - expect( - rutube.parse( - JSON.stringify({ type: 'player:currentTime', data: { time: 30 } }) - ) - ).toEqual({ kind: 'time', seconds: 30 }); - expect( - rutube.parse({ type: 'player:changeState', data: { state: 'playing' } }) - ).toEqual({ kind: 'play' }); - expect( - rutube.parse({ type: 'player:durationChange', data: { duration: 90 } }) - ).toEqual({ kind: 'duration', seconds: 90 }); - }); - - it('ignores foreign messages', () => { - expect(rutube.parse({ event: 'play', answer: 1 })).toBeNull(); - expect(rutube.parse({ key: 'kodik_player_play' })).toBeNull(); - expect(rutube.matchUrl!('https://rutube.ru/play/embed/123')).toBe(true); - expect(rutube.matchUrl!('https://vimeo.com/1')).toBe(false); - }); -}); - -describe('dailymotion parse + prepareUrl', () => { - it('parses classic querystring events', () => { - expect(dailymotion.parse('event=timeupdate&time=12&duration=240')).toEqual( - { kind: 'time', seconds: 12, duration: 240 } - ); - expect(dailymotion.parse('event=pause')).toEqual({ kind: 'pause' }); - expect(dailymotion.parse('event=video_end')).toEqual({ kind: 'ended' }); - expect(dailymotion.parse({ event: 'play' })).toBeNull(); - }); - - it('matchUrl + prepareUrl inject api=postMessage and preserve params', () => { - expect(dailymotion.matchUrl!('https://www.dailymotion.com/embed/video/x')) - .toBe(true); - expect(dailymotion.matchUrl!('https://dai.ly/x')).toBe(true); - const prepared = dailymotion.prepareUrl!( - 'https://www.dailymotion.com/embed/video/x?foo=1' - ); - expect(prepared).toContain('api=postMessage'); - expect(prepared).toContain('controls=0'); - expect(prepared).toContain('foo=1'); - // idempotent - expect(dailymotion.prepareUrl!(prepared)).toBe(prepared); - }); -}); - -describe('vk parse + prepareUrl', () => { - it('parses player_api events', () => { - expect( - vk.parse({ type: 'player_api', event: 'timeupdate', time: 8, duration: 60 }) - ).toEqual({ kind: 'time', seconds: 8, duration: 60 }); - expect(vk.parse({ type: 'player_api', event: 'started' })).toEqual({ - kind: 'play', - }); - expect(vk.parse({ type: 'player_api', event: 'paused' })).toEqual({ - kind: 'pause', - }); - }); - - it('ignores foreign messages and injects js_api=1', () => { - expect(vk.parse({ event: 'play', answer: 1 })).toBeNull(); - expect(vk.matchUrl!('https://vk.com/video_ext.php?oid=1')).toBe(true); - expect(vk.matchUrl!('https://vkvideo.ru/video_ext.php?oid=1')).toBe(true); - expect(vk.prepareUrl!('https://vk.com/video_ext.php?oid=1')).toContain( - 'js_api=1' - ); - }); -}); - -describe('registry order + prepareEmbedUrl', () => { - it('generic (content-detected) set is player.js then playerjs', () => { - expect( - EMBED_PROTOCOLS.filter((p) => !p.matchUrl).map((p) => p.name) - ).toEqual(['player.js', 'playerjs']); - }); - - it('prepareEmbedUrl applies hostname-matched params, leaves others alone', () => { - expect( - prepareEmbedUrl('https://www.dailymotion.com/embed/video/x') - ).toContain('api=postMessage'); - expect(prepareEmbedUrl('https://kodik.info/seria/1/hash/720p')).toBe( - 'https://kodik.info/seria/1/hash/720p' - ); - }); -}); diff --git a/EchoionWeb/frontend/src/lib/embedProtocols.ts b/EchoionWeb/frontend/src/lib/embedProtocols.ts deleted file mode 100644 index f0f4899..0000000 --- a/EchoionWeb/frontend/src/lib/embedProtocols.ts +++ /dev/null @@ -1,972 +0,0 @@ -// Adapters for postMessage-controllable embed players in the Watch view. -// -// A generic iframe can only be driven if the player inside exposes a -// postMessage API — everything else stays view-only by browser design. -// Protocols supported (each is one self-contained entry in EMBED_PROTOCOLS): -// - kodik: JSON *strings* like {key:'kodik_player_time_update', value:sec}; -// commands {key:'kodik_player_api', value:{method}}. -// - vimeo: {method:'play'|...} strings; events {event:'timeupdate', -// data:{seconds,duration}}. Hostname-selected (player.vimeo.com). -// - rutube / dailymotion / vk: hostname-selected; some need opt-in URL -// params (prepareUrl) and their command/event shapes are community- -// documented — flagged VERIFY, one-line fixes if a live embed differs. -// - player.js (embedly spec): {context:'player.js', ...} — Wistia & co. -// - playerjs (playerjs.com, many CIS hosters): {api:'play'|...} commands, -// {event, answer} events. -// Shapes marked VERIFY are community-documented, not official; dev builds -// console.debug every unrecognized frame message to reverse-engineer them. -// -// Detection: for a hostname-matched player only that protocol is probed; -// otherwise the generic set is probed until one `parse` recognizes a message -// and locks the adapter. On timeout the embed is uncontrollable and the -// caller keeps today's host-driven view-only behavior. - -export interface EmbedAdapter { - protocol: string; - // True for players (Kodik) driven by reloading the iframe rather than - // postMessage commands: the caller should avoid drift-reconcile churn and - // not expect pause to work. - reloadBased: boolean; - play(): void; - pause(): void; - seekMs(ms: number): void; - setVolume(v01: number): void; // 0..1 - positionMs(): number; - durationMs(): number; - paused(): boolean; - extras(): PlayerExtraControl[]; - setExtra(id: string, value: string): void; - destroy(): void; -} - -export interface ExtraControlOption { - value: string; - label: string; -} - -export interface PlayerExtraControl { - id: string; - label: string; - kind: 'select' | 'button'; - options: ExtraControlOption[]; - current: string | null; - scope: 'local' | 'synced'; -} - -// Fired only for events NOT caused by our own commands (see suppression -// below) — i.e. gestures made inside the embed UI, which the host must relay -// to the room. -export interface EmbedCallbacks { - onPlay(positionMs: number): void; - onPause(positionMs: number): void; - onSeek(positionMs: number): void; - onDurationChange(durationMs: number): void; - onEnded(): void; - onExtraControls(controls: PlayerExtraControl[]): void; -} - -export type EmbedEvent = - // `duration` piggybacks on time events for players (Vimeo, player.js, DM, - // VK) that bundle it into their timeupdate payload. - | { kind: 'time'; seconds: number; duration?: number } - | { kind: 'duration'; seconds: number } - | { kind: 'play' } - | { kind: 'pause' } - | { kind: 'ended' } - | { kind: 'extraList'; control: PlayerExtraControl } - | { kind: 'extraCurrent'; id: string; value: string } - // Recognized the protocol but the event carries no state we track; enough - // to lock detection. - | { kind: 'hello' }; - -export interface ProtocolDef { - name: string; - // Hostname-based selection: when a URL matches, only this protocol is - // probed (skips content-based detection). Left undefined for generic - // protocols detected purely by the messages they emit (kodik, player.js). - matchUrl?(url: string): boolean; - // Inject opt-in query params the player needs before the iframe loads - // (e.g. Dailymotion `?api=postMessage`, VK `?js_api=1`). - prepareUrl?(url: string): string; - // Some players (Kodik) expose no postMessage command API — the only way to - // seek is to reload the iframe at a start offset. When present, the adapter - // seeks by setting frame.src to this URL instead of posting a command. - reloadSeek?(currentSrc: string, seconds: number): string; - probe(win: Window): void; - parse(data: unknown): EmbedEvent | null; - play(win: Window): void; - pause(win: Window): void; - seek(win: Window, seconds: number): void; - volume(win: Window, v01: number): void; - probeExtras?(win: Window): void; - setExtra?(win: Window, id: string, value: string): void; - staticExtras?(url: string): PlayerExtraControl[]; -} - -// Embeds are served from many mirror domains (esp. Kodik), so the target -// origin can't be pinned; we never trust incoming data beyond parsing known -// shapes into numbers. -function post(win: Window, msg: unknown) { - try { - win.postMessage(msg, '*'); - } catch { - /* frame navigating/gone */ - } -} - -const asNumber = (v: unknown): number => - typeof v === 'number' ? v : Number(v); - -// Embed URLs are absolute, so no base is needed; guard `location` so the -// helpers also work under the node test runner. -const baseHref = (): string | undefined => - typeof location !== 'undefined' ? location.href : undefined; - -function hostOf(url: string): string { - try { - return new URL(url, baseHref()).hostname.toLowerCase(); - } catch { - return ''; - } -} - -function isHostOrSubdomain(host: string, domain: string): boolean { - return host === domain || host.endsWith(`.${domain}`); -} - -function withParams(url: string, params: Record): string { - try { - const u = new URL(url, baseHref()); - for (const [k, v] of Object.entries(params)) { - if (!u.searchParams.has(k)) u.searchParams.set(k, v); - } - return u.toString(); - } catch { - return url; - } -} - -// Overwrite a single query param (preserves the rest, incl. Kodik's signed -// d_sign/ref_sign params). -function setParam(url: string, key: string, value: string): string { - try { - const u = new URL(url, baseHref()); - u.searchParams.set(key, value); - return u.toString(); - } catch { - return url; - } -} - -// Normalize an object-or-JSON-string payload into a plain object, or null. -function asObj(data: unknown): Record | null { - let obj: unknown = data; - if (typeof data === 'string') { - const s = data.trim(); - if (!s.startsWith('{') && !s.startsWith('[')) return null; - try { - obj = JSON.parse(s); - } catch { - return null; - } - } - return obj && typeof obj === 'object' - ? (obj as Record) - : null; -} - -function toOptions(value: unknown): ExtraControlOption[] { - const entries = Array.isArray(value) - ? value.map((item, index) => [String(index), item] as const) - : value && typeof value === 'object' - ? Object.entries(value as Record) - : []; - return entries.flatMap(([fallback, item]) => { - if (item && typeof item === 'object') { - const option = item as Record; - const raw = option.value ?? option.id ?? option.index ?? fallback; - const label = option.label ?? option.name ?? option.title ?? raw; - return [{ value: String(raw), label: String(label) }]; - } - return item == null - ? [] - : [{ value: fallback, label: String(item) }]; - }); -} - -function extraControl( - id: string, - label: string, - scope: PlayerExtraControl['scope'], - options: ExtraControlOption[], - current: string | null = null -): PlayerExtraControl { - return { id, label, scope, options, current, kind: 'select' }; -} - -const kodik: ProtocolDef = { - name: 'kodik', - // Kodik (kodikplayer.com and its mirrors). Hostname-pinned so it always - // locks as `kodik` and never falls back to view-only. - matchUrl: (url) => { - const host = hostOf(url); - return ['kodik.info', 'kodik.cc', 'kodik.biz', 'kodik.online', 'kodikplayer.com'] - .some((domain) => isHostOrSubdomain(host, domain)); - }, - // Kodik has NO postMessage command API — the only way to seek is to reload - // the iframe at a start offset (preserving its signed params). start_from - // auto-resumes playback from that second. - reloadSeek: (src, seconds) => - setParam(src, 'start_from', String(Math.max(0, Math.floor(seconds)))), - probe(win) { - // Community-documented; harmless if ignored by the player. - post(win, { key: 'kodik_player_api', value: { method: 'get_duration' } }); - post(win, { key: 'kodik_player_api', value: { method: 'get_time' } }); - }, - parse(data) { - let obj: unknown = data; - if (typeof data === 'string') { - if (!data.includes('kodik_player')) return null; - try { - obj = JSON.parse(data); - } catch { - return null; - } - } - const m = obj as { key?: unknown; value?: unknown } | null; - if (!m || typeof m.key !== 'string' || !m.key.startsWith('kodik_player')) { - return null; - } - const n = asNumber(m.value); - switch (m.key) { - case 'kodik_player_time_update': - case 'kodik_player_current_time': - return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' }; - case 'kodik_player_duration_update': - case 'kodik_player_duration': - return isFinite(n) && n > 0 - ? { kind: 'duration', seconds: n } - : { kind: 'hello' }; - case 'kodik_player_play': - return { kind: 'play' }; - case 'kodik_player_pause': - return { kind: 'pause' }; - case 'kodik_player_video_ended': - return { kind: 'ended' }; - default: - // Unmapped kodik_player_* event — still unambiguously Kodik. - return { kind: 'hello' }; - } - }, - play: (win) => post(win, { key: 'kodik_player_api', value: { method: 'play' } }), - pause: (win) => post(win, { key: 'kodik_player_api', value: { method: 'pause' } }), - seek: (win, seconds) => - post(win, { key: 'kodik_player_api', value: { method: 'seek', seconds } }), - volume: (win, v01) => - post(win, { - key: 'kodik_player_api', - value: { method: 'change_volume', volume: v01 }, - }), -}; - -const playerjs: ProtocolDef = { - name: 'playerjs', - probe(win) { - post(win, { api: 'duration' }); - post(win, { api: 'time' }); - }, - probeExtras(win) { - for (const api of ['qualities', 'audiotracks', 'subtitles']) { - post(win, { api }); - } - }, - staticExtras() { - return [ - extraControl( - 'speed', - 'Speed', - 'synced', - [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => ({ - value: String(speed), - label: `${speed}×`, - })), - '1' - ), - ]; - }, - parse(data) { - let obj: unknown = data; - if (typeof data === 'string') { - if (!data.startsWith('{')) return null; - try { - obj = JSON.parse(data); - } catch { - return null; - } - } - const m = obj as - | { event?: unknown; answer?: unknown; context?: unknown } - | null; - if (!m || typeof m.event !== 'string') return null; - // A {context:'player.js'} message belongs to the embedly spec adapter, - // not this one. - if (m.context === 'player.js') return null; - const n = asNumber(m.answer); - // Only lock on events Playerjs actually emits — a bare {event:...} - // could belong to some other player's protocol. - switch (m.event) { - case 'qualities': - return { - kind: 'extraList', - control: extraControl( - 'quality', - 'Quality', - 'local', - toOptions(m.answer) - ), - }; - case 'audiotracks': - return { - kind: 'extraList', - control: extraControl( - 'audiotrack', - 'Voiceover', - 'synced', - toOptions(m.answer) - ), - }; - case 'subtitles': - return { - kind: 'extraList', - control: extraControl( - 'subtitle', - 'Subtitles', - 'local', - [ - { value: '-1', label: 'Off' }, - ...toOptions(m.answer), - ] - ), - }; - case 'episodes': - return { - kind: 'extraList', - control: extraControl( - 'episode', - 'Episode', - 'synced', - toOptions(m.answer) - ), - }; - case 'quality': - case 'audiotrack': - case 'subtitle': - case 'speed': - case 'episode': - return { - kind: 'extraCurrent', - id: m.event, - value: String(m.answer ?? ''), - }; - case 'time': - case 'updatetime': - return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' }; - case 'duration': - return isFinite(n) && n > 0 - ? { kind: 'duration', seconds: n } - : { kind: 'hello' }; - case 'play': - return { kind: 'play' }; - case 'pause': - return { kind: 'pause' }; - case 'end': - case 'ended': - return { kind: 'ended' }; - case 'init': - case 'inited': - case 'ready': - case 'volume': - return { kind: 'hello' }; - default: - return null; - } - }, - play: (win) => post(win, { api: 'play' }), - pause: (win) => post(win, { api: 'pause' }), - seek: (win, seconds) => post(win, { api: 'seek', set: seconds }), - volume: (win, v01) => post(win, { api: 'volume', set: v01 }), - setExtra: (win, id, value) => { - if (!['quality', 'audiotrack', 'subtitle', 'speed', 'episode', 'next', 'prev'].includes(id)) { - return; - } - post(win, { api: id, set: value }); - }, -}; - -const alloha: ProtocolDef = { - ...playerjs, - name: 'alloha', - matchUrl: (url) => - ['alloha.tv', 'alloha.video', 'alloha.online', 'allarknow.online'].some( - (domain) => isHostOrSubdomain(hostOf(url), domain) - ), -}; - -// Vimeo (vimeo/player.js): well documented. Selected by hostname; disambiguated -// from playerjs.com by carrying `data`, not `answer`. -const vimeo: ProtocolDef = { - name: 'vimeo', - matchUrl: (url) => /(^|\.)vimeo\.com$/.test(hostOf(url)), - // Our overlay bar is the only control surface, so hide Vimeo's native chrome. - prepareUrl: (url) => - withParams(url, { - controls: '0', - title: '0', - byline: '0', - portrait: '0', - }), - probe(win) { - for (const ev of ['timeupdate', 'play', 'pause', 'ended']) { - post(win, JSON.stringify({ method: 'addEventListener', value: ev })); - } - post(win, JSON.stringify({ method: 'getDuration' })); - }, - probeExtras(win) { - post(win, JSON.stringify({ method: 'getQualities' })); - }, - parse(data) { - const m = asObj(data); - if (!m) return null; - if (m.method === 'getDuration') { - const n = asNumber(m.value); - return isFinite(n) && n > 0 - ? { kind: 'duration', seconds: n } - : { kind: 'hello' }; - } - if (m.method === 'getQualities') { - return { - kind: 'extraList', - control: extraControl( - 'quality', - 'Quality', - 'local', - toOptions(m.value) - ), - }; - } - if (typeof m.event !== 'string') return null; - if ('answer' in m) return null; // that's a playerjs.com message - const d = (m.data ?? {}) as { seconds?: unknown; duration?: unknown }; - switch (m.event) { - case 'timeupdate': { - const sec = asNumber(d.seconds); - const dur = asNumber(d.duration); - return isFinite(sec) - ? { - kind: 'time', - seconds: sec, - duration: isFinite(dur) && dur > 0 ? dur : undefined, - } - : { kind: 'hello' }; - } - case 'play': - return { kind: 'play' }; - case 'pause': - return { kind: 'pause' }; - case 'ended': - case 'finish': - return { kind: 'ended' }; - case 'ready': - case 'loaded': - return { kind: 'hello' }; - default: - return null; // bare {event} without vimeo markers → not ours - } - }, - play: (w) => post(w, JSON.stringify({ method: 'play' })), - pause: (w) => post(w, JSON.stringify({ method: 'pause' })), - seek: (w, s) => - post(w, JSON.stringify({ method: 'setCurrentTime', value: s })), - volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', value: v })), - setExtra: (w, id, value) => { - if (id === 'quality') { - post(w, JSON.stringify({ method: 'setQuality', value })); - } - }, -}; - -// embedly player.js SPEC (github.com/embedly/player.js): the `context` field -// makes every message unambiguous. Generic (no matchUrl) — covers Wistia etc. -const PJS = { context: 'player.js', version: '0.0.11' } as const; -const playerjsSpec: ProtocolDef = { - name: 'player.js', - probe(win) { - for (const ev of ['timeupdate', 'play', 'pause', 'ended']) { - post(win, { - ...PJS, - method: 'addEventListener', - listener: `ec_${ev}`, - value: ev, - }); - } - }, - parse(data) { - const m = asObj(data); - if (!m || m.context !== 'player.js' || typeof m.event !== 'string') { - return null; - } - const v = (m.value ?? {}) as { seconds?: unknown; duration?: unknown }; - switch (m.event) { - case 'timeupdate': { - const sec = asNumber(v.seconds); - const dur = asNumber(v.duration); - return isFinite(sec) - ? { - kind: 'time', - seconds: sec, - duration: isFinite(dur) && dur > 0 ? dur : undefined, - } - : { kind: 'hello' }; - } - case 'play': - return { kind: 'play' }; - case 'pause': - return { kind: 'pause' }; - case 'ended': - return { kind: 'ended' }; - default: - return { kind: 'hello' }; // any context:'player.js' event is ours - } - }, - play: (w) => post(w, { ...PJS, method: 'play' }), - pause: (w) => post(w, { ...PJS, method: 'pause' }), - seek: (w, s) => post(w, { ...PJS, method: 'setCurrentTime', value: s }), - volume: (w, v) => post(w, { ...PJS, method: 'setVolume', value: v }), -}; - -// Rutube (RutubePlayerJSAPI). VERIFY command/subscribe shapes on a live embed. -const rutube: ProtocolDef = { - name: 'rutube', - matchUrl: (url) => /(^|\.)rutube\.ru$/.test(hostOf(url)), - probe(win) { - // Rutube emits events only after an explicit subscribe. VERIFY payload. - post(win, JSON.stringify({ type: 'player:subscribe', data: {} })); - }, - parse(data) { - const m = asObj(data); - if (!m || typeof m.type !== 'string' || !m.type.startsWith('player:')) { - return null; - } - const d = (m.data ?? {}) as { - time?: unknown; - duration?: unknown; - state?: unknown; - }; - switch (m.type) { - case 'player:currentTime': { - const n = asNumber(d.time); - return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' }; - } - case 'player:durationChange': { - const n = asNumber(d.duration); - return isFinite(n) && n > 0 - ? { kind: 'duration', seconds: n } - : { kind: 'hello' }; - } - case 'player:changeState': { - const st = String(d.state); - if (st === 'playing') return { kind: 'play' }; - if (st === 'paused' || st === 'stopped') return { kind: 'pause' }; - if (st === 'ended') return { kind: 'ended' }; - return { kind: 'hello' }; - } - default: - return { kind: 'hello' }; // player:* is unambiguously Rutube - } - }, - play: (w) => post(w, JSON.stringify({ type: 'player:play', data: {} })), - pause: (w) => post(w, JSON.stringify({ type: 'player:pause', data: {} })), - seek: (w, s) => - post(w, JSON.stringify({ type: 'player:setCurrentTime', data: { time: s } })), - volume: (w, v) => - post(w, JSON.stringify({ type: 'player:setVolume', data: { volume: v } })), -}; - -// Dailymotion classic embed (?api=postMessage → querystring events). VERIFY; -// the newer geo.dailymotion.com SDK uses JSON — add a branch here if needed. -const dailymotion: ProtocolDef = { - name: 'dailymotion', - matchUrl: (url) => /(^|\.)(dailymotion\.com|dai\.ly)$/.test(hostOf(url)), - // api=postMessage enables control; controls=0 + ui-* hide the native chrome - // (our overlay bar drives playback instead). - prepareUrl: (url) => - withParams(url, { - api: 'postMessage', - controls: '0', - 'ui-start-screen-info': 'false', - 'ui-logo': 'false', - }), - probe() { - /* classic embed auto-emits once api=postMessage is set */ - }, - parse(data) { - if (typeof data !== 'string' || !data.includes('event=')) return null; - const p = new URLSearchParams(data); - const ev = p.get('event'); - if (!ev) return null; - const sec = Number(p.get('time')); - const dur = Number(p.get('duration')); - switch (ev) { - case 'timeupdate': - case 'progress': - return isFinite(sec) - ? { - kind: 'time', - seconds: sec, - duration: isFinite(dur) && dur > 0 ? dur : undefined, - } - : { kind: 'hello' }; - case 'durationchange': - return isFinite(dur) && dur > 0 - ? { kind: 'duration', seconds: dur } - : { kind: 'hello' }; - case 'play': - case 'playing': - return { kind: 'play' }; - case 'pause': - return { kind: 'pause' }; - case 'video_end': - case 'ended': - return { kind: 'ended' }; - default: - return { kind: 'hello' }; - } - }, - play: (w) => post(w, JSON.stringify({ command: 'play', parameters: [] })), - pause: (w) => post(w, JSON.stringify({ command: 'pause', parameters: [] })), - seek: (w, s) => post(w, JSON.stringify({ command: 'seek', parameters: [s] })), - volume: (w, v) => - post(w, JSON.stringify({ command: 'setVolume', parameters: [v] })), -}; - -// VK Video (?js_api=1 → {type:'player_api', event}). VERIFY command shapes. -const vk: ProtocolDef = { - name: 'vk', - matchUrl: (url) => /(^|\.)(vk\.com|vkvideo\.ru|vk\.ru)$/.test(hostOf(url)), - prepareUrl: (url) => withParams(url, { js_api: '1' }), - probe(win) { - post(win, JSON.stringify({ method: 'addEventListener', event: '*' })); - }, - parse(data) { - const m = asObj(data); - if (!m || m.type !== 'player_api' || typeof m.event !== 'string') { - return null; - } - const sec = asNumber(m.time ?? m.position); - const dur = asNumber(m.duration); - switch (m.event) { - case 'timeupdate': - return isFinite(sec) - ? { - kind: 'time', - seconds: sec, - duration: isFinite(dur) && dur > 0 ? dur : undefined, - } - : { kind: 'hello' }; - case 'started': - case 'resumed': - return { kind: 'play' }; - case 'paused': - return { kind: 'pause' }; - case 'ended': - return { kind: 'ended' }; - default: - return { kind: 'hello' }; // type:'player_api' is unambiguously VK - } - }, - play: (w) => post(w, JSON.stringify({ method: 'play' })), - pause: (w) => post(w, JSON.stringify({ method: 'pause' })), - seek: (w, s) => post(w, JSON.stringify({ method: 'seek', time: s })), - volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', volume: v })), -}; - -// Hostname-selected protocols first (they're picked by URL, never by content); -// then the generic set probed by the messages they emit — kodik first (its -// keys are unambiguous), the embedly spec before the looser playerjs.com. -// Exported for the parse unit tests. -export const EMBED_PROTOCOLS: ProtocolDef[] = [ - kodik, - alloha, - vimeo, - rutube, - dailymotion, - vk, - playerjsSpec, - playerjs, -]; - -// Inject any opt-in params a hostname-matched player needs, before iframe.src. -export function prepareEmbedUrl(url: string): string { - const p = EMBED_PROTOCOLS.find((x) => x.matchUrl?.(url)); - // Signed players such as Kodik depend on their own origin for scripts, - // AJAX, cookies and anti-abuse checks. Keep them on the provider origin; - // Echoion controls them only through their postMessage surface. - return p?.prepareUrl ? p.prepareUrl(url) : url; -} - -const PROBE_INTERVAL_MS = 750; -// Commands are echoed back as events by the player; ignore relay callbacks -// for this long after each command we send. -const SUPPRESS_MS = 800; -// A time event this far off the extrapolated position counts as a user seek. -const SEEK_JUMP_SEC = 2.5; -// Minimum gap between reload-based (Kodik) iframe reloads. -const RELOAD_DEBOUNCE_MS = 4000; - -export function detectEmbedAdapter( - frame: HTMLIFrameElement, - cb: EmbedCallbacks, - timeoutMs = 5000 -): Promise { - return new Promise((resolve) => { - let locked: ProtocolDef | null = null; - - // A hostname-matched player is probed alone; otherwise probe the - // generic (content-detected) set. frame.src is the prepared URL. - const matched = - EMBED_PROTOCOLS.find((p) => p.matchUrl?.(frame.src)) ?? null; - const probeSet = matched - ? [matched] - : EMBED_PROTOCOLS.filter((p) => !p.matchUrl); - - // Normalized player state. Embeds push time updates rather than expose - // getters, so position is the last event extrapolated by wall clock. - let lastTimeSec = 0; - let lastTimeAt = performance.now(); - let durationSec = 0; - let playing = false; - let suppressUntil = 0; - const extraControls = new Map(); - - const positionMs = () => - Math.floor( - (lastTimeSec + - (playing ? (performance.now() - lastTimeAt) / 1000 : 0)) * - 1000 - ); - const suppressed = () => performance.now() < suppressUntil; - - const applyEvent = (ev: EmbedEvent) => { - switch (ev.kind) { - case 'time': { - const jumped = - Math.abs(ev.seconds - positionMs() / 1000) > - SEEK_JUMP_SEC; - // Advancing time implies playing even when the protocol - // never sends an explicit play event. - const advancing = ev.seconds > lastTimeSec + 0.05; - lastTimeSec = ev.seconds; - lastTimeAt = performance.now(); - // Some protocols bundle duration into the time event. - if ( - ev.duration != null && - Math.abs(ev.duration - durationSec) > 0.5 - ) { - durationSec = ev.duration; - cb.onDurationChange(Math.floor(ev.duration * 1000)); - } - if (jumped && !suppressed()) { - cb.onSeek(Math.floor(ev.seconds * 1000)); - } - if (!playing && advancing) { - playing = true; - if (!suppressed()) cb.onPlay(positionMs()); - } - break; - } - case 'duration': - if (Math.abs(ev.seconds - durationSec) > 0.5) { - durationSec = ev.seconds; - cb.onDurationChange(Math.floor(ev.seconds * 1000)); - } - break; - case 'play': - if (!playing) { - playing = true; - lastTimeAt = performance.now(); - if (!suppressed()) cb.onPlay(positionMs()); - } - break; - case 'pause': - if (playing) { - lastTimeSec = positionMs() / 1000; - playing = false; - if (!suppressed()) cb.onPause(positionMs()); - } - break; - case 'ended': - playing = false; - cb.onEnded(); - break; - case 'extraList': - if (ev.control.options.length > 0) { - extraControls.set(ev.control.id, ev.control); - cb.onExtraControls([...extraControls.values()]); - } - break; - case 'extraCurrent': { - const control = extraControls.get(ev.id); - if (control && control.current !== ev.value) { - extraControls.set(ev.id, { ...control, current: ev.value }); - cb.onExtraControls([...extraControls.values()]); - } - break; - } - case 'hello': - break; - } - }; - - // contentWindow is read live on every use: it changes when the frame - // navigates, while ev.source comparison below stays valid because the - // browsing context object is stable for the life of the element. - const win = () => frame.contentWindow; - - const makeAdapter = (p: ProtocolDef): EmbedAdapter => { - for (const control of p.staticExtras?.(frame.src) ?? []) { - extraControls.set(control.id, control); - } - if (extraControls.size > 0) { - cb.onExtraControls([...extraControls.values()]); - } - const probeExtras = () => { - const current = win(); - if (current) p.probeExtras?.(current); - }; - probeExtras(); - const extraProbeTimers = [1500, 3000].map((delay) => - window.setTimeout(probeExtras, delay) - ); - // Reload-based (Kodik) seeking: replace frame.src at a start offset, - // debounced so drift-reconcile can't spam reloads (each reload - // re-buffers and may replay an ad). - let lastReloadAt = 0; - const reloadTo = (sec: number) => { - const now = performance.now(); - if (now - lastReloadAt < RELOAD_DEBOUNCE_MS) return; - lastReloadAt = now; - suppressUntil = now + SUPPRESS_MS; - lastTimeSec = Math.max(0, sec); - lastTimeAt = now; - playing = true; // start_from auto-resumes - frame.src = p.reloadSeek!(frame.src, sec); - }; - return { - protocol: p.name, - reloadBased: !!p.reloadSeek, - play() { - // Commands update state optimistically so positionMs()/paused() - // reflect intent immediately — otherwise the 3s sync heartbeat - // would fight the slow embed acknowledgement. - suppressUntil = performance.now() + SUPPRESS_MS; - playing = true; - lastTimeAt = performance.now(); - if (p.reloadSeek) { - // No play command — resume by reloading at the current spot. - reloadTo(lastTimeSec); - return; - } - const w = win(); - if (w) p.play(w); - }, - pause() { - suppressUntil = performance.now() + SUPPRESS_MS; - lastTimeSec = positionMs() / 1000; - playing = false; - // Reload-based players (Kodik) have no pause — best-effort no-op. - if (p.reloadSeek) return; - const w = win(); - if (w) p.pause(w); - }, - seekMs(ms: number) { - if (p.reloadSeek) { - reloadTo(ms / 1000); - return; - } - suppressUntil = performance.now() + SUPPRESS_MS; - lastTimeSec = ms / 1000; - lastTimeAt = performance.now(); - const w = win(); - if (w) p.seek(w, ms / 1000); - }, - setVolume(v01: number) { - const w = win(); - if (w) p.volume(w, Math.max(0, Math.min(1, v01))); - }, - extras: () => [...extraControls.values()], - setExtra(id, value) { - const control = extraControls.get(id); - if (!control || !p.setExtra) return; - suppressUntil = performance.now() + 1500; - extraControls.set(id, { ...control, current: value }); - cb.onExtraControls([...extraControls.values()]); - const current = win(); - if (current) p.setExtra(current, id, value); - }, - positionMs, - durationMs: () => Math.floor(durationSec * 1000), - paused: () => !playing, - destroy() { - window.removeEventListener('message', handler); - clearInterval(probeTimer); - clearTimeout(giveUp); - for (const timer of extraProbeTimers) clearTimeout(timer); - }, - }; - }; - - const handler = (ev: MessageEvent) => { - if (ev.source !== frame.contentWindow) return; - if (locked) { - const e = locked.parse(ev.data); - if (e) applyEvent(e); - else if (import.meta.env.DEV) { - console.debug('[embed] unrecognized message', ev.data); - } - return; - } - for (const p of probeSet) { - const e = p.parse(ev.data); - if (e) { - locked = p; - clearInterval(probeTimer); - clearTimeout(giveUp); - applyEvent(e); - resolve(makeAdapter(p)); - return; - } - } - if (import.meta.env.DEV) { - console.debug('[embed] unrecognized message', ev.data); - } - }; - window.addEventListener('message', handler); - - const sendProbes = () => { - const w = win(); - if (!w || locked) return; - for (const p of probeSet) p.probe(w); - }; - // The inner player may boot slowly; keep probing until lock or timeout. - const probeTimer = setInterval(sendProbes, PROBE_INTERVAL_MS); - frame.addEventListener('load', sendProbes); - sendProbes(); - - const giveUp = setTimeout(() => { - if (locked) return; - window.removeEventListener('message', handler); - clearInterval(probeTimer); - resolve(null); - }, timeoutMs); - }); -} diff --git a/EchoionWeb/frontend/src/lib/emoji.ts b/EchoionWeb/frontend/src/lib/emoji.ts deleted file mode 100644 index 16ba575..0000000 --- a/EchoionWeb/frontend/src/lib/emoji.ts +++ /dev/null @@ -1,96 +0,0 @@ -// Emoji support for watch chat and reactions (item 16). A curated Unicode set -// across categories (dependency-free — no multi-MB emoji-data bundle), plus -// admin-managed custom image emojis served at /emoji/ and referenced by -// :name: shortcodes. Recently-used emoji are remembered locally. - -import { Store } from './store'; -import { rpc } from './rpc'; - -export interface CustomEmoji { - name: string; - mime: string; -} - -export const emojiStore = new Store<{ - custom: CustomEmoji[]; - recent: string[]; // unicode chars or :shortcode: -}>({ - custom: [], - recent: JSON.parse(localStorage.getItem('echoion.recentEmoji') || '[]'), -}); - -export async function loadCustomEmojis() { - try { - const res = await rpc.call<{ emojis?: CustomEmoji[] }>( - 'GetCustomEmojis' - ); - emojiStore.set({ custom: (res && res.emojis) || [] }); - } catch { - /* not connected / not authed — leave empty */ - } -} - -export function rememberEmoji(token: string) { - const recent = [ - token, - ...emojiStore.get().recent.filter((r) => r !== token), - ].slice(0, 24); - emojiStore.set({ recent }); - localStorage.setItem('echoion.recentEmoji', JSON.stringify(recent)); -} - -// Curated categories of common Unicode emoji. -export const EMOJI_CATEGORIES: Array<{ label: string; emoji: string[] }> = [ - { - label: 'Smileys', - emoji: [ - '😀', '😁', '😂', '🤣', '😊', '😇', '🙂', '😉', '😍', '🥰', - '😘', '😜', '🤪', '😎', '🤩', '🥳', '😏', '😒', '😔', '😞', - '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', - '😱', '😨', '🤗', '🤔', '🤫', '🤥', '😴', '🤤', '😷', '🤒', - ], - }, - { - label: 'Gestures', - emoji: [ - '👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '👊', '✊', '🙌', - '👏', '🙏', '💪', '👀', '👋', '🤙', '💅', '🖖', '🫶', '🤝', - ], - }, - { - label: 'Hearts', - emoji: [ - '❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '💔', '❣️', - '💕', '💞', '💓', '💗', '💖', '💘', '💝', '✨', '💯', '🔥', - ], - }, - { - label: 'Fun', - emoji: [ - '🎉', '🎊', '🥂', '🍻', '🍕', '🍿', '🎮', '🎧', '🎵', '🎸', - '⚡', '🌟', '💥', '👑', '🚀', '🏆', '🎯', '💎', '🌈', '☀️', - ], - }, -]; - -// Render a chat message: plain text with :name: custom-emoji shortcodes -// replaced by tags. Returns React nodes (text is auto-escaped by React). -export function renderChatText(text: string): (string | EmojiToken)[] { - const out: (string | EmojiToken)[] = []; - const re = /:([a-z0-9_]{1,32}):/g; - const custom = new Set(emojiStore.get().custom.map((c) => c.name)); - let last = 0; - let m: RegExpExecArray | null; - while ((m = re.exec(text)) !== null) { - if (!custom.has(m[1])) continue; - if (m.index > last) out.push(text.slice(last, m.index)); - out.push({ emojiName: m[1] }); - last = m.index + m[0].length; - } - if (last < text.length) out.push(text.slice(last)); - return out; -} - -export interface EmojiToken { - emojiName: string; -} diff --git a/EchoionWeb/frontend/src/lib/router.test.ts b/EchoionWeb/frontend/src/lib/router.test.ts new file mode 100644 index 0000000..97178dc --- /dev/null +++ b/EchoionWeb/frontend/src/lib/router.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { viewFromHash } from './router'; + +describe('dashboard routing', () => { + it('uses dashboard as the default and redirects the retired now view', () => { + expect(viewFromHash('')).toBe('dashboard'); + expect(viewFromHash('#now')).toBe('dashboard'); + expect(viewFromHash('#dashboard')).toBe('dashboard'); + }); + + it('keeps the remaining flat views bookmarkable', () => { + expect(viewFromHash('#queue')).toBe('queue'); + expect(viewFromHash('#server')).toBe('server'); + expect(viewFromHash('#updates')).toBe('updates'); + }); +}); diff --git a/EchoionWeb/frontend/src/lib/router.ts b/EchoionWeb/frontend/src/lib/router.ts index c88c8a1..42cbddb 100644 --- a/EchoionWeb/frontend/src/lib/router.ts +++ b/EchoionWeb/frontend/src/lib/router.ts @@ -1,50 +1,41 @@ // Tiny hash router: keeps the active view in the URL so views are // bookmarkable and the browser back/forward buttons work. No dependency — -// the app has a single flat set of views. The Watch view owns its own -// `#watch/` hash (see watch.ts joinRoom/leaveRoom); this router only -// reads the room from it to auto-join a deep-linked room. +// the app has a single flat set of views. import { appStore, type ViewName } from './app'; -import { joinRoom, watchStore } from './watch'; const VIEWS: readonly ViewName[] = [ - 'now', + 'dashboard', 'queue', 'search', 'library', 'stats', - 'watch', 'server', + 'updates', 'rpc', ]; -// The view named by the current hash, defaulting to `now`. Handles both -// `#queue` and the watch form `#watch/`. -export function viewFromHash(): ViewName { - const raw = location.hash.replace(/^#\/?/, ''); +// The view named by the current hash, defaulting to `dashboard`. Old `#now` +// bookmarks are intentionally canonicalized during router initialization. +export function viewFromHash(hash = location.hash): ViewName { + const raw = hash.replace(/^#\/?/, ''); const base = raw.split(/[/?]/)[0]; + if (base === 'now') return 'dashboard'; return (VIEWS as readonly string[]).includes(base) ? (base as ViewName) - : 'now'; -} - -function roomFromHash(): string | null { - const m = location.hash.match(/^#watch\/([\w-]{1,48})/); - return m ? m[1] : null; + : 'dashboard'; } export function initRouter() { // Initial view comes from the hash (refresh / shared link). - appStore.set({ view: viewFromHash() }); + const initial = viewFromHash(); + appStore.set({ view: initial }); + if (location.hash.replace(/^#\/?/, '').split(/[/?]/)[0] === 'now') { + history.replaceState(null, '', '#dashboard'); + } window.addEventListener('hashchange', () => { const view = viewFromHash(); appStore.set({ view }); - // Auto-join a room that appears in the hash (pasted link, or - // back/forward onto a different room). Leaving is always explicit. - if (view === 'watch') { - const room = roomFromHash(); - if (room && room !== watchStore.get().room) joinRoom(room); - } }); } diff --git a/EchoionWeb/frontend/src/lib/rpc.test.ts b/EchoionWeb/frontend/src/lib/rpc.test.ts index c1be43c..5e087bf 100644 --- a/EchoionWeb/frontend/src/lib/rpc.test.ts +++ b/EchoionWeb/frontend/src/lib/rpc.test.ts @@ -75,6 +75,18 @@ describe('RpcClient wire contract', () => { expect(frame.authToken).toBe('tok-abc'); }); + it('sends updater requests through their append-only RPC enum names', async () => { + installFakes(); + const rpc = new RpcClient(); + await rpc.connect(); + const ws = FakeWebSocket.instances[0]; + + rpc.call('GetUpdateStatus'); + const frame = JSON.parse(ws.sent[0]); + expect(frame.method).toBe('GetUpdateStatus'); + expect(JSON.parse(frame.params)).toEqual({}); + }); + it('resolves a call by requestId and JSON-decodes the result string', async () => { installFakes(); const rpc = new RpcClient(); @@ -125,6 +137,21 @@ describe('RpcClient wire contract', () => { expect(seen).toEqual([{ position: 1000, duration: 200000 }]); }); + it('dispatches the updater change event without renaming it', async () => { + installFakes(); + const rpc = new RpcClient(); + await rpc.connect(); + const ws = FakeWebSocket.instances[0]; + + const seen: unknown[] = []; + rpc.on('updates.changed', (data) => seen.push(data)); + ws.receive({ + event: 'updates.changed', + data: JSON.stringify({ component: 'core', state: 'staged' }), + }); + expect(seen).toEqual([{ component: 'core', state: 'staged' }]); + }); + it('fires the wildcard listener with event name and data', async () => { installFakes(); const rpc = new RpcClient(); @@ -139,4 +166,18 @@ describe('RpcClient wire contract', () => { }); expect(seen).toEqual([['queue.updated', { size: 3 }]]); }); + + it('unsubscribes a notification listener', async () => { + installFakes(); + const rpc = new RpcClient(); + await rpc.connect(); + const ws = FakeWebSocket.instances[0]; + const seen: unknown[] = []; + const unsubscribe = rpc.on('listening_rooms.updated', (data) => + seen.push(data) + ); + unsubscribe(); + ws.receive({ event: 'listening_rooms.updated', data: '{}' }); + expect(seen).toEqual([]); + }); }); diff --git a/EchoionWeb/frontend/src/lib/rpc.ts b/EchoionWeb/frontend/src/lib/rpc.ts index a6ad4eb..ee23d90 100644 --- a/EchoionWeb/frontend/src/lib/rpc.ts +++ b/EchoionWeb/frontend/src/lib/rpc.ts @@ -62,9 +62,33 @@ export type RpcMethodName = | 'GetAuditLog' | 'GetUserPrefs' | 'SetUserPrefs' - | 'GetCustomEmojis' - | 'AddCustomEmoji' - | 'RemoveCustomEmoji'; + | 'GetCapabilities' + | 'GetPluginExtensions' + | 'PluginCall' + | 'GetTeamSpeakDirectory' + | 'MoveTeamSpeakClient' + | 'KickTeamSpeakClient' + | 'BanTeamSpeakClient' + | 'GetTeamSpeakBans' + | 'UnbanTeamSpeakClient' + | 'CreateTeamSpeakChannel' + | 'EditTeamSpeakChannel' + | 'ReorderTeamSpeakChannel' + | 'DeleteTeamSpeakChannel' + | 'GetTeamSpeakServerGroups' + | 'AddTeamSpeakServerGroupMember' + | 'RemoveTeamSpeakServerGroupMember' + | 'SendTeamSpeakPrivateMessage' + | 'SendTeamSpeakChannelMessage' + | 'SendTeamSpeakServerMessage' + | 'GetUpdateStatus' + | 'GetUpdateConfig' + | 'SetUpdateConfig' + | 'CheckForUpdates' + | 'ApplyUpdate' + | 'RollbackUpdate' + | 'ConfirmUnsignedUpdate'; + type Pending = { resolve: (value: unknown) => void; @@ -226,6 +250,13 @@ export class RpcClient { on(event: string, cb: (...args: unknown[]) => void) { if (!this.listeners.has(event)) this.listeners.set(event, []); this.listeners.get(event)!.push(cb); + return () => { + const listeners = this.listeners.get(event); + if (!listeners) return; + const index = listeners.indexOf(cb); + if (index >= 0) listeners.splice(index, 1); + if (listeners.length === 0) this.listeners.delete(event); + }; } authenticate(token: string) { diff --git a/EchoionWeb/frontend/src/lib/store.ts b/EchoionWeb/frontend/src/lib/store.ts index 086de26..7104e1b 100644 --- a/EchoionWeb/frontend/src/lib/store.ts +++ b/EchoionWeb/frontend/src/lib/store.ts @@ -28,5 +28,9 @@ export class Store { } export function useStore(store: Store): T { - return useSyncExternalStore(store.subscribe, () => store.get()); + return useSyncExternalStore( + store.subscribe, + () => store.get(), + () => store.get() + ); } diff --git a/EchoionWeb/frontend/src/lib/types.ts b/EchoionWeb/frontend/src/lib/types.ts index d91349b..f8ef1a9 100644 --- a/EchoionWeb/frontend/src/lib/types.ts +++ b/EchoionWeb/frontend/src/lib/types.ts @@ -12,6 +12,48 @@ export interface Track { source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex } +export interface PublicDashboardClient { + nickname: string; + talking: boolean; + muted: boolean; + deafened: boolean; + away: boolean; +} + +export interface PublicDashboardChannel { + id: number; + name: string; + parentId: number | null; + order: number; + default: boolean; + permanent: boolean; + semiPermanent: boolean; + password: boolean; + maxClients: number; + currentClients: number; + clients: PublicDashboardClient[]; + channels: PublicDashboardChannel[]; +} + +export interface PublicDashboard { + server: { + name: string; + connected: boolean; + clientCount: number; + maxClients: number; + channelCount: number; + revision: number; + }; + channels: PublicDashboardChannel[]; + playback: { + isPlaying: boolean; + isPaused: boolean; + positionMs: number; + volume: number; + track: (Track & { durationMs?: number; album?: string }) | null; + }; +} + export interface QueueEntry { queueId: number; track: Track; diff --git a/EchoionWeb/frontend/src/lib/updates.test.ts b/EchoionWeb/frontend/src/lib/updates.test.ts new file mode 100644 index 0000000..b587600 --- /dev/null +++ b/EchoionWeb/frontend/src/lib/updates.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest'; +import { + configForSave, + isValidSourceId, + normalizeUpdateConfig, + normalizeUpdateStatus, +} from './updates'; + +describe('update payload normalization', () => { + it('normalizes direct config and strips read-only secret presence on save', () => { + const config = normalizeUpdateConfig({ + enabled: true, + checkInterval: '12h', + sources: { + private: { + url: ' https://updates.example/feed.json ', + publicKeys: [{ id: ' key-1 ', ed25519: ' abc123 ' }], + allowUnsigned: false, + bearerTokenEnv: ' UPDATE_TOKEN ', + bearerTokenPresent: true, + bearerToken: 'must-not-enter-browser-state', + }, + }, + runtime: { source: 'private', channel: 'stable' }, + plugins: { managedOnly: false }, + }); + + expect(config.checkInterval).toBe('12h'); + expect(config.sources.private.bearerTokenPresent).toBe(true); + expect(config.sources.private).not.toHaveProperty('bearerToken'); + expect(config.runtime.source).toBe('private'); + expect(config.plugins.managedOnly).toBe(true); + const writable = configForSave(config); + expect(writable.sources.private).not.toHaveProperty( + 'bearerTokenPresent' + ); + expect(writable.sources.private.bearerTokenEnv).toBe('UPDATE_TOKEN'); + expect(writable.sources.private.url).toBe( + 'https://updates.example/feed.json' + ); + expect(writable.sources.private.publicKeys).toEqual([ + { id: 'key-1', ed25519: 'abc123' }, + ]); + }); + + it('normalizes component candidates, plugin inventory, and history', () => { + const status = normalizeUpdateStatus({ + enabled: true, + checking: false, + components: { + runtime: { + installedVersion: '1.0.0', + availableVersion: '1.1.0', + signed: false, + requiresRestart: true, + }, + core: { currentVersion: '4.0.0', state: 'healthy' }, + plugins: { state: 'current' }, + }, + pluginEntries: [ + { + pluginId: 'weather', + managed: true, + installedVersion: '2.0.0', + candidate: { version: '2.1.0', signed: true }, + }, + ], + history: [{ timestamp: 42, component: 'runtime', result: 'success' }], + }); + + expect(status.components.runtime.currentVersion).toBe('1.0.0'); + expect(status.components.runtime.candidate).toMatchObject({ + version: '1.1.0', + signed: false, + requiresRestart: true, + }); + expect(status.plugins[0]).toMatchObject({ + id: 'weather', + managed: true, + currentVersion: '2.0.0', + }); + expect(status.history).toHaveLength(1); + }); + + it('accepts safe source identifiers only', () => { + expect(isValidSourceId('private-beta_2')).toBe(true); + expect(isValidSourceId('../escape')).toBe(false); + expect(isValidSourceId('has spaces')).toBe(false); + expect(isValidSourceId('')).toBe(false); + }); +}); diff --git a/EchoionWeb/frontend/src/lib/updates.ts b/EchoionWeb/frontend/src/lib/updates.ts new file mode 100644 index 0000000..17e4ad1 --- /dev/null +++ b/EchoionWeb/frontend/src/lib/updates.ts @@ -0,0 +1,481 @@ +export type UpdateComponent = 'runtime' | 'core' | 'plugins'; + +export interface UpdatePublicKey { + id: string; + ed25519: string; +} + +export interface UpdateSourceConfig { + url: string; + publicKeys: UpdatePublicKey[]; + allowUnsigned: boolean; + bearerTokenEnv: string; + // Read-only status supplied by the server. It is stripped before save so + // the browser can never turn secret-presence metadata into configuration. + bearerTokenPresent?: boolean; + [key: string]: unknown; +} + +export interface ComponentUpdatePolicy { + enabled: boolean; + source: string; + channel: string; + autoApply: boolean; + [key: string]: unknown; +} + +export interface PluginOverridePolicy { + source: string; + channel: string; + autoApply: boolean; + [key: string]: unknown; +} + +export interface PluginUpdatePolicy extends ComponentUpdatePolicy { + managedOnly: boolean; + overrides: Record; +} + +export interface UpdateConfig { + enabled: boolean; + checkInterval: string; + jitter: string; + maintenanceWindowUtc: { + start: string; + duration: string; + [key: string]: unknown; + }; + maxRuntimeDeferral: string; + retainHealthyVersions: number; + sources: Record; + runtime: ComponentUpdatePolicy; + core: ComponentUpdatePolicy; + plugins: PluginUpdatePolicy; + [key: string]: unknown; +} + +export interface UpdateCandidate { + id?: string; + version: string; + channel?: string; + source?: string; + signed?: boolean; + compatible?: boolean; + downgrade?: boolean; + requiresRestart?: boolean; + cohort?: string; + message?: string; + [key: string]: unknown; +} + +export interface ComponentUpdateStatus { + component: UpdateComponent; + currentVersion?: string; + state?: string; + message?: string; + channel?: string; + source?: string; + candidate?: UpdateCandidate; + rollbackVersion?: string; + lastChangedAt?: string | number; + [key: string]: unknown; +} + +export interface PluginUpdateStatus { + id: string; + name?: string; + managed: boolean; + currentVersion?: string; + state?: string; + channel?: string; + source?: string; + candidate?: UpdateCandidate; + rollbackVersion?: string; + message?: string; + [key: string]: unknown; +} + +export interface UpdateHistoryEntry { + timestamp?: string | number; + component?: UpdateComponent | string; + pluginId?: string; + action?: string; + version?: string; + result?: string; + message?: string; + actor?: string; + [key: string]: unknown; +} + +export interface UpdateStatus { + enabled: boolean; + checking: boolean; + lastCheckAt?: string | number; + nextCheckAt?: string | number; + components: Record; + plugins: PluginUpdateStatus[]; + history: UpdateHistoryEntry[]; + message?: string; + [key: string]: unknown; +} + +const DEFAULT_COMPONENT_POLICY: ComponentUpdatePolicy = { + enabled: true, + source: 'official', + channel: 'stable', + autoApply: true, +}; + +export const DEFAULT_UPDATE_CONFIG: UpdateConfig = { + enabled: true, + checkInterval: '6h', + jitter: '30m', + maintenanceWindowUtc: { + start: '03:00', + duration: '2h', + }, + maxRuntimeDeferral: '24h', + retainHealthyVersions: 2, + sources: { + official: { + url: '', + publicKeys: [], + allowUnsigned: false, + bearerTokenEnv: '', + }, + }, + runtime: { ...DEFAULT_COMPONENT_POLICY }, + core: { ...DEFAULT_COMPONENT_POLICY }, + plugins: { + ...DEFAULT_COMPONENT_POLICY, + managedOnly: true, + overrides: {}, + }, +}; + +function record(value: unknown): Record { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : {}; +} + +function stringValue(value: unknown, fallback = ''): string { + return typeof value === 'string' ? value : fallback; +} + +function booleanValue(value: unknown, fallback: boolean): boolean { + return typeof value === 'boolean' ? value : fallback; +} + +function numberValue(value: unknown, fallback: number): number { + return typeof value === 'number' && Number.isFinite(value) + ? value + : fallback; +} + +function unwrap(payload: unknown, key: string): Record { + const outer = record(payload); + const nested = record(outer[key]); + return Object.keys(nested).length ? nested : outer; +} + +function sourceFieldsWithoutSecrets( + source: Record +): Record { + return Object.fromEntries( + Object.entries(source).filter(([key]) => { + if (key === 'bearerTokenEnv' || key === 'bearerTokenPresent') { + return true; + } + return !/(token|secret|password|authorization|privatekey)/i.test(key); + }) + ); +} + +function normalizeComponentPolicy( + value: unknown, + fallback: ComponentUpdatePolicy +): ComponentUpdatePolicy { + const raw = record(value); + return { + ...raw, + enabled: booleanValue(raw.enabled, fallback.enabled), + source: stringValue(raw.source, fallback.source), + channel: stringValue(raw.channel, fallback.channel), + autoApply: booleanValue(raw.autoApply, fallback.autoApply), + }; +} + +function normalizePluginOverride( + value: unknown, + fallback: ComponentUpdatePolicy +): PluginOverridePolicy { + const raw = record(value); + return { + ...raw, + source: stringValue(raw.source, fallback.source), + channel: stringValue(raw.channel, fallback.channel), + autoApply: booleanValue(raw.autoApply, fallback.autoApply), + }; +} + +export function normalizeUpdateConfig(payload: unknown): UpdateConfig { + const raw = unwrap(payload, 'config'); + const rawSources = record(raw.sources); + const sources: Record = {}; + + for (const [id, value] of Object.entries(rawSources)) { + const source = record(value); + const safeSource = sourceFieldsWithoutSecrets(source); + const rawKeys = Array.isArray(source.publicKeys) + ? source.publicKeys + : []; + sources[id] = { + ...safeSource, + url: stringValue(source.url), + publicKeys: rawKeys.map((key) => { + const rawKey = record(key); + return { + id: stringValue(rawKey.id), + ed25519: stringValue(rawKey.ed25519), + }; + }), + allowUnsigned: booleanValue(source.allowUnsigned, false), + bearerTokenEnv: stringValue(source.bearerTokenEnv), + ...(typeof source.bearerTokenPresent === 'boolean' + ? { bearerTokenPresent: source.bearerTokenPresent } + : {}), + }; + } + + if (!Object.keys(sources).length) { + sources.official = { ...DEFAULT_UPDATE_CONFIG.sources.official }; + } + + const runtime = normalizeComponentPolicy( + raw.runtime, + DEFAULT_UPDATE_CONFIG.runtime + ); + const core = normalizeComponentPolicy(raw.core, DEFAULT_UPDATE_CONFIG.core); + const rawPlugins = record(raw.plugins); + const pluginBase = normalizeComponentPolicy( + rawPlugins, + DEFAULT_UPDATE_CONFIG.plugins + ); + const overrides: Record = {}; + for (const [id, value] of Object.entries(record(rawPlugins.overrides))) { + overrides[id] = normalizePluginOverride(value, pluginBase); + } + + const rawWindow = record(raw.maintenanceWindowUtc); + return { + ...raw, + enabled: booleanValue(raw.enabled, DEFAULT_UPDATE_CONFIG.enabled), + checkInterval: stringValue( + raw.checkInterval, + DEFAULT_UPDATE_CONFIG.checkInterval + ), + jitter: stringValue(raw.jitter, DEFAULT_UPDATE_CONFIG.jitter), + maintenanceWindowUtc: { + ...rawWindow, + start: stringValue( + rawWindow.start, + DEFAULT_UPDATE_CONFIG.maintenanceWindowUtc.start + ), + duration: stringValue( + rawWindow.duration, + DEFAULT_UPDATE_CONFIG.maintenanceWindowUtc.duration + ), + }, + maxRuntimeDeferral: stringValue( + raw.maxRuntimeDeferral, + DEFAULT_UPDATE_CONFIG.maxRuntimeDeferral + ), + retainHealthyVersions: numberValue( + raw.retainHealthyVersions, + DEFAULT_UPDATE_CONFIG.retainHealthyVersions + ), + sources, + runtime, + core, + plugins: { + ...rawPlugins, + ...pluginBase, + // Loose local shared objects are never updater-owned. Keep this an + // invariant even if an older or hand-written config says otherwise. + managedOnly: true, + overrides, + }, + }; +} + +function normalizeCandidate(value: unknown): UpdateCandidate | undefined { + const raw = record(value); + const version = stringValue(raw.version || raw.availableVersion); + if (!version) return undefined; + return { + ...raw, + id: stringValue(raw.id || raw.candidateId) || undefined, + version, + channel: stringValue(raw.channel) || undefined, + source: stringValue(raw.source) || undefined, + ...(typeof raw.signed === 'boolean' ? { signed: raw.signed } : {}), + ...(typeof raw.compatible === 'boolean' + ? { compatible: raw.compatible } + : {}), + ...(typeof raw.downgrade === 'boolean' + ? { downgrade: raw.downgrade } + : {}), + ...(typeof raw.requiresRestart === 'boolean' + ? { requiresRestart: raw.requiresRestart } + : {}), + cohort: stringValue(raw.cohort) || undefined, + message: stringValue(raw.message) || undefined, + }; +} + +function normalizeComponent( + component: UpdateComponent, + value: unknown +): ComponentUpdateStatus { + const raw = record(value); + const candidate = + normalizeCandidate(raw.candidate) || + normalizeCandidate({ + version: raw.availableVersion, + id: raw.candidateId, + channel: raw.availableChannel, + source: raw.availableSource, + signed: raw.signed, + compatible: raw.compatible, + downgrade: raw.downgrade, + requiresRestart: raw.requiresRestart, + }); + return { + ...raw, + component, + currentVersion: + stringValue(raw.currentVersion || raw.installedVersion) || undefined, + state: stringValue(raw.state || raw.status) || undefined, + message: stringValue(raw.message) || undefined, + channel: stringValue(raw.channel) || undefined, + source: stringValue(raw.source) || undefined, + candidate, + rollbackVersion: stringValue(raw.rollbackVersion) || undefined, + lastChangedAt: + typeof raw.lastChangedAt === 'string' || + typeof raw.lastChangedAt === 'number' + ? raw.lastChangedAt + : undefined, + }; +} + +function normalizePlugin(value: unknown): PluginUpdateStatus | null { + const raw = record(value); + const id = stringValue(raw.id || raw.pluginId); + if (!id) return null; + return { + ...raw, + id, + name: stringValue(raw.name) || undefined, + managed: booleanValue(raw.managed, false), + currentVersion: + stringValue(raw.currentVersion || raw.installedVersion) || undefined, + state: stringValue(raw.state || raw.status) || undefined, + channel: stringValue(raw.channel) || undefined, + source: stringValue(raw.source) || undefined, + candidate: + normalizeCandidate(raw.candidate) || + normalizeCandidate({ + version: raw.availableVersion, + id: raw.candidateId, + signed: raw.signed, + compatible: raw.compatible, + downgrade: raw.downgrade, + requiresRestart: raw.requiresRestart, + }), + rollbackVersion: stringValue(raw.rollbackVersion) || undefined, + message: stringValue(raw.message) || undefined, + }; +} + +export function normalizeUpdateStatus(payload: unknown): UpdateStatus { + const raw = unwrap(payload, 'status'); + const rawComponents = record(raw.components); + const pluginComponent = record( + rawComponents.plugins || + (!Array.isArray(raw.plugins) ? raw.plugins : undefined) + ); + const rawPluginEntries = + (Array.isArray(raw.pluginEntries) && raw.pluginEntries) || + (Array.isArray(raw.managedPlugins) && raw.managedPlugins) || + (Array.isArray(raw.plugins) && raw.plugins) || + (Array.isArray(pluginComponent.items) && pluginComponent.items) || + []; + const rawHistory = Array.isArray(raw.history) ? raw.history : []; + + return { + ...raw, + enabled: booleanValue(raw.enabled, true), + checking: booleanValue(raw.checking, false), + lastCheckAt: + typeof raw.lastCheckAt === 'string' || + typeof raw.lastCheckAt === 'number' + ? raw.lastCheckAt + : undefined, + nextCheckAt: + typeof raw.nextCheckAt === 'string' || + typeof raw.nextCheckAt === 'number' + ? raw.nextCheckAt + : undefined, + components: { + runtime: normalizeComponent( + 'runtime', + rawComponents.runtime || raw.runtime + ), + core: normalizeComponent('core', rawComponents.core || raw.core), + plugins: normalizeComponent('plugins', pluginComponent), + }, + plugins: rawPluginEntries + .map(normalizePlugin) + .filter((plugin): plugin is PluginUpdateStatus => plugin !== null), + history: rawHistory.map((entry) => record(entry) as UpdateHistoryEntry), + message: stringValue(raw.message) || undefined, + }; +} + +export function configForSave(config: UpdateConfig): UpdateConfig { + const normalized = normalizeUpdateConfig(config); + const sources: Record = {}; + for (const [id, source] of Object.entries(normalized.sources)) { + const { bearerTokenPresent: _present, ...writable } = source; + sources[id] = { + ...sourceFieldsWithoutSecrets(writable), + url: source.url.trim(), + allowUnsigned: source.allowUnsigned, + bearerTokenEnv: source.bearerTokenEnv.trim(), + publicKeys: source.publicKeys + .map((key) => ({ + id: key.id.trim(), + ed25519: key.ed25519.trim(), + })) + .filter((key) => key.id || key.ed25519), + }; + } + return { + ...normalized, + sources, + retainHealthyVersions: Math.max( + 1, + Math.min(10, Math.trunc(normalized.retainHealthyVersions)) + ), + }; +} + +export function isValidSourceId(value: string): boolean { + return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value); +} + +export function cloneUpdateConfig(config: UpdateConfig): UpdateConfig { + return normalizeUpdateConfig(JSON.parse(JSON.stringify(config))); +} diff --git a/EchoionWeb/frontend/src/lib/useControlsAutoHide.ts b/EchoionWeb/frontend/src/lib/useControlsAutoHide.ts deleted file mode 100644 index b131790..0000000 --- a/EchoionWeb/frontend/src/lib/useControlsAutoHide.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { useEffect, useState, type RefObject } from 'react'; - -// Auto-hides the Watch player's overlay controls (and the mouse cursor) after -// `idleMs` of no input while a video is PLAYING, and reveals them instantly on -// any input — like a regular video player, in both windowed and fullscreen. -// Hover / keyboard-focus reveal (and keeping controls up while a dropdown is -// open) is left to CSS (:hover / :focus-within); this hook only owns the idle -// timeout and the "always visible while paused" rule. Returns the hidden flag. -export function useControlsAutoHide( - shellRef: RefObject, - opts: { playing: boolean; enabled?: boolean; idleMs?: number } -): boolean { - const { playing, enabled = true, idleMs = 3000 } = opts; - const [hidden, setHidden] = useState(false); - - useEffect(() => { - const shell = shellRef.current; - // Paused, disabled, or no element: always show, no timer. - if (!shell || !enabled || !playing) { - setHidden(false); - return; - } - let timer: number | undefined; - const arm = () => { - if (timer) window.clearTimeout(timer); - timer = window.setTimeout(() => setHidden(true), idleMs); - }; - const reveal = () => { - setHidden(false); // React bails when already false → no churn - arm(); - }; - const events = [ - 'mousemove', - 'pointerdown', - 'touchstart', - 'keydown', - 'focusin', - ] as const; - for (const e of events) { - shell.addEventListener(e, reveal, { passive: true }); - } - // Entering/leaving fullscreen counts as activity. - document.addEventListener('fullscreenchange', reveal); - arm(); - return () => { - if (timer) window.clearTimeout(timer); - for (const e of events) shell.removeEventListener(e, reveal); - document.removeEventListener('fullscreenchange', reveal); - }; - }, [shellRef, playing, enabled, idleMs]); - - return hidden; -} diff --git a/EchoionWeb/frontend/src/lib/watch.ts b/EchoionWeb/frontend/src/lib/watch.ts deleted file mode 100644 index 7deb190..0000000 --- a/EchoionWeb/frontend/src/lib/watch.ts +++ /dev/null @@ -1,1293 +0,0 @@ -// Synchronized watching — an independent feature, unrelated to the music bot. -// TypeScript port of web/watch.js. The server (EchoionWeb /ws) is the timing -// authority for a room; every browser plays the video locally and reconciles -// to the server's position. -// -// Roles: the first authenticated joiner is the host; only the host may -// load/play/pause/seek (the server enforces this and answers watch.denied -// otherwise). Twitch rooms are live: everyone embeds the same channel and -// there is nothing to seek. - -import { Store } from './store'; -import { t } from '../i18n'; -import { - detectEmbedAdapter, - prepareEmbedUrl, - type EmbedAdapter, - type PlayerExtraControl, -} from './embedProtocols'; -import { - loadYouTubeApi, - YOUTUBE_EMBED_HOST, - youtubeEmbedVars, -} from './youtube'; - -export interface WatchQueueItem { - source: string; - url?: string; - videoId?: string; - title?: string; - thumbnailUrl?: string; - addedBy?: string; -} - -export interface RoomSummary { - name: string; - participants: number; - source: string; - videoId?: string; - nowTitle?: string; - hasHost: boolean; -} - -export interface Participant { - id: number; - name: string; - uid?: string; - host?: boolean; - buffering?: boolean; - offsetMs?: number | null; -} - -export interface ChatEntry { - name: string; - text: string; - at: number; // local receipt time -} - -// Watch sources. youtube/twitch use provider iframes; `direct` is a raw -// video/HLS URL played in an HTML5