feat/retire-plugin-path #2
No files matched your search
@@ -0,0 +1,7 @@
|
||||
.git
|
||||
build*
|
||||
dist
|
||||
release
|
||||
EchoionWeb/frontend/node_modules
|
||||
EchoionWeb/frontend/web-dist
|
||||
docs
|
||||
@@ -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://<gitea>/<owner>/<repo>/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.
|
||||
@@ -0,0 +1,3 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MCowBQYDK2VwAyEASj3V/xDWSJ37MwLjhyZ0MZPwj/DoJUEWZdYSv+R5NNI=
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{
|
||||
"id": "echoion-release-2026-07",
|
||||
"ed25519": "Sj3V/xDWSJ37MwLjhyZ0MZPwj/DoJUEWZdYSv+R5NNI="
|
||||
}
|
||||
]
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+6
-1
@@ -1,6 +1,11 @@
|
||||
*build*
|
||||
release
|
||||
/dist/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.claude
|
||||
.cache
|
||||
.idea
|
||||
AGENTS.md
|
||||
.vscode
|
||||
.opencode/
|
||||
.opencode/
|
||||
@@ -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
|
||||
|
||||
+191
-56
@@ -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(
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-ffile-prefix-map=${_echoionPrefixMap}>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-fmacro-prefix-map=${_echoionPrefixMap}>"
|
||||
"$<$<COMPILE_LANGUAGE:C,CXX>:-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 <install_dir>")
|
||||
message(STATUS "To package: cpack -G TGZ (or DEB, RPM, ZIP, NSIS)")
|
||||
message(STATUS "To release: scripts/release.sh --version <version>")
|
||||
message(STATUS "")
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+1
-1
Submodule EchoionApi updated: e7573fbcd0...caac928923.
+1
-1
Submodule EchoionCore updated: 5c036d91fb...7975f2b38e.
@@ -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
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
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()
|
||||
@@ -0,0 +1,100 @@
|
||||
#pragma once
|
||||
#include <Void/System/FileWatcher.hpp>
|
||||
#include <Void/Plugin/Manager.hpp>
|
||||
#include <CoreInterface.hpp>
|
||||
#include <PluginTypes.hpp>
|
||||
#include <Types.hpp>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
#include <thread>
|
||||
|
||||
namespace Echoion::Host
|
||||
{
|
||||
|
||||
class CoreLoader
|
||||
{
|
||||
public:
|
||||
|
||||
CoreLoader();
|
||||
~CoreLoader();
|
||||
|
||||
Api::Result<void> load(const std::filesystem::path& libraryPath);
|
||||
Api::Result<void> unload();
|
||||
Api::Result<void>
|
||||
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<void>
|
||||
checkpoint(const std::filesystem::path& destination);
|
||||
Api::Result<void>
|
||||
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<void()>;
|
||||
using HotReloadPrepareCallback = std::function<void()>;
|
||||
void setHotReloadPrepareCallback(HotReloadPrepareCallback callback)
|
||||
{
|
||||
hotReloadPrepareCallback_ = std::move(callback);
|
||||
}
|
||||
void setHotReloadCallback(HotReloadCallback callback)
|
||||
{
|
||||
hotReloadCallback_ = std::move(callback);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Api::Result<void>
|
||||
loadLibraryInternal(const std::filesystem::path& path);
|
||||
Api::Result<void> unloadLibraryInternal();
|
||||
[[nodiscard]] Api::Result<void> 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<bool> loaded_{false};
|
||||
std::atomic<bool> hotReloading_{false};
|
||||
|
||||
// Auto reload
|
||||
Void::FileSystem::FileWatcher fileWatcher_;
|
||||
std::atomic<bool> autoReloadEnabled_{false};
|
||||
|
||||
// Deferred reload - waits for current track to finish
|
||||
std::thread deferredReloadThread_;
|
||||
std::atomic<bool> hasPendingReload_{false};
|
||||
std::atomic<bool> 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
|
||||
@@ -0,0 +1,585 @@
|
||||
#include "echoion/host/CoreLoader.hpp"
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Plugin/Loader.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#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<gid_t> groups(static_cast<std::size_t>(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<Api::ICoreInterface*>(&plugin) !=
|
||||
nullptr;
|
||||
}})
|
||||
{
|
||||
}
|
||||
|
||||
void CoreLoader::enableAutoReload()
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<void> CoreLoader::load(const std::filesystem::path& libraryPath)
|
||||
{
|
||||
std::unique_lock<std::mutex> 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<void> CoreLoader::unload()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
return unloadLibraryInternal();
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
CoreLoader::hotReload(const std::filesystem::path& newLibraryPath)
|
||||
{
|
||||
std::unique_lock<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
return core_;
|
||||
}
|
||||
|
||||
void CoreLoader::setConfigPath(const std::filesystem::path& configPath)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
configPath_ = configPath;
|
||||
}
|
||||
|
||||
std::filesystem::path CoreLoader::getConfigPath() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return configPath_;
|
||||
}
|
||||
|
||||
bool CoreLoader::isHotReloading() const noexcept
|
||||
{
|
||||
return hotReloading_.load();
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
CoreLoader::checkpoint(const std::filesystem::path& destination)
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<char>((value >> shift) & 0xffU));
|
||||
}
|
||||
};
|
||||
appendU32(state.version);
|
||||
appendU32(static_cast<uint32_t>(state.timestamp.size()));
|
||||
bytes.append(state.timestamp);
|
||||
bytes.append(reinterpret_cast<const char*>(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<void>
|
||||
CoreLoader::restoreCheckpoint(const std::filesystem::path& source)
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<unsigned char>((*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<std::ptrdiff_t>(dataOffset),
|
||||
contents->end());
|
||||
return core_->restoreState(state);
|
||||
}
|
||||
|
||||
Api::Result<void>
|
||||
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<void> CoreLoader::refreshCoreHandle()
|
||||
{
|
||||
auto pin = std::make_shared<Void::Plugin::PluginHandle>(
|
||||
pluginManager_.acquire(pluginName_));
|
||||
if (!*pin) {
|
||||
return Api::fail(Api::ErrorCode::PluginError,
|
||||
"Core plugin disappeared from the registry");
|
||||
}
|
||||
auto* interface = dynamic_cast<Api::ICoreInterface*>(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<void> 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
|
||||
Submodule EchoionPlugin deleted from 470ab507e1.
@@ -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()
|
||||
@@ -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.
|
||||
@@ -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 <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::string, std::string>;
|
||||
|
||||
struct ParsedCommand {
|
||||
std::string name;
|
||||
CommandParams params; // first group
|
||||
std::vector<CommandParams> 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
|
||||
@@ -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 <array>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Protocol::Crypto
|
||||
{
|
||||
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
using ByteView = std::span<const uint8_t>;
|
||||
|
||||
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<uint8_t, 8> 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<uint8_t, 16> DUMMY_KEY = {
|
||||
'c', ':', '\\', 'w', 'i', 'n', 'd', 'o',
|
||||
'w', 's', '\\', 's', 'y', 's', 't', 'e'};
|
||||
inline constexpr std::array<uint8_t, 16> 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<uint8_t, 20> sha1(ByteView data);
|
||||
std::array<uint8_t, 32> sha256(ByteView data);
|
||||
std::array<uint8_t, 64> 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<uint8_t> a, ByteView b, size_t len);
|
||||
|
||||
// --- AES-128-CMAC (OMAC1) ----------------------------------------------
|
||||
// 16-byte MAC over `data` under the 16-byte `key`.
|
||||
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data);
|
||||
|
||||
// --- AES-128-EAX --------------------------------------------------------
|
||||
struct EaxResult {
|
||||
Bytes ciphertext;
|
||||
std::array<uint8_t, MAC_LEN> 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<Bytes> eaxDecrypt(ByteView key, ByteView nonce,
|
||||
ByteView header, ByteView ciphertext,
|
||||
ByteView mac);
|
||||
|
||||
// --- Per-packet key/nonce derivation -----------------------------------
|
||||
struct KeyNonce {
|
||||
std::array<uint8_t, 16> key;
|
||||
std::array<uint8_t, 16> 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
|
||||
@@ -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 <cstdint>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
|
||||
class Identity
|
||||
{
|
||||
public:
|
||||
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
using ByteView = std::span<const uint8_t>;
|
||||
|
||||
// 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<void> pkey_;
|
||||
std::string publicKeyString_;
|
||||
std::string uid_;
|
||||
uint64_t keyOffset_ = 0;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
@@ -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 <array>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
using ByteView = std::span<const uint8_t>;
|
||||
|
||||
struct LicenseBlock {
|
||||
std::array<uint8_t, 32> key;
|
||||
std::array<uint8_t, 32> hash; // first 32 bytes of SHA-512(content)
|
||||
uint8_t type = 0;
|
||||
};
|
||||
|
||||
struct TempKey {
|
||||
std::array<uint8_t, 32> publicKey;
|
||||
std::array<uint8_t, 32> privateKey;
|
||||
};
|
||||
|
||||
// Parse the server license blob into its chain of blocks.
|
||||
std::vector<LicenseBlock> parseLicense(ByteView data);
|
||||
|
||||
// Walk the chain from the root key to the final server public key (32 bytes).
|
||||
std::array<uint8_t, 32>
|
||||
deriveLicenseKey(const std::vector<LicenseBlock>& 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<uint8_t, 64>
|
||||
getSharedSecret2(ByteView serverDerivedKey, ByteView tempPrivateKey);
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
@@ -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 <cstdint>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
using ByteView = std::span<const uint8_t>;
|
||||
|
||||
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
|
||||
@@ -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 <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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<void()> onConnected;
|
||||
std::function<void()> onDisconnected;
|
||||
std::function<void(const std::string&)> onError;
|
||||
std::function<void(const ParsedCommand&)> onCommand;
|
||||
std::function<void(const CommandParams&)> onTextMessage;
|
||||
std::function<void(std::span<const uint8_t>)> onVoice;
|
||||
std::function<void(const std::string&)> 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<const uint8_t> opus);
|
||||
// Whisper the frame to the given channel/client targets.
|
||||
void sendWhisper(std::span<const uint8_t> opus,
|
||||
const std::vector<uint64_t>& channelIds,
|
||||
const std::vector<uint16_t>& 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<const uint8_t> raw);
|
||||
void sendOutgoing(std::span<const uint8_t> data, PacketType type,
|
||||
uint8_t extraFlags = 0);
|
||||
std::vector<uint8_t> buildRawPacket(std::span<const uint8_t> data,
|
||||
PacketType type,
|
||||
uint16_t packetId,
|
||||
uint8_t flags);
|
||||
void encryptPacket(std::vector<uint8_t>& raw, PacketType type,
|
||||
uint16_t packetId, uint32_t gen, uint8_t flags,
|
||||
std::span<const uint8_t> data);
|
||||
std::vector<uint8_t> decryptPacket(std::span<const uint8_t> raw,
|
||||
PacketType type,
|
||||
uint16_t packetId, uint32_t gen,
|
||||
uint8_t flags, bool& ok);
|
||||
void sendRawLocked(const std::vector<uint8_t>& raw);
|
||||
void sendInitPacket(const std::vector<uint8_t>& data);
|
||||
|
||||
// ---- handshake / commands ----
|
||||
std::vector<uint8_t> buildInit0();
|
||||
void handleInit(std::span<const uint8_t> data);
|
||||
void handleCommandData(std::span<const uint8_t> data, uint8_t flags);
|
||||
void processCommand(std::span<const uint8_t> 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<ClientState> state_{ClientState::Disconnected};
|
||||
std::atomic<uint16_t> clientId_{0};
|
||||
|
||||
std::thread thread_;
|
||||
std::atomic<bool> 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<uint16_t, 9> packetCounter_{};
|
||||
std::array<uint32_t, 9> generationCounter_{};
|
||||
|
||||
bool cryptoInitComplete_ = false;
|
||||
std::vector<uint8_t> ivStruct_;
|
||||
std::array<uint8_t, 8> fakeSignature_{};
|
||||
std::vector<uint8_t> alphaTmp_;
|
||||
|
||||
// resend tracking
|
||||
struct Resend {
|
||||
std::vector<uint8_t> raw;
|
||||
uint16_t packetId = 0;
|
||||
int64_t firstSend = 0;
|
||||
int64_t lastSend = 0;
|
||||
};
|
||||
std::map<uint16_t, Resend> resendMap_;
|
||||
std::unique_ptr<Resend> initResend_;
|
||||
int64_t lastMessageTime_ = 0;
|
||||
int64_t lastPing_ = 0;
|
||||
int64_t connectStart_ = 0;
|
||||
|
||||
// fragment reassembly
|
||||
std::vector<uint8_t> fragmentBuffer_;
|
||||
bool fragmenting_ = false;
|
||||
uint8_t fragmentFlags_ = 0;
|
||||
|
||||
// channel map for auto-move
|
||||
std::map<std::string, uint64_t> channelMap_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
@@ -1,24 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
// Small dependency-free encoding helpers shared across the protocol modules.
|
||||
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Protocol::Util
|
||||
{
|
||||
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
using ByteView = std::span<const uint8_t>;
|
||||
|
||||
// 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
|
||||
@@ -1,184 +0,0 @@
|
||||
#include "echoion/protocol/Command.hpp"
|
||||
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
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<std::string> 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
|
||||
@@ -1,249 +0,0 @@
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/sha.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
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<uint8_t, BLOCK_SIZE> aesEncryptBlock(
|
||||
ByteView key, std::span<const uint8_t, BLOCK_SIZE> block)
|
||||
{
|
||||
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
|
||||
if (!ctx) {
|
||||
throw std::runtime_error("EVP_CIPHER_CTX_new failed");
|
||||
}
|
||||
std::array<uint8_t, BLOCK_SIZE> 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<int>(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<uint8_t, BLOCK_SIZE> doubleBlock(
|
||||
const std::array<uint8_t, BLOCK_SIZE>& buf)
|
||||
{
|
||||
std::array<uint8_t, BLOCK_SIZE> out{};
|
||||
uint8_t carry = 0;
|
||||
for (int i = BLOCK_SIZE - 1; i >= 0; --i) {
|
||||
uint16_t tmp = static_cast<uint16_t>((buf[i] << 1) | carry);
|
||||
out[i] = static_cast<uint8_t>(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<uint8_t, BLOCK_SIZE> 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<const uint8_t, BLOCK_SIZE> 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<int>(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<size_t>(total) + len);
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::array<uint8_t, 20> sha1(ByteView data)
|
||||
{
|
||||
std::array<uint8_t, 20> out{};
|
||||
::SHA1(data.data(), data.size(), out.data());
|
||||
return out;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 32> sha256(ByteView data)
|
||||
{
|
||||
std::array<uint8_t, 32> out{};
|
||||
::SHA256(data.data(), data.size(), out.data());
|
||||
return out;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 64> sha512(ByteView data)
|
||||
{
|
||||
std::array<uint8_t, 64> 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<uint8_t> a, ByteView b, size_t len)
|
||||
{
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
a[i] ^= b[i];
|
||||
}
|
||||
}
|
||||
|
||||
std::array<uint8_t, BLOCK_SIZE> cmac(ByteView key, ByteView data)
|
||||
{
|
||||
const std::array<uint8_t, BLOCK_SIZE> zero{};
|
||||
auto L = aesEncryptBlock(key, std::span<const uint8_t, BLOCK_SIZE>(
|
||||
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<uint8_t, BLOCK_SIZE> x{};
|
||||
for (size_t i = 0; i + 1 < numBlocks; ++i) {
|
||||
std::array<uint8_t, BLOCK_SIZE> 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<const uint8_t, BLOCK_SIZE>(
|
||||
block.data(), BLOCK_SIZE));
|
||||
}
|
||||
|
||||
std::array<uint8_t, BLOCK_SIZE> 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<const uint8_t, BLOCK_SIZE>(
|
||||
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<const uint8_t, BLOCK_SIZE>(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<Bytes> 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<uint8_t, MAC_LEN> 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<uint8_t>(tag[i] ^ (i < mac.size() ? mac[i] : 0));
|
||||
}
|
||||
if (diff != 0 || mac.size() < MAC_LEN) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return aesCtr(key,
|
||||
std::span<const uint8_t, BLOCK_SIZE>(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<uint8_t>((generationId >> 24) & 0xff);
|
||||
tmp[3] = static_cast<uint8_t>((generationId >> 16) & 0xff);
|
||||
tmp[4] = static_cast<uint8_t>((generationId >> 8) & 0xff);
|
||||
tmp[5] = static_cast<uint8_t>(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<uint8_t>((packetId >> 8) & 0xff);
|
||||
out.key[1] ^= static_cast<uint8_t>(packetId & 0xff);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string hashPassword(const std::string& password)
|
||||
{
|
||||
if (password.empty()) {
|
||||
return "";
|
||||
}
|
||||
auto digest = sha1(ByteView(
|
||||
reinterpret_cast<const uint8_t*>(password.data()), password.size()));
|
||||
return Util::base64Encode(ByteView(digest.data(), digest.size()));
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol::Crypto
|
||||
@@ -1,426 +0,0 @@
|
||||
#include "echoion/protocol/Identity.hpp"
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <openssl/bn.h>
|
||||
#include <openssl/core_names.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/param_build.h>
|
||||
#include <openssl/pem.h>
|
||||
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Protocol
|
||||
{
|
||||
namespace
|
||||
{
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
|
||||
[[noreturn]] void fail(const char* what)
|
||||
{
|
||||
throw std::runtime_error(std::string("Identity: ") + what);
|
||||
}
|
||||
|
||||
EVP_PKEY* asPkey(const std::shared_ptr<void>& p)
|
||||
{
|
||||
return static_cast<EVP_PKEY*>(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<size_t>(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<uint8_t>(len)};
|
||||
}
|
||||
if (len < 0x100) {
|
||||
return {0x81, static_cast<uint8_t>(len)};
|
||||
}
|
||||
return {0x82, static_cast<uint8_t>((len >> 8) & 0xff),
|
||||
static_cast<uint8_t>(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<const uint8_t*>(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<BIGNUM*> 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<int>(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<EVP_PKEY*>(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<char*>("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<void>(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<const uint8_t*>(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<size_t>(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<char>(in)),
|
||||
std::istreambuf_iterator<char>());
|
||||
|
||||
BIO* mem = BIO_new_mem_buf(pem.data(), static_cast<int>(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<void>(pkey, PKeyDeleter{});
|
||||
|
||||
auto uidHash = Crypto::sha1(Crypto::ByteView(
|
||||
reinterpret_cast<const uint8_t*>(id.publicKeyString_.data()),
|
||||
id.publicKeyString_.size()));
|
||||
id.uid_ = Util::base64Encode(
|
||||
Crypto::ByteView(uidHash.data(), uidHash.size()));
|
||||
return id;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
@@ -1,171 +0,0 @@
|
||||
#include "echoion/protocol/License.hpp"
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
|
||||
#include <sodium.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
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<uint8_t, 32> 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<LicenseBlock> parseLicense(ByteView data)
|
||||
{
|
||||
if (data.size() < 1) {
|
||||
fail("license too short");
|
||||
}
|
||||
if (data[0] != 1) {
|
||||
fail("unsupported license version");
|
||||
}
|
||||
|
||||
std::vector<LicenseBlock> 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<uint8_t, 32>
|
||||
deriveLicenseKey(const std::vector<LicenseBlock>& blocks)
|
||||
{
|
||||
ensureSodium();
|
||||
std::array<uint8_t, 32> parentKey = LICENSE_ROOT_KEY;
|
||||
|
||||
for (const auto& block : blocks) {
|
||||
// Clamp the block hash into an Ed25519 scalar.
|
||||
std::array<uint8_t, 32> scalar = block.hash;
|
||||
scalar[0] &= 0xf8;
|
||||
scalar[31] &= 0x3f;
|
||||
scalar[31] |= 0x40;
|
||||
|
||||
std::array<uint8_t, 32> mul{};
|
||||
if (crypto_scalarmult_ed25519_noclamp(mul.data(), scalar.data(),
|
||||
block.key.data()) != 0) {
|
||||
fail("ed25519 scalarmult failed");
|
||||
}
|
||||
std::array<uint8_t, 32> 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<uint8_t, 64> getSharedSecret2(ByteView serverDerivedKey,
|
||||
ByteView tempPrivateKey)
|
||||
{
|
||||
ensureSodium();
|
||||
if (serverDerivedKey.size() != 32 || tempPrivateKey.size() != 32) {
|
||||
fail("bad key length for shared secret");
|
||||
}
|
||||
std::array<uint8_t, 32> priv{};
|
||||
std::memcpy(priv.data(), tempPrivateKey.data(), 32);
|
||||
priv[31] &= 0x7f;
|
||||
|
||||
std::array<uint8_t, 32> 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
|
||||
@@ -1,158 +0,0 @@
|
||||
#include "echoion/protocol/QuickLz.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
|
||||
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<uint32_t>(b[off]) |
|
||||
(static_cast<uint32_t>(b[off + 1]) << 8) |
|
||||
(static_cast<uint32_t>(b[off + 2]) << 16) |
|
||||
(static_cast<uint32_t>(b[off + 3]) << 24);
|
||||
}
|
||||
|
||||
int32_t readI32LE(ByteView b, size_t off)
|
||||
{
|
||||
return static_cast<int32_t>(readU32LE(b, off));
|
||||
}
|
||||
|
||||
uint32_t read24(const Bytes& b, size_t off)
|
||||
{
|
||||
return static_cast<uint32_t>(b[off]) |
|
||||
(static_cast<uint32_t>(b[off + 1]) << 8) |
|
||||
(static_cast<uint32_t>(b[off + 2]) << 16);
|
||||
}
|
||||
|
||||
int hashVal(uint32_t value)
|
||||
{
|
||||
return static_cast<int>(((value >> 12) ^ value) & 0xfff);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
uint32_t qlzDecompressedSize(ByteView data)
|
||||
{
|
||||
return (data[0] & 0x02) != 0
|
||||
? static_cast<uint32_t>(readI32LE(data, 5))
|
||||
: data[2];
|
||||
}
|
||||
|
||||
uint32_t qlzCompressedSize(ByteView data)
|
||||
{
|
||||
return (data[0] & 0x02) != 0
|
||||
? static_cast<uint32_t>(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<int32_t> 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<int32_t>(nextHashed);
|
||||
for (size_t i = nextHashed + 1; i < end; ++i) {
|
||||
nxt = (nxt >> 8) |
|
||||
(static_cast<uint32_t>(dest[i + 2]) << 16);
|
||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
|
||||
}
|
||||
}
|
||||
nextHashed = destPos;
|
||||
} else if (destPos >=
|
||||
std::max<size_t>(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<int32_t>(nextHashed);
|
||||
for (size_t i = nextHashed + 1; i < end; ++i) {
|
||||
nxt = (nxt >> 8) |
|
||||
(static_cast<uint32_t>(dest[i + 2]) << 16);
|
||||
hashtable[hashVal(nxt)] = static_cast<int32_t>(i);
|
||||
}
|
||||
}
|
||||
nextHashed = std::max(nextHashed, end);
|
||||
}
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol
|
||||
@@ -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 <openssl/bn.h>
|
||||
#include <openssl/rand.h>
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
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::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
void putU16BE(std::vector<uint8_t>& b, size_t off, uint16_t v)
|
||||
{
|
||||
b[off] = static_cast<uint8_t>((v >> 8) & 0xff);
|
||||
b[off + 1] = static_cast<uint8_t>(v & 0xff);
|
||||
}
|
||||
uint16_t getU16BE(std::span<const uint8_t> b, size_t off)
|
||||
{
|
||||
return static_cast<uint16_t>((b[off] << 8) | b[off + 1]);
|
||||
}
|
||||
|
||||
// y = x^(2^level) mod n, all big-endian 64-byte.
|
||||
std::vector<uint8_t> rsaPuzzle(std::span<const uint8_t> x,
|
||||
std::span<const uint8_t> n, int32_t level)
|
||||
{
|
||||
BN_CTX* ctx = BN_CTX_new();
|
||||
BIGNUM* bx = BN_bin2bn(x.data(), static_cast<int>(x.size()),
|
||||
nullptr);
|
||||
BIGNUM* bn = BN_bin2bn(n.data(), static_cast<int>(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<uint8_t> 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<size_t>(type);
|
||||
return {packetCounter_[i], generationCounter_[i]};
|
||||
}
|
||||
|
||||
void TsClient::incCounter(PacketType type)
|
||||
{
|
||||
if (type == PacketType::Init1) {
|
||||
return;
|
||||
}
|
||||
auto i = static_cast<size_t>(type);
|
||||
if (++packetCounter_[i] == 0) {
|
||||
++generationCounter_[i];
|
||||
}
|
||||
}
|
||||
|
||||
void TsClient::connect(const TsClientOptions& opts)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> 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<std::recursive_mutex> 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<const uint8_t>(buf, static_cast<size_t>(n)));
|
||||
}
|
||||
}
|
||||
resendTick();
|
||||
}
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (sock_ >= 0) {
|
||||
::close(sock_);
|
||||
sock_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Outgoing ----------------------------------------------------------
|
||||
|
||||
std::vector<uint8_t> TsClient::buildInit0()
|
||||
{
|
||||
std::vector<uint8_t> buf(4 + 1 + 4 + 4 + 8, 0);
|
||||
putU16BE(buf, 0, static_cast<uint16_t>((Crypto::INIT_VERSION >> 16)));
|
||||
putU16BE(buf, 2, static_cast<uint16_t>(Crypto::INIT_VERSION & 0xffff));
|
||||
buf[4] = 0x00; // step 0
|
||||
uint32_t ts = static_cast<uint32_t>(
|
||||
std::chrono::duration_cast<std::chrono::seconds>(
|
||||
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<uint8_t>& 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>(
|
||||
Resend{raw, 101, nowMs(), nowMs()});
|
||||
sendRawLocked(raw);
|
||||
}
|
||||
|
||||
std::vector<uint8_t> TsClient::buildRawPacket(std::span<const uint8_t> data,
|
||||
PacketType type,
|
||||
uint16_t packetId,
|
||||
uint8_t flags)
|
||||
{
|
||||
std::vector<uint8_t> 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<uint8_t>((flags & 0xf0) |
|
||||
(static_cast<uint8_t>(type) & 0x0f));
|
||||
std::memcpy(raw.data() + MAC_LEN + C2S_HEADER_LEN, data.data(),
|
||||
data.size());
|
||||
return raw;
|
||||
}
|
||||
|
||||
void TsClient::encryptPacket(std::vector<uint8_t>& raw, PacketType type,
|
||||
uint16_t packetId, uint32_t gen, uint8_t flags,
|
||||
std::span<const uint8_t> 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<uint8_t>(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<const uint8_t> dataIn, PacketType type,
|
||||
uint8_t extraFlags)
|
||||
{
|
||||
auto ctr = getCounter(type);
|
||||
incCounter(type);
|
||||
|
||||
std::vector<uint8_t> 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<uint8_t>& raw)
|
||||
{
|
||||
if (sock_ < 0) {
|
||||
return;
|
||||
}
|
||||
::send(sock_, raw.data(), raw.size(), 0);
|
||||
}
|
||||
|
||||
void TsClient::sendCommand(const std::string& cmd)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
std::span<const uint8_t> data(
|
||||
reinterpret_cast<const uint8_t*>(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<const uint8_t> opus)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lock(mu_);
|
||||
if (state_.load() != ClientState::Connected) {
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> 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<std::recursive_mutex> lock(mu_);
|
||||
if (state_.load() != ClientState::Connected) {
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> buf(3, 0);
|
||||
buf[2] = 5;
|
||||
sendOutgoing(buf, PacketType::Voice);
|
||||
}
|
||||
|
||||
void TsClient::sendWhisper(std::span<const uint8_t> opus,
|
||||
const std::vector<uint64_t>& channelIds,
|
||||
const std::vector<uint16_t>& clientIds)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> 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<uint8_t> 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<uint8_t>(channelIds.size());
|
||||
buf[p++] = static_cast<uint8_t>(clientIds.size());
|
||||
for (uint64_t cid : channelIds) {
|
||||
for (int s = 56; s >= 0; s -= 8) {
|
||||
buf[p++] = static_cast<uint8_t>((cid >> s) & 0xff);
|
||||
}
|
||||
}
|
||||
for (uint16_t clid : clientIds) {
|
||||
buf[p++] = static_cast<uint8_t>((clid >> 8) & 0xff);
|
||||
buf[p++] = static_cast<uint8_t>(clid & 0xff);
|
||||
}
|
||||
std::memcpy(buf.data() + p, opus.data(), opus.size());
|
||||
sendOutgoing(buf, PacketType::VoiceWhisper);
|
||||
}
|
||||
|
||||
// ---- Incoming ----------------------------------------------------------
|
||||
|
||||
std::vector<uint8_t> TsClient::decryptPacket(std::span<const uint8_t> 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<uint8_t>(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<uint8_t>(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<uint8_t>(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<const uint8_t> 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<PacketType>(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<const uint8_t> 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<uint8_t> buf(2, 0);
|
||||
putU16BE(buf, 0, ackId);
|
||||
sendOutgoing(buf, ackType);
|
||||
}
|
||||
|
||||
void TsClient::handlePing(uint16_t packetId)
|
||||
{
|
||||
std::vector<uint8_t> buf(2, 0);
|
||||
putU16BE(buf, 0, packetId);
|
||||
sendOutgoing(buf, PacketType::Pong);
|
||||
}
|
||||
|
||||
// ---- Handshake ---------------------------------------------------------
|
||||
|
||||
void TsClient::handleInit(std::span<const uint8_t> 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<uint8_t> init2(4 + 1 + 16 + 4, 0);
|
||||
putU16BE(init2, 0,
|
||||
static_cast<uint16_t>(Crypto::INIT_VERSION >> 16));
|
||||
putU16BE(init2, 2,
|
||||
static_cast<uint16_t>(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<const uint8_t> x = data.subspan(1, 64);
|
||||
std::span<const uint8_t> n = data.subspan(65, 64);
|
||||
int32_t level = static_cast<int32_t>(
|
||||
(data[129] << 24) | (data[130] << 16) | (data[131] << 8) |
|
||||
data[132]);
|
||||
std::span<const uint8_t> 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<const uint8_t> textBytes(
|
||||
reinterpret_cast<const uint8_t*>(initAdd.data()),
|
||||
initAdd.size());
|
||||
|
||||
std::vector<uint8_t> init4(4 + 1 + 64 + 64 + 4 + 100 + 64 +
|
||||
textBytes.size(),
|
||||
0);
|
||||
putU16BE(init4, 0,
|
||||
static_cast<uint16_t>(Crypto::INIT_VERSION >> 16));
|
||||
putU16BE(init4, 2,
|
||||
static_cast<uint16_t>(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<const uint8_t> 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<const uint8_t>(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<const uint8_t> data, uint8_t flags)
|
||||
{
|
||||
std::vector<uint8_t> decompressed;
|
||||
if (flags & FLAG_COMPRESSED) {
|
||||
try {
|
||||
decompressed = qlzDecompress(data);
|
||||
data = std::span<const uint8_t>(decompressed.data(),
|
||||
decompressed.size());
|
||||
} catch (const std::exception& e) {
|
||||
debug(std::string("decompression failed: ") + e.what());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
std::string cmdStr(reinterpret_cast<const char*>(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<uint16_t>(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<uint8_t> 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<uint16_t>(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<CommandParams>{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<uint64_t>(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<uint8_t> 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<std::recursive_mutex> 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<std::recursive_mutex> 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
|
||||
@@ -1,116 +0,0 @@
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Echoion::Protocol::Util
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr char kEnc[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
std::array<int8_t, 256> makeDecodeTable()
|
||||
{
|
||||
std::array<int8_t, 256> t{};
|
||||
t.fill(-1);
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
t[static_cast<uint8_t>(kEnc[i])] = static_cast<int8_t>(i);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
const std::array<int8_t, 256> 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<uint32_t>(data[i]) << 16) |
|
||||
(static_cast<uint32_t>(data[i + 1]) << 8) |
|
||||
static_cast<uint32_t>(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<uint32_t>(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<uint32_t>(data[i]) << 16) |
|
||||
(static_cast<uint32_t>(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<uint8_t>(c)];
|
||||
if (v < 0) {
|
||||
throw std::runtime_error("invalid base64 character");
|
||||
}
|
||||
buf = (buf << 6) | static_cast<uint32_t>(v);
|
||||
bits += 6;
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
out.push_back(static_cast<uint8_t>((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<uint8_t>((nib(hex[i]) << 4) |
|
||||
nib(hex[i + 1])));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Echoion::Protocol::Util
|
||||
@@ -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)
|
||||
@@ -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 <cstdio>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace echotest
|
||||
{
|
||||
struct Case {
|
||||
std::string name;
|
||||
std::function<void()> fn;
|
||||
};
|
||||
|
||||
inline std::vector<Case>& registry()
|
||||
{
|
||||
static std::vector<Case> cases;
|
||||
return cases;
|
||||
}
|
||||
|
||||
inline int& failures()
|
||||
{
|
||||
static int f = 0;
|
||||
return f;
|
||||
}
|
||||
|
||||
struct Registrar {
|
||||
Registrar(const std::string& name, std::function<void()> 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)
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
#include "check.hpp"
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
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<uint8_t>& b)
|
||||
{
|
||||
return Util::toHex(ByteView(b.data(), b.size()));
|
||||
}
|
||||
template <size_t N> std::string hx(const std::array<uint8_t, N>& 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<const uint8_t*>(abc.data()), abc.size()));
|
||||
CHECK_EQ(hx(s1),
|
||||
std::string("a9993e364706816aba3e25717850c26c9cd0d89d"));
|
||||
|
||||
// base64 round-trip + known value.
|
||||
CHECK_EQ(Util::base64Encode(ByteView(
|
||||
reinterpret_cast<const uint8_t*>("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));
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
#include "check.hpp"
|
||||
#include "echoion/protocol/Crypto.hpp"
|
||||
#include "echoion/protocol/Identity.hpp"
|
||||
#include "echoion/protocol/Util.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
|
||||
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<const uint8_t*>(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<const uint8_t*>(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());
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
#include "check.hpp"
|
||||
|
||||
int main()
|
||||
{
|
||||
return echotest::run();
|
||||
}
|
||||
@@ -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<uint8_t>(3 + payload.size())); // compressed size
|
||||
buf.push_back(static_cast<uint8_t>(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);
|
||||
}
|
||||
@@ -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=\"$<TARGET_FILE:EchoionCore>\"")
|
||||
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"
|
||||
$<TARGET_FILE:EchoionUpdater>
|
||||
"${CMAKE_SOURCE_DIR}/packaging/service")
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include <PluginTypes.hpp>
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
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<Api::EventCallback> callbacks_;
|
||||
std::size_t activeDispatches_{0};
|
||||
bool accepting_{true};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<std::string>
|
||||
chunkMessage(const std::string& message, std::size_t limit = 900);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<ReleaseFileEntry> files;
|
||||
|
||||
[[nodiscard]] static Api::Result<ReleaseManifest>
|
||||
load(const std::filesystem::path& manifestPath);
|
||||
[[nodiscard]] Api::Result<void> validate() const;
|
||||
[[nodiscard]] Api::Result<void> validateInstallLayout() const;
|
||||
};
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include <expected>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
[[nodiscard]] std::expected<std::filesystem::path, std::string>
|
||||
runningExecutablePath();
|
||||
|
||||
[[nodiscard]] std::filesystem::path deriveInstallRoot(
|
||||
const std::filesystem::path& executablePath,
|
||||
const std::optional<std::filesystem::path>& homeOverride =
|
||||
std::nullopt);
|
||||
|
||||
[[nodiscard]] std::filesystem::path resolveCorePath(
|
||||
const std::filesystem::path& installRoot,
|
||||
const std::filesystem::path& executableDirectory,
|
||||
const std::optional<std::filesystem::path>& coreOverride =
|
||||
std::nullopt);
|
||||
|
||||
[[nodiscard]] std::filesystem::path resolveStateDirectory(
|
||||
const std::optional<std::filesystem::path>& commandLineOverride,
|
||||
const std::optional<std::filesystem::path>& environmentOverride,
|
||||
const std::optional<std::filesystem::path>& xdgStateHome,
|
||||
const std::optional<std::filesystem::path>& userHome,
|
||||
const std::filesystem::path& fallback);
|
||||
|
||||
[[nodiscard]] std::optional<std::filesystem::path> runtimeWorkingDirectory(
|
||||
const std::filesystem::path& installRoot,
|
||||
const std::filesystem::path& executableDirectory);
|
||||
|
||||
[[nodiscard]] std::expected<std::filesystem::path, std::string>
|
||||
resolveAvatarCacheDirectory(
|
||||
const std::filesystem::path& configuredDirectory,
|
||||
const std::filesystem::path& requestedDirectory = {});
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -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 <PluginInterface.hpp>
|
||||
|
||||
#include "echoion/protocol/Identity.hpp"
|
||||
#include "echoion/protocol/TsClient.hpp"
|
||||
#include "echoion/standalone/EventCallbackGate.hpp"
|
||||
#include <Void/TeamSpeak/TeamSpeak.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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<std::optional<Api::ClientInfo>>
|
||||
getClient(uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getClientIp(uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getClientAvatarPath(uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
getClientAvatarUrl(uint64_t clientId) override;
|
||||
[[nodiscard]] Api::Result<std::optional<std::string>>
|
||||
requestClientAvatar(uint64_t clientId,
|
||||
const std::string& destDir) override;
|
||||
Api::Result<void> moveClient(uint64_t clientId,
|
||||
uint64_t channelId) override;
|
||||
Api::Result<void> kickClient(uint64_t clientId,
|
||||
const std::string& reason) override;
|
||||
Api::Result<void>
|
||||
kickClientFromChannel(uint64_t clientId,
|
||||
const std::string& reason) override;
|
||||
Api::Result<void> banClient(uint64_t clientId,
|
||||
uint64_t durationSeconds,
|
||||
const std::string& reason) override;
|
||||
[[nodiscard]] Api::Result<std::vector<Api::BanInfo>>
|
||||
getBans() override;
|
||||
Api::Result<void> unban(uint64_t banId) override;
|
||||
|
||||
// Channels
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
|
||||
getChannels() const override;
|
||||
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
|
||||
getChannel(uint64_t channelId) const override;
|
||||
Api::Result<uint64_t> createChannel(
|
||||
const Api::ChannelCreateOptions& options) override;
|
||||
Api::Result<void>
|
||||
editChannel(uint64_t channelId,
|
||||
const Api::ChannelEditOptions& options) override;
|
||||
Api::Result<void> reorderChannel(uint64_t channelId,
|
||||
uint64_t parentId,
|
||||
uint64_t orderAfterId) override;
|
||||
Api::Result<void> deleteChannel(uint64_t channelId,
|
||||
bool force) override;
|
||||
|
||||
[[nodiscard]] Api::Result<std::vector<Api::ServerGroupInfo>>
|
||||
getServerGroups() override;
|
||||
Api::Result<void>
|
||||
addClientToServerGroup(uint64_t groupId,
|
||||
uint64_t clientDatabaseId) override;
|
||||
Api::Result<void>
|
||||
removeClientFromServerGroup(uint64_t groupId,
|
||||
uint64_t clientDatabaseId) override;
|
||||
[[nodiscard]] Api::Result<Api::ServerInfo>
|
||||
getTeamSpeakServerInfo() override;
|
||||
|
||||
// Messaging
|
||||
Api::Result<void>
|
||||
@@ -83,35 +123,51 @@ namespace Echoion::Standalone
|
||||
Api::Result<void> 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<std::string>
|
||||
hostControl(const std::string& method,
|
||||
const std::string& requestJson) override;
|
||||
using HostControlHandler = std::function<Api::Result<std::string>(
|
||||
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<void> commandResult(
|
||||
const Void::Result::Result<void, Void::TeamSpeak::Error>&
|
||||
result) const;
|
||||
|
||||
StandaloneSettings settings_;
|
||||
std::unique_ptr<Protocol::Identity> identity_;
|
||||
std::unique_ptr<Protocol::TsClient> client_;
|
||||
std::shared_ptr<Void::TeamSpeak::Identity> identity_;
|
||||
std::unique_ptr<Void::TeamSpeak::Client> client_;
|
||||
std::unique_ptr<AudioEncoder> encoder_;
|
||||
|
||||
Api::ServerConfig currentConfig_{};
|
||||
std::atomic<bool> initialized_{false};
|
||||
|
||||
mutable std::mutex mirrorMutex_;
|
||||
std::map<uint64_t, Api::ClientInfo> clients_;
|
||||
std::map<uint64_t, Api::ChannelInfo> channels_;
|
||||
std::map<uint64_t, Void::TeamSpeak::RemoteClient> clients_;
|
||||
std::map<uint64_t, Void::TeamSpeak::Channel> channels_;
|
||||
std::optional<Void::TeamSpeak::ServerInfo> serverInfo_;
|
||||
std::map<uint64_t, std::string> clientIps_;
|
||||
std::map<uint64_t, std::string> avatarHashes_;
|
||||
std::map<uint64_t, std::string> avatarUrls_;
|
||||
std::map<uint64_t, std::string> avatarPaths_;
|
||||
std::vector<uint64_t> whisperList_;
|
||||
std::jthread snapshotThread_;
|
||||
mutable std::mutex hostControlMutex_;
|
||||
HostControlHandler hostControlHandler_;
|
||||
|
||||
std::mutex cbMutex_;
|
||||
std::vector<Api::EventCallback> callbacks_;
|
||||
EventCallbackGate eventCallbacks_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
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";
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <Types.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
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<void> 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<Api::Result<void>(
|
||||
const std::filesystem::path&)>
|
||||
replaceCore;
|
||||
std::function<Api::Result<std::string>(const std::string&)>
|
||||
managePlugins;
|
||||
std::function<Api::Result<std::string>(const std::string&)>
|
||||
manageRuntime;
|
||||
std::function<bool()> playbackActive;
|
||||
std::function<std::string()> 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<void> 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<std::string>
|
||||
handle(const std::string& method,
|
||||
const std::string& requestJson);
|
||||
|
||||
private:
|
||||
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl_;
|
||||
};
|
||||
} // namespace Echoion::Standalone
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "echoion/standalone/EventCallbackGate.hpp"
|
||||
|
||||
#include <Void/Core/Scope.hpp>
|
||||
|
||||
#include <utility>
|
||||
|
||||
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<Api::EventCallback> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
#include "echoion/standalone/MessageChunker.hpp"
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace Echoion::Standalone
|
||||
{
|
||||
std::vector<std::string> chunkMessage(const std::string& message,
|
||||
std::size_t limit)
|
||||
{
|
||||
if (limit == 0 || message.empty()) {
|
||||
return message.empty() ? std::vector<std::string>{}
|
||||
: std::vector<std::string>{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<std::string> 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<unsigned char>(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
#include "echoion/standalone/ReleaseManifest.hpp"
|
||||
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
|
||||
#include <openssl/evp.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <memory>
|
||||
#include <ranges>
|
||||
#include <sstream>
|
||||
#include <tuple>
|
||||
#include <unordered_set>
|
||||
|
||||
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<std::string_view, 4> kImmutableRoots{
|
||||
"bin", "lib", "service", "share"};
|
||||
constexpr double kMaximumExactJsonInteger = 9'007'199'254'740'991.0;
|
||||
|
||||
Api::Result<std::string> 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<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
|
||||
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<char, 64 * 1024> buffer{};
|
||||
while (input) {
|
||||
input.read(buffer.data(),
|
||||
static_cast<std::streamsize>(buffer.size()));
|
||||
if (const auto count = input.gcount();
|
||||
count > 0 &&
|
||||
EVP_DigestUpdate(context.get(), buffer.data(),
|
||||
static_cast<std::size_t>(count)) != 1) {
|
||||
return Api::fail(Api::ErrorCode::UnknownError,
|
||||
"cannot hash release artifact");
|
||||
}
|
||||
}
|
||||
std::array<unsigned char, EVP_MAX_MD_SIZE> 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<unsigned int>(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<std::filesystem::perms> 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<unsigned int>(character - '0');
|
||||
}
|
||||
return static_cast<std::filesystem::perms>(result);
|
||||
}
|
||||
|
||||
std::optional<std::uintmax_t> 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<std::uintmax_t>(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<std::filesystem::path>
|
||||
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<std::filesystem::path>
|
||||
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<void>
|
||||
validateImmutableCoverage(const ReleaseManifest& manifest)
|
||||
{
|
||||
auto prefix = payloadPrefix(manifest);
|
||||
if (!prefix) {
|
||||
return std::unexpected(prefix.error());
|
||||
}
|
||||
|
||||
std::unordered_set<std::string> 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<ReleaseManifest>
|
||||
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<ReleaseManifest>
|
||||
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<std::string> 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>
|
||||
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<void> 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<void> 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
|
||||
@@ -0,0 +1,178 @@
|
||||
#include "echoion/standalone/RuntimePaths.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <ranges>
|
||||
#include <system_error>
|
||||
|
||||
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<std::filesystem::path, std::string> 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<std::filesystem::path>& 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<std::filesystem::path>& 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<std::filesystem::path>& commandLineOverride,
|
||||
const std::optional<std::filesystem::path>& environmentOverride,
|
||||
const std::optional<std::filesystem::path>& xdgStateHome,
|
||||
const std::optional<std::filesystem::path>& 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<std::filesystem::path> 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<std::filesystem::path, std::string>
|
||||
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
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+878
-53
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,153 @@
|
||||
#include "echoion/host/CoreLoader.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <unistd.h>
|
||||
|
||||
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<std::filesystem::path> 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;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#include "echoion/standalone/EventCallbackGate.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
||||
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<int> calls{0};
|
||||
auto lifetime = std::make_shared<int>(42);
|
||||
std::weak_ptr<int> 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);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#include "echoion/standalone/MessageChunker.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
#include "echoion/standalone/ReleaseManifest.hpp"
|
||||
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <sys/stat.h>
|
||||
#include <vector>
|
||||
|
||||
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<std::string> 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;
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
#include "echoion/standalone/RuntimePaths.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
class TemporaryTree
|
||||
{
|
||||
public:
|
||||
|
||||
TemporaryTree()
|
||||
{
|
||||
std::random_device random;
|
||||
path_ =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("echoion-runtime-paths-" +
|
||||
std::to_string(static_cast<unsigned long long>(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;
|
||||
}
|
||||
+62
@@ -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 '<!doctype html>\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
|
||||
@@ -0,0 +1,691 @@
|
||||
#include "echoion/standalone/UpdateService.hpp"
|
||||
|
||||
#include <Void/Crypto/Crypto.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Text/Hex.hpp>
|
||||
#include <Void/Update/Update.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
class TemporaryTree
|
||||
{
|
||||
public:
|
||||
|
||||
TemporaryTree()
|
||||
{
|
||||
std::random_device random;
|
||||
path_ =
|
||||
std::filesystem::temp_directory_path() /
|
||||
("echoion-update-service-" +
|
||||
std::to_string(static_cast<unsigned long long>(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<std::streamsize>(contents.size()));
|
||||
return output.good();
|
||||
}
|
||||
|
||||
std::string readFile(const std::filesystem::path& path)
|
||||
{
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
return {std::istreambuf_iterator<char>{input},
|
||||
std::istreambuf_iterator<char>{}};
|
||||
}
|
||||
|
||||
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<std::string>& response,
|
||||
std::optional<Void::Json::Value>& 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<void> {
|
||||
++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<std::string> {
|
||||
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<Void::Json::Value> 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<Void::Json::Value> 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<Void::Json::Value> 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<Void::Json::Value> 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<Void::Json::Value> 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<Void::Json::Value> 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;
|
||||
}
|
||||
+31
-18
@@ -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}"
|
||||
|
||||
Generated
-39
@@ -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": [
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<string, [string, string]> = {
|
||||
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 (
|
||||
<div id="app">
|
||||
@@ -82,7 +73,7 @@ export function App() {
|
||||
<div className="header-right">
|
||||
<span className="pill">
|
||||
<span className="dot dot-green" />
|
||||
{s.onlineCount} {t('listening')}
|
||||
{s.onlineCount} {t('online')}
|
||||
</span>
|
||||
<button
|
||||
className="icon-btn"
|
||||
@@ -97,18 +88,13 @@ export function App() {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{s.view === 'now' && <NowView />}
|
||||
{s.view === 'dashboard' && <DashboardView />}
|
||||
{s.view === 'queue' && <QueueView />}
|
||||
{s.view === 'search' && <SearchView />}
|
||||
{s.view === 'library' && <LibraryView />}
|
||||
{s.view === 'stats' && <StatsView />}
|
||||
{/* The watch view stays mounted so the embedded player and
|
||||
room connection survive view switches (the old UI only
|
||||
toggled `hidden`). */}
|
||||
<div hidden={s.view !== 'watch'}>
|
||||
<WatchView />
|
||||
</div>
|
||||
{s.view === 'server' && <ServerView />}
|
||||
{s.view === 'updates' && <UpdatesView />}
|
||||
{s.view === 'rpc' && <RpcView />}
|
||||
|
||||
<MiniPlayer />
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useStore } from '../lib/store';
|
||||
import { emojiStore, loadCustomEmojis } from '../lib/emoji';
|
||||
import { safeCall, toast } from '../lib/app';
|
||||
import { CloseIcon } from './icons';
|
||||
import { t } from '../i18n';
|
||||
|
||||
// Admin custom-emoji manager (item 16): upload an image (≤64KB) under a
|
||||
// shortcode name, list existing ones, and remove them. The image is sent as
|
||||
// base64 to AddCustomEmoji and served back at /emoji/<name>.
|
||||
export function EmojiManager() {
|
||||
const { custom } = useStore(emojiStore);
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadCustomEmojis();
|
||||
}, []);
|
||||
|
||||
const upload = async () => {
|
||||
const file = fileRef.current?.files?.[0];
|
||||
const clean = name.trim().toLowerCase();
|
||||
if (!/^[a-z0-9_]{1,32}$/.test(clean)) {
|
||||
toast(t('Emoji name must be 1-32 chars of a-z, 0-9, _'));
|
||||
return;
|
||||
}
|
||||
if (!file) {
|
||||
toast(t('Choose an image file'));
|
||||
return;
|
||||
}
|
||||
if (file.size > 64 * 1024) {
|
||||
toast(t('Emoji image too large (max ~64KB)'));
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
const dataBase64 = await new Promise<string>((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const res = String(reader.result);
|
||||
resolve(res.slice(res.indexOf(',') + 1)); // strip data: prefix
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
const res = await safeCall('AddCustomEmoji', {
|
||||
name: clean,
|
||||
mime: file.type,
|
||||
dataBase64,
|
||||
});
|
||||
setBusy(false);
|
||||
if (res) {
|
||||
toast(t('Emoji added'));
|
||||
setName('');
|
||||
if (fileRef.current) fileRef.current.value = '';
|
||||
loadCustomEmojis();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>
|
||||
{t('Custom emojis')}{' '}
|
||||
<span className="muted">
|
||||
{custom.length ? `· ${custom.length}` : ''}
|
||||
</span>
|
||||
</h2>
|
||||
</div>
|
||||
<div className="emoji-manage-row">
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder={t('shortcode (a-z0-9_)')}
|
||||
maxLength={32}
|
||||
/>
|
||||
<input ref={fileRef} type="file" accept="image/*" />
|
||||
<button
|
||||
className="btn btn-accent"
|
||||
disabled={busy}
|
||||
onClick={upload}
|
||||
>
|
||||
{t('Add emoji')}
|
||||
</button>
|
||||
</div>
|
||||
<div className="emoji-manage-grid">
|
||||
{custom.map((c) => (
|
||||
<div key={c.name} className="emoji-manage-item">
|
||||
<img
|
||||
className="emoji-img-lg"
|
||||
src={`/emoji/${c.name}`}
|
||||
alt={c.name}
|
||||
/>
|
||||
<span className="mono">:{c.name}:</span>
|
||||
<button
|
||||
className="icon-btn danger"
|
||||
title={t('Remove')}
|
||||
onClick={async () => {
|
||||
await safeCall('RemoveCustomEmoji', {
|
||||
name: c.name,
|
||||
});
|
||||
toast(t('Emoji removed'));
|
||||
loadCustomEmojis();
|
||||
}}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<HTMLDivElement>(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 (
|
||||
<div className="emoji-picker" ref={ref}>
|
||||
{recent.length > 0 && (
|
||||
<div className="emoji-section">
|
||||
<div className="emoji-section-label">{t('Recent')}</div>
|
||||
<div className="emoji-grid">
|
||||
{recent.map((token, i) =>
|
||||
token.startsWith(':') ? (
|
||||
<button
|
||||
key={i}
|
||||
className="emoji-btn"
|
||||
onClick={() => pick(token)}
|
||||
>
|
||||
<img
|
||||
src={`/emoji/${token.slice(1, -1)}`}
|
||||
alt={token}
|
||||
className="emoji-img"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
key={i}
|
||||
className="emoji-btn"
|
||||
onClick={() => pick(token)}
|
||||
>
|
||||
{token}
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{custom.length > 0 && (
|
||||
<div className="emoji-section">
|
||||
<div className="emoji-section-label">{t('Custom')}</div>
|
||||
<div className="emoji-grid">
|
||||
{custom.map((c) => (
|
||||
<button
|
||||
key={c.name}
|
||||
className="emoji-btn"
|
||||
title={`:${c.name}:`}
|
||||
onClick={() => pick(`:${c.name}:`)}
|
||||
>
|
||||
<img
|
||||
src={`/emoji/${c.name}`}
|
||||
alt={c.name}
|
||||
className="emoji-img"
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{EMOJI_CATEGORIES.map((cat) => (
|
||||
<div key={cat.label} className="emoji-section">
|
||||
<div className="emoji-section-label">{cat.label}</div>
|
||||
<div className="emoji-grid">
|
||||
{cat.emoji.map((e) => (
|
||||
<button
|
||||
key={e}
|
||||
className="emoji-btn"
|
||||
onClick={() => pick(e)}
|
||||
>
|
||||
{e}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 &&
|
||||
|
||||
@@ -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(
|
||||
<Modal title="Confirm update" onClose={() => {}}>
|
||||
<p>Review the candidate.</p>
|
||||
</Modal>
|
||||
);
|
||||
expect(html).toContain('role="dialog"');
|
||||
expect(html).toContain('aria-modal="true"');
|
||||
expect(html).toContain('aria-labelledby=');
|
||||
expect(html).toContain('aria-label="Close"');
|
||||
});
|
||||
});
|
||||
@@ -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<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
const focusable = modalRef.current?.querySelector<HTMLElement>(
|
||||
'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<HTMLDivElement>) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
props.onClose();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab' || !modalRef.current) return;
|
||||
const focusable = Array.from(
|
||||
modalRef.current.querySelectorAll<HTMLElement>(
|
||||
'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 (
|
||||
<div className="modal-backdrop" onClick={props.onClose}>
|
||||
<div
|
||||
ref={modalRef}
|
||||
className={'modal' + (props.wide ? ' modal-wide' : '')}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
onKeyDown={onKeyDown}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="modal-head">
|
||||
<h2>{props.title}</h2>
|
||||
<button className="icon-btn" onClick={props.onClose}>
|
||||
<h2 id={titleId}>{props.title}</h2>
|
||||
<button
|
||||
className="icon-btn"
|
||||
aria-label={t('Close')}
|
||||
onClick={props.onClose}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -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 (
|
||||
<div className="player-controls">
|
||||
<div className="watch-controls">
|
||||
<div className="player-control-row">
|
||||
<button
|
||||
className="ctrl ctrl-main"
|
||||
title={t('Play/Pause')}
|
||||
@@ -102,7 +100,7 @@ export function PlayerControls(props: {
|
||||
{props.extra}
|
||||
</div>
|
||||
{(props.showLocal ?? true) && (
|
||||
<div className="watch-controls watch-local">
|
||||
<div className="player-control-row player-local-row">
|
||||
<span className="muted">{t('Vol')}</span>
|
||||
<Bar
|
||||
slim
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { PlayerExtraControl } from '../lib/embedProtocols';
|
||||
import { t } from '../i18n';
|
||||
import { GearIcon } from './icons';
|
||||
|
||||
export function PlayerSettingsMenu(props: {
|
||||
extras: PlayerExtraControl[];
|
||||
rate: number;
|
||||
rateOptions?: number[];
|
||||
canControl: boolean;
|
||||
onExtra: (id: string, value: string) => void;
|
||||
onRate: (rate: number) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const local = props.extras.filter((control) => control.scope === 'local');
|
||||
const room = props.extras.filter(
|
||||
(control) => control.scope === 'synced' && control.id !== 'speed'
|
||||
);
|
||||
const hasRoom = room.length > 0 || !!props.rateOptions?.length;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const close = (event: MouseEvent) => {
|
||||
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
|
||||
};
|
||||
document.addEventListener('mousedown', close);
|
||||
return () => document.removeEventListener('mousedown', close);
|
||||
}, [open]);
|
||||
|
||||
if (local.length === 0 && !hasRoom) return null;
|
||||
const renderControl = (control: PlayerExtraControl) => (
|
||||
<label className="player-setting" key={control.id}>
|
||||
<span>{t(control.label)}</span>
|
||||
<select
|
||||
value={control.current ?? ''}
|
||||
disabled={control.scope === 'synced' && !props.canControl}
|
||||
title={
|
||||
control.scope === 'synced' && !props.canControl
|
||||
? t('Only the host can change this')
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) => props.onExtra(control.id, event.target.value)}
|
||||
>
|
||||
{control.current == null && <option value="">{t('Choose')}</option>}
|
||||
{control.options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{t(option.label)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="player-settings" ref={rootRef}>
|
||||
<button
|
||||
className="ctrl"
|
||||
title={t('Settings')}
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
>
|
||||
<GearIcon />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="player-settings-popover">
|
||||
{local.length > 0 && (
|
||||
<section>
|
||||
<div className="player-settings-heading">{t('Local')}</div>
|
||||
{local.map(renderControl)}
|
||||
</section>
|
||||
)}
|
||||
{hasRoom && (
|
||||
<section>
|
||||
<div className="player-settings-heading">{t('Room')}</div>
|
||||
{props.rateOptions && (
|
||||
<label className="player-setting">
|
||||
<span>{t('Speed')}</span>
|
||||
<select
|
||||
value={String(props.rate)}
|
||||
disabled={!props.canControl}
|
||||
onChange={(event) =>
|
||||
props.onRate(Number(event.target.value))
|
||||
}
|
||||
>
|
||||
{props.rateOptions.map((rate) => (
|
||||
<option key={rate} value={rate}>{rate}×</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{room.map(renderControl)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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: <PlayIcon />, label: 'Now Playing' },
|
||||
{ view: 'dashboard', icon: <PlayIcon />, label: 'Dashboard' },
|
||||
{ view: 'queue', icon: <QueueIcon />, label: 'Queue' },
|
||||
{ view: 'search', icon: <SearchIcon />, label: 'Search' },
|
||||
{ view: 'library', icon: <HeartIcon />, label: 'Library' },
|
||||
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
|
||||
{ view: 'watch', icon: <WatchIcon />, label: 'Watch Together' },
|
||||
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
|
||||
{ view: 'updates', icon: <UpdateIcon />, label: 'Updates' },
|
||||
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
|
||||
];
|
||||
|
||||
@@ -67,18 +68,22 @@ export function Sidebar() {
|
||||
|
||||
<nav className="nav">
|
||||
{NAV.filter(
|
||||
(item) => item.view !== 'server' || isAdmin
|
||||
(item) =>
|
||||
(item.view !== 'server' && item.view !== 'updates') ||
|
||||
isAdmin
|
||||
).map((item) => (
|
||||
<button
|
||||
key={item.view}
|
||||
className={
|
||||
'nav-item' + (s.view === item.view ? ' active' : '')
|
||||
'nav-item' +
|
||||
(s.view === item.view ? ' active' : '')
|
||||
}
|
||||
aria-current={s.view === item.view ? 'page' : undefined}
|
||||
onClick={() => showView(item.view)}
|
||||
>
|
||||
<span className="nav-ico">{item.icon}</span>
|
||||
{t(item.label)}
|
||||
{item.view === 'now' && playing && (
|
||||
{item.view === 'dashboard' && playing && (
|
||||
<span className="live-dot" />
|
||||
)}
|
||||
{item.view === 'queue' && s.queue.length > 0 && (
|
||||
@@ -86,6 +91,22 @@ export function Sidebar() {
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
{s.watchUrl && (
|
||||
<a
|
||||
className="nav-item"
|
||||
href={s.watchUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<span className="nav-ico">
|
||||
<WatchIcon />
|
||||
</span>
|
||||
{t('Watch Together')}
|
||||
<span className="nav-external" aria-hidden="true">
|
||||
↗
|
||||
</span>
|
||||
</a>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-foot">
|
||||
|
||||
@@ -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<DirectoryResponse | null>(null);
|
||||
const [bans, setBans] = useState<Ban[]>([]);
|
||||
const [groups, setGroups] = useState<ServerGroup[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const [nextDirectory, nextBans, nextGroups] = await Promise.all([
|
||||
safeCall<DirectoryResponse>('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<string, unknown>,
|
||||
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 (
|
||||
<div className="ts-admin-client">
|
||||
<div className="ts-admin-client-main">
|
||||
<span
|
||||
className={'ts-presence' + (client.talking ? ' talking' : '')}
|
||||
/>
|
||||
<strong>{client.nickname}</strong>
|
||||
<span className="muted">#{client.id}</span>
|
||||
{client.away && <span className="ts-tag">{t('away')}</span>}
|
||||
{client.muted && <span className="ts-tag">{t('muted')}</span>}
|
||||
{client.deafened && <span className="ts-tag">{t('deafened')}</span>}
|
||||
</div>
|
||||
<div className="ts-admin-private muted">
|
||||
<span>UID: {client.uid || '—'}</span>
|
||||
<span>DB: {client.databaseId || '—'}</span>
|
||||
<span>{t('Groups')}: {client.groups.join(', ') || '—'}</span>
|
||||
</div>
|
||||
<div className="ts-admin-actions">
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const message = await promptDialog({
|
||||
title: tf('Message {0}', client.nickname),
|
||||
message: t('Private message:'),
|
||||
confirmLabel: t('Send'),
|
||||
});
|
||||
if (message)
|
||||
await mutate(
|
||||
'SendTeamSpeakPrivateMessage',
|
||||
{ clientId: client.id, message },
|
||||
t('Message sent')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Message')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const channelId = await promptDialog({
|
||||
title: tf('Move {0}', client.nickname),
|
||||
message: t('Destination channel ID:'),
|
||||
confirmLabel: t('Move'),
|
||||
});
|
||||
if (channelId && /^\d+$/.test(channelId))
|
||||
await mutate(
|
||||
'MoveTeamSpeakClient',
|
||||
{ clientId: client.id, channelId: Number(channelId) },
|
||||
t('Client moved')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Move')}
|
||||
</button>
|
||||
{client.databaseId && (
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const groupId = await promptDialog({
|
||||
title: t('Add server group'),
|
||||
message: groups.length
|
||||
? groups.map((g) => `${g.id}: ${g.name}`).join('\n')
|
||||
: t('Server group ID:'),
|
||||
confirmLabel: t('Add'),
|
||||
});
|
||||
if (groupId && /^\d+$/.test(groupId))
|
||||
await mutate(
|
||||
'AddTeamSpeakServerGroupMember',
|
||||
{
|
||||
groupId: Number(groupId),
|
||||
clientDatabaseId: client.databaseId,
|
||||
},
|
||||
t('Group added')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Add group')}
|
||||
</button>
|
||||
)}
|
||||
{client.databaseId && client.groups.length > 0 && (
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const groupId = await promptDialog({
|
||||
title: t('Remove server group'),
|
||||
message: `${t('Current groups')}: ${client.groups.join(', ')}`,
|
||||
confirmLabel: t('Remove'),
|
||||
});
|
||||
if (groupId && /^\d+$/.test(groupId))
|
||||
await mutate(
|
||||
'RemoveTeamSpeakServerGroupMember',
|
||||
{
|
||||
groupId: Number(groupId),
|
||||
clientDatabaseId: client.databaseId,
|
||||
},
|
||||
t('Group removed')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Remove group')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirmDialog({
|
||||
title: tf('Kick {0}', client.nickname),
|
||||
message: t('Kick this client from the server?'),
|
||||
confirmLabel: t('Kick'),
|
||||
danger: true,
|
||||
})
|
||||
)
|
||||
await mutate(
|
||||
'KickTeamSpeakClient',
|
||||
{ clientId: client.id, fromServer: true },
|
||||
t('Client kicked')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Kick')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
const duration = await promptDialog({
|
||||
title: tf('Ban {0}', client.nickname),
|
||||
message: t('Duration in seconds (0 = permanent):'),
|
||||
confirmLabel: t('Continue'),
|
||||
});
|
||||
if (!duration || !/^\d+$/.test(duration)) return;
|
||||
if (
|
||||
await confirmDialog({
|
||||
title: tf('Ban {0}', client.nickname),
|
||||
message: t('Apply this ban now?'),
|
||||
confirmLabel: t('Ban'),
|
||||
danger: true,
|
||||
})
|
||||
)
|
||||
await mutate(
|
||||
'BanTeamSpeakClient',
|
||||
{
|
||||
clientId: client.id,
|
||||
durationSeconds: Number(duration),
|
||||
},
|
||||
t('Client banned')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Ban')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Channel({ channel, depth = 0 }: { channel: AdminChannel; depth?: number }) {
|
||||
return (
|
||||
<div className="ts-admin-channel" style={{ marginLeft: depth * 16 }}>
|
||||
<div className="ts-admin-channel-head">
|
||||
<strong>{channel.name}</strong>
|
||||
<span className="muted">#{channel.id}</span>
|
||||
<span className="ts-capacity">
|
||||
{channel.currentClients}/{channel.maxClients || '∞'}
|
||||
</span>
|
||||
<button className="btn btn-ghost" onClick={() => createChannel(channel.id)}>
|
||||
{t('Add child')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const name = await promptDialog({
|
||||
title: t('Rename channel'),
|
||||
message: channel.name,
|
||||
confirmLabel: t('Save'),
|
||||
});
|
||||
if (name)
|
||||
await mutate(
|
||||
'EditTeamSpeakChannel',
|
||||
{ channelId: channel.id, name },
|
||||
t('Channel updated')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Edit')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const message = await promptDialog({
|
||||
title: tf('Message {0}', channel.name),
|
||||
message: t('Channel message:'),
|
||||
confirmLabel: t('Send'),
|
||||
});
|
||||
if (message)
|
||||
await mutate(
|
||||
'SendTeamSpeakChannelMessage',
|
||||
{ channelId: channel.id, message },
|
||||
t('Message sent')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Message')}
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-ghost"
|
||||
onClick={async () => {
|
||||
const parentId = await promptDialog({
|
||||
title: t('Reorder channel'),
|
||||
message: t('Parent channel ID (0 = root):'),
|
||||
confirmLabel: t('Continue'),
|
||||
});
|
||||
if (parentId === null || !/^\d+$/.test(parentId)) return;
|
||||
const orderAfterId = await promptDialog({
|
||||
title: t('Reorder channel'),
|
||||
message: t('Previous sibling channel ID (0 = first):'),
|
||||
confirmLabel: t('Move'),
|
||||
});
|
||||
if (orderAfterId === null || !/^\d+$/.test(orderAfterId)) return;
|
||||
await mutate(
|
||||
'ReorderTeamSpeakChannel',
|
||||
{
|
||||
channelId: channel.id,
|
||||
parentId: Number(parentId),
|
||||
orderAfterId: Number(orderAfterId),
|
||||
},
|
||||
t('Channel reordered')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Reorder')}
|
||||
</button>
|
||||
{!channel.default && (
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirmDialog({
|
||||
title: t('Delete channel'),
|
||||
message: tf('Delete {0} and its contents?', channel.name),
|
||||
confirmLabel: t('Delete'),
|
||||
danger: true,
|
||||
})
|
||||
)
|
||||
await mutate(
|
||||
'DeleteTeamSpeakChannel',
|
||||
{ channelId: channel.id, force: true },
|
||||
t('Channel deleted')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Delete')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{channel.clients.map((client) => (
|
||||
<ClientRow key={client.id} client={client} />
|
||||
))}
|
||||
{channel.channels.map((child) => (
|
||||
<Channel key={child.id} channel={child} depth={depth + 1} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-stack">
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<div>
|
||||
<h2>{directory?.server.name || t('TeamSpeak')}</h2>
|
||||
<div className="muted">
|
||||
{directory?.server.connected ? t('Connected') : t('Disconnected')}
|
||||
{' · '}
|
||||
{directory?.server.clientCount || 0}/{directory?.server.maxClients || '∞'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-gap">
|
||||
<button className="btn btn-ghost" onClick={sendServerMessage}>
|
||||
{t('Server message')}
|
||||
</button>
|
||||
<button className="btn btn-ghost" onClick={() => createChannel()}>
|
||||
{t('Create channel')}
|
||||
</button>
|
||||
<button className="btn btn-ghost" disabled={loading} onClick={refresh}>
|
||||
{loading ? t('Loading…') : t('Refresh')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ts-admin-tree">
|
||||
{directory?.channels.length ? (
|
||||
directory.channels.map((channel) => (
|
||||
<Channel key={channel.id} channel={channel} />
|
||||
))
|
||||
) : (
|
||||
<EmptyRow text={t('No TeamSpeak topology available')} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>{t('Bans')}</h2>
|
||||
<span className="muted">{bans.length}</span>
|
||||
</div>
|
||||
<div className="tracklist">
|
||||
{bans.length ? (
|
||||
bans.map((ban) => (
|
||||
<div className="ts-ban-row" key={ban.id}>
|
||||
<div>
|
||||
<strong>{ban.nickname || ban.uid || `#${ban.id}`}</strong>
|
||||
<div className="muted">{ban.reason || t('No reason')}</div>
|
||||
</div>
|
||||
<span className="muted">
|
||||
{ban.durationSeconds ? `${ban.durationSeconds}s` : t('Permanent')}
|
||||
</span>
|
||||
<button
|
||||
className="btn btn-danger-ghost"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirmDialog({
|
||||
title: t('Remove ban'),
|
||||
message: t('Remove this TeamSpeak ban?'),
|
||||
confirmLabel: t('Unban'),
|
||||
danger: true,
|
||||
})
|
||||
)
|
||||
await mutate(
|
||||
'UnbanTeamSpeakClient',
|
||||
{ banId: ban.id },
|
||||
t('Ban removed')
|
||||
);
|
||||
}}
|
||||
>
|
||||
{t('Unban')}
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<EmptyRow text={t('No bans')} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<Track[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
if (w.sourceChoice === 'twitch') {
|
||||
return (
|
||||
<div className="watch-search">
|
||||
<form
|
||||
className="search-row"
|
||||
onSubmit={(e) => {
|
||||
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('');
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={channel}
|
||||
onChange={(e) => setChannel(e.target.value)}
|
||||
placeholder={t(
|
||||
'Twitch channel name or id to queue…'
|
||||
)}
|
||||
autoComplete="off"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<button
|
||||
className="btn btn-accent"
|
||||
type="submit"
|
||||
disabled={disabled}
|
||||
>
|
||||
{t('Add channel')}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="watch-search">
|
||||
<form
|
||||
className="search-row"
|
||||
onSubmit={async (e) => {
|
||||
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');
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={t('Search YouTube to queue…')}
|
||||
autoComplete="off"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<button className="btn btn-accent" type="submit" disabled={disabled}>
|
||||
{t('Search')}
|
||||
</button>
|
||||
</form>
|
||||
{open && results.length > 0 && (
|
||||
<div className="watch-search-results">
|
||||
{results.slice(0, 8).map((tr, i) => (
|
||||
<button
|
||||
key={tr.url || tr.id || i}
|
||||
className="watch-search-item"
|
||||
onClick={() => {
|
||||
send({
|
||||
type: 'watch.queue.add',
|
||||
source: 'youtube',
|
||||
url: tr.url || tr.id,
|
||||
title: tr.title || '',
|
||||
});
|
||||
toast(
|
||||
tf(
|
||||
'Added “{0}” to queue',
|
||||
tr.title || ''
|
||||
)
|
||||
);
|
||||
setOpen(false);
|
||||
setQuery('');
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="track-cover"
|
||||
style={
|
||||
thumbFor(tr)
|
||||
? {
|
||||
background: `url("${thumbFor(tr)}") center/cover`,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<span className="watch-search-title">
|
||||
{tr.title}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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'
|
||||
);
|
||||
|
||||
@@ -4,13 +4,14 @@
|
||||
|
||||
export const ru: Record<string, string> = {
|
||||
// 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<string, string> = {
|
||||
'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<string, string> = {
|
||||
'{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<string, string> = {
|
||||
'Offline': 'Не в сети',
|
||||
'Unsub': 'Отписать',
|
||||
'Unsubscribe {0}?': 'Отписать {0}?',
|
||||
'Unsubscribed {0}': '{0} отписан',
|
||||
'Announcement to all subscribers:': 'Объявление всем подписчикам:',
|
||||
'Announcement sent': 'Объявление отправлено',
|
||||
'Configuration reloaded': 'Конфигурация перезагружена',
|
||||
@@ -210,11 +309,92 @@ export const ru: Record<string, string> = {
|
||||
'Удалить ВСЕ подписки? Это нельзя отменить.',
|
||||
'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<string, string> = {
|
||||
'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<string, string> = {
|
||||
'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': 'Добавить',
|
||||
};
|
||||
@@ -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<AppState>({
|
||||
view: 'now',
|
||||
view: 'dashboard',
|
||||
connection: 'disconnected',
|
||||
identity: null,
|
||||
status: null,
|
||||
@@ -67,10 +72,16 @@ export const appStore = new Store<AppState>({
|
||||
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/<room> 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<AppState['capabilities']>(
|
||||
'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<string, LoadedWebExtension>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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 {
|
||||
|
||||
@@ -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'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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, string>): 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<string, unknown> | 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<string, unknown>)
|
||||
: 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<string, unknown>)
|
||||
: [];
|
||||
return entries.flatMap(([fallback, item]) => {
|
||||
if (item && typeof item === 'object') {
|
||||
const option = item as Record<string, unknown>;
|
||||
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<EmbedAdapter | null> {
|
||||
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<string, PlayerExtraControl>();
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -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/<name> 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 <img> 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;
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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/<room>` 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/<room>`.
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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) {
|
||||
|
||||
@@ -28,5 +28,9 @@ export class Store<T> {
|
||||
}
|
||||
|
||||
export function useStore<T>(store: Store<T>): T {
|
||||
return useSyncExternalStore(store.subscribe, () => store.get());
|
||||
return useSyncExternalStore(
|
||||
store.subscribe,
|
||||
() => store.get(),
|
||||
() => store.get()
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<string, PluginOverridePolicy>;
|
||||
}
|
||||
|
||||
export interface UpdateConfig {
|
||||
enabled: boolean;
|
||||
checkInterval: string;
|
||||
jitter: string;
|
||||
maintenanceWindowUtc: {
|
||||
start: string;
|
||||
duration: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
maxRuntimeDeferral: string;
|
||||
retainHealthyVersions: number;
|
||||
sources: Record<string, UpdateSourceConfig>;
|
||||
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<UpdateComponent, ComponentUpdateStatus>;
|
||||
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<string, unknown> {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
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<string, unknown> {
|
||||
const outer = record(payload);
|
||||
const nested = record(outer[key]);
|
||||
return Object.keys(nested).length ? nested : outer;
|
||||
}
|
||||
|
||||
function sourceFieldsWithoutSecrets(
|
||||
source: Record<string, unknown>
|
||||
): Record<string, unknown> {
|
||||
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<string, UpdateSourceConfig> = {};
|
||||
|
||||
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<string, PluginOverridePolicy> = {};
|
||||
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<string, UpdateSourceConfig> = {};
|
||||
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)));
|
||||
}
|
||||
@@ -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<HTMLElement | null>,
|
||||
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;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,5 @@
|
||||
// Shared loader for the YouTube IFrame API. Both Watch Together and the Now
|
||||
// Playing video preview use it; the script is injected once and callers await
|
||||
// the same readiness promise.
|
||||
// Shared loader for the dashboard's muted YouTube preview. The script is
|
||||
// injected once and callers await the same readiness promise.
|
||||
//
|
||||
// Console-error triage for the YouTube embeds (as seen in production behind
|
||||
// the reverse proxy):
|
||||
|
||||
@@ -5,7 +5,7 @@ import './styles/style.css';
|
||||
// Human-readable fingerprint for deployment/debugging. Vite's filename hash
|
||||
// can legitimately match an older backup when the emitted code becomes
|
||||
// byte-identical after a revert, so expose an explicit release identity too.
|
||||
export const WEB_BUILD_ID = '2026.07.10-player-fix.3';
|
||||
export const WEB_BUILD_ID = '2026.07.13-external-player-fix.1';
|
||||
document.documentElement.dataset.echoionBuild = WEB_BUILD_ID;
|
||||
console.info(`[Echoion] web build ${WEB_BUILD_ID}`);
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
|
||||
/* Inline SVG icons (components/icons.tsx) baseline-align inside text buttons
|
||||
and never shrink in flex rows. */
|
||||
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .room-chip svg, .link svg {
|
||||
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .link svg {
|
||||
vertical-align: -0.125em; flex: none;
|
||||
}
|
||||
|
||||
@@ -186,6 +186,8 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.btn-ghost:hover { color: var(--text-2); background: rgba(255, 255, 255, 0.04); }
|
||||
.btn-danger-ghost { background: transparent; border-color: rgba(255, 92, 92, 0.3); color: var(--red-text); }
|
||||
.btn-danger-ghost:hover { background: rgba(255, 92, 92, 0.1); }
|
||||
.btn-danger { background: #c8434b; color: #fff; }
|
||||
.btn-danger:hover { background: #dc5059; }
|
||||
/* Leave-room button: prominent but not alarming; pushed to the right of the
|
||||
room header so it reads as the primary in-room action. */
|
||||
.btn-leave {
|
||||
@@ -398,145 +400,15 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.split-legend span { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.split-legend b { color: var(--text-2); margin-left: 2px; }
|
||||
|
||||
/* ── Watch Together ───────────────────────────────────────────────────── */
|
||||
.watch-grid { display: grid; grid-template-columns: 1.6fr 1fr; gap: 18px; align-items: start; }
|
||||
.src-yt.active { background: rgba(255, 92, 92, 0.16); border-color: rgba(255, 92, 92, 0.4); color: var(--red-text); }
|
||||
.src-tw.active { background: rgba(169, 112, 255, 0.18); border-color: rgba(169, 112, 255, 0.4); color: #c3a3ff; }
|
||||
.src-direct.active { background: rgba(95, 224, 148, 0.16); border-color: rgba(95, 224, 148, 0.4); color: var(--green-text); }
|
||||
.src-iframe.active { background: rgba(255, 217, 119, 0.16); border-color: rgba(255, 217, 119, 0.4); color: #ffd977; }
|
||||
/* The direct <video> and generic <iframe> fill the player box like the embeds. */
|
||||
#watchPlayer video, #watchPlayer iframe { width: 100%; height: 100%; display: block; background: #000; }
|
||||
.player-box {
|
||||
position: relative; width: 100%; aspect-ratio: 16 / 9;
|
||||
border-radius: 12px; overflow: hidden;
|
||||
background: linear-gradient(135deg, #2a1a4a, #0d0d1f);
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.player-box iframe, .player-box > div:first-child { position: absolute; inset: 0; width: 100%; height: 100%; }
|
||||
|
||||
/* The shell owns the outer spacing; the control bar overlays the video bottom
|
||||
(windowed and fullscreen) so it can fade out when idle. */
|
||||
.player-shell { position: relative; margin-bottom: 14px; }
|
||||
.player-shell .player-box { margin-bottom: 0; }
|
||||
.player-shell.youtube-native .player-overlay { bottom: 42px; }
|
||||
.player-overlay {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; z-index: 5;
|
||||
padding: 34px 14px 8px;
|
||||
background: linear-gradient(to top,
|
||||
rgba(0,0,0,0.82) 0%, rgba(0,0,0,0.45) 46%, rgba(0,0,0,0) 100%);
|
||||
opacity: 1; transition: opacity 0.25s ease;
|
||||
}
|
||||
.player-overlay .watch-controls { margin-bottom: 8px; }
|
||||
.player-overlay .watch-controls:last-child { margin-bottom: 0; }
|
||||
/* Lift muted/mono text for legibility over video. */
|
||||
.player-overlay .muted, .player-overlay .mono { color: #e9e9f2; }
|
||||
|
||||
/* Idle-hidden while playing (the hook removes the class when paused). Hover /
|
||||
keyboard focus (incl. an open quality/speed dropdown) reveals regardless. */
|
||||
.player-shell.controls-hidden .player-overlay { opacity: 0; pointer-events: none; }
|
||||
.player-shell.controls-hidden { cursor: none; }
|
||||
.player-shell.controls-hidden:hover .player-overlay,
|
||||
.player-shell.controls-hidden:focus-within .player-overlay {
|
||||
opacity: 1; pointer-events: auto;
|
||||
}
|
||||
.player-shell.controls-hidden:hover,
|
||||
.player-shell.controls-hidden:focus-within { cursor: auto; }
|
||||
|
||||
/* Fullscreen targets the shell: the player fills the screen and the overlay
|
||||
floats at the bottom (controls stay usable while fullscreen). */
|
||||
.player-shell:fullscreen { background: #000; padding: 0; }
|
||||
.player-shell:fullscreen .player-box {
|
||||
width: 100%; height: 100%; aspect-ratio: auto;
|
||||
border-radius: 0; margin: 0;
|
||||
}
|
||||
.player-shell:fullscreen .player-overlay { padding: 46px 24px 18px; }
|
||||
.player-empty {
|
||||
position: absolute; inset: 0;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
color: var(--faint); font-size: 13.5px;
|
||||
pointer-events: none;
|
||||
text-align: center; padding: 0 24px;
|
||||
}
|
||||
.player-empty[hidden] { display: none; }
|
||||
/* Muted-autoplay affordance overlaid on the player until the user unmutes. */
|
||||
.unmute-btn {
|
||||
position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%);
|
||||
z-index: 6; box-shadow: 0 4px 16px rgba(0,0,0,0.5);
|
||||
}
|
||||
/* Watch lobby (no room joined). */
|
||||
.watch-lobby { max-width: 640px; margin: 0 auto; }
|
||||
.watch-lobby .rooms-list { display: flex; flex-direction: column; gap: 8px; margin: 12px 0; }
|
||||
.watch-lobby .room-chip { justify-content: flex-start; text-align: left; }
|
||||
.room-now { font-style: italic; }
|
||||
.watch-controls { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
|
||||
.watch-controls .ctrl-main { width: 42px; height: 42px; }
|
||||
.watch-local .bar { flex: 0 0 130px; }
|
||||
.watch-local[hidden] { display: none; }
|
||||
.quality-select {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid var(--line);
|
||||
color: var(--text-2);
|
||||
border-radius: 8px;
|
||||
padding: 6px 8px;
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.player-settings { position: relative; }
|
||||
.player-settings-popover {
|
||||
position: absolute; right: 0; bottom: calc(100% + 10px); z-index: 20;
|
||||
width: min(290px, 80vw); padding: 10px;
|
||||
border: 1px solid rgba(255,255,255,0.14); border-radius: 12px;
|
||||
background: rgba(14, 14, 28, 0.96);
|
||||
box-shadow: 0 18px 46px rgba(0,0,0,0.5);
|
||||
backdrop-filter: blur(18px);
|
||||
}
|
||||
.player-settings-popover section + section {
|
||||
margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--line);
|
||||
}
|
||||
.player-settings-heading {
|
||||
margin: 0 2px 7px; color: var(--faint); font-size: 10px;
|
||||
font-weight: 800; letter-spacing: .13em; text-transform: uppercase;
|
||||
}
|
||||
.player-setting {
|
||||
display: grid; grid-template-columns: minmax(80px, 1fr) minmax(110px, 1.35fr);
|
||||
align-items: center; gap: 10px; padding: 5px 2px;
|
||||
color: var(--text-2); font-size: 12.5px;
|
||||
}
|
||||
.player-setting select {
|
||||
min-width: 0; width: 100%; padding: 6px 8px;
|
||||
border: 1px solid var(--line); border-radius: 8px;
|
||||
background: #1b1b31; color: var(--text-2); font: inherit;
|
||||
}
|
||||
/* ── Shared playback controls ─────────────────────────────────────────── */
|
||||
.player-control-row { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
|
||||
.player-control-row .ctrl-main { width: 42px; height: 42px; }
|
||||
.player-local-row .bar { flex: 0 0 130px; }
|
||||
.player-local-row[hidden] { display: none; }
|
||||
.ctrl:disabled, .btn:disabled, .icon-btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.reactions { display: flex; gap: 8px; }
|
||||
.reaction {
|
||||
padding: 8px 14px; border-radius: 10px;
|
||||
border: 1px solid var(--line); background: transparent;
|
||||
cursor: pointer; font-size: 16px;
|
||||
}
|
||||
.reaction:hover { background: rgba(255, 255, 255, 0.06); }
|
||||
.reaction-fly {
|
||||
position: fixed; font-size: 26px; pointer-events: none;
|
||||
animation: fly-up 1.6s ease-out forwards; z-index: 60;
|
||||
}
|
||||
@keyframes fly-up { to { transform: translateY(-120px); opacity: 0; } }
|
||||
|
||||
.chat-card { display: flex; flex-direction: column; }
|
||||
.chat-log {
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
max-height: 320px; overflow-y: auto;
|
||||
margin-bottom: 12px; padding-right: 4px;
|
||||
}
|
||||
.chat-msg { display: flex; gap: 10px; align-items: flex-start; }
|
||||
.chat-body { min-width: 0; }
|
||||
.chat-name { font-weight: 700; font-size: 12.5px; color: var(--accent-2); }
|
||||
.chat-time { color: var(--faint); font-size: 11px; margin-left: 6px; }
|
||||
.chat-text { font-size: 13px; color: var(--text-2); margin-top: 1px; word-break: break-word; }
|
||||
.chat-row { display: flex; gap: 8px; }
|
||||
.chat-row input { flex: 1; }
|
||||
|
||||
/* ── RPC view ─────────────────────────────────────────────────────────── */
|
||||
.rpc-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }
|
||||
@@ -587,7 +459,7 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.drawer-backdrop { display: none; }
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.now-grid, .stats-grid, .watch-grid { grid-template-columns: 1fr; }
|
||||
.now-grid, .stats-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
/* Tablet and below: the sidebar becomes a slide-in drawer. */
|
||||
@@ -620,10 +492,10 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.header h1 { font-size: 20px; }
|
||||
.card { padding: 14px; }
|
||||
.np-title { font-size: 19px; }
|
||||
.search-row, .chat-row, .rooms-create, .row-gap { flex-wrap: wrap; }
|
||||
.search-row input, .chat-row input { min-width: 0; flex: 1 1 160px; }
|
||||
.watch-controls { flex-wrap: wrap; row-gap: 8px; }
|
||||
.watch-local .bar { flex: 1 1 100px; }
|
||||
.search-row, .row-gap { flex-wrap: wrap; }
|
||||
.search-row input { min-width: 0; flex: 1 1 160px; }
|
||||
.player-control-row { flex-wrap: wrap; row-gap: 8px; }
|
||||
.player-local-row .bar { flex: 1 1 100px; }
|
||||
.tabs { overflow-x: auto; }
|
||||
.audit-row { grid-template-columns: 1fr auto; }
|
||||
.audit-time { grid-column: 1 / -1; }
|
||||
@@ -653,9 +525,6 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
|
||||
/* Reactions rendered inside the player box (the vanilla UI appended them
|
||||
to <body> at fixed coordinates). */
|
||||
.reaction-layer { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
|
||||
.reaction-fly-abs { position: absolute; bottom: 50px; }
|
||||
.player-box { position: relative; }
|
||||
|
||||
/* Drop indicator for queue drag-and-drop (item 9). */
|
||||
.drop-indicator {
|
||||
@@ -675,6 +544,104 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.np-video-toggle { align-self: flex-start; margin-bottom: 8px; }
|
||||
.np-video-toggle.on { color: #b28dff; }
|
||||
|
||||
/* Public TeamSpeak directory. Nested channels keep their server order while
|
||||
the guide line makes deep trees readable without turning them into tables. */
|
||||
.ts-directory-card { min-height: 360px; }
|
||||
.ts-server-head { align-items: flex-start; }
|
||||
.ts-server-head h2 { margin-bottom: 2px; }
|
||||
.ts-connected { color: #74e5a2; border-color: rgba(95, 224, 148, 0.3); }
|
||||
.ts-disconnected { color: #ef8a8a; border-color: rgba(239, 99, 99, 0.28); }
|
||||
.ts-summary {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
|
||||
margin: 14px 0 16px;
|
||||
}
|
||||
.ts-summary > div {
|
||||
display: flex; flex-direction: column; gap: 2px;
|
||||
padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
.ts-summary strong { font-size: 18px; }
|
||||
.ts-summary span { color: var(--muted-2); font-size: 11px; }
|
||||
.ts-tree { display: flex; flex-direction: column; gap: 3px; }
|
||||
.ts-channel {
|
||||
position: relative;
|
||||
margin-left: calc(var(--tree-depth, 0) * 18px);
|
||||
}
|
||||
.ts-channel::before {
|
||||
content: ''; position: absolute; left: -10px; top: 0; bottom: 0;
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.ts-channel-row, .ts-client-row {
|
||||
display: flex; align-items: center; min-width: 0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.ts-channel-row { min-height: 34px; padding: 4px 7px; gap: 7px; }
|
||||
.ts-channel-row:hover, .ts-client-row:hover { background: rgba(255, 255, 255, 0.035); }
|
||||
.ts-channel-caret { width: 14px; color: var(--faint); text-align: center; }
|
||||
.ts-channel-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-weight: 650; }
|
||||
.ts-capacity { margin-left: auto; color: var(--faint); font: 11px var(--font-mono); }
|
||||
.ts-tag {
|
||||
padding: 2px 6px; border-radius: 999px; color: var(--muted-2);
|
||||
background: rgba(255, 255, 255, 0.06); font-size: 9px;
|
||||
letter-spacing: 0.04em; text-transform: uppercase;
|
||||
}
|
||||
.ts-client-row { min-height: 30px; margin-left: 26px; padding: 3px 8px; gap: 8px; }
|
||||
.ts-presence { width: 7px; height: 7px; flex: none; border-radius: 50%; background: #687080; }
|
||||
.ts-presence.talking { background: #5fe094; box-shadow: 0 0 0 4px rgba(95, 224, 148, 0.1); }
|
||||
.ts-client-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-size: 13px; }
|
||||
.ts-client-flags { display: flex; gap: 5px; margin-left: auto; }
|
||||
.ts-client-flags span {
|
||||
color: var(--faint); font-size: 9px; text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.nav-external { margin-left: auto; color: var(--faint); }
|
||||
|
||||
/* Guarded administration surface. */
|
||||
.admin-tabs {
|
||||
display: flex; gap: 4px; overflow-x: auto; margin-bottom: 14px;
|
||||
padding: 4px; border: 1px solid var(--line); border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
}
|
||||
.admin-tab {
|
||||
flex: none; border: 0; border-radius: 8px; padding: 8px 13px;
|
||||
background: transparent; color: var(--muted-2); cursor: pointer;
|
||||
font: inherit; font-size: 12px; font-weight: 650;
|
||||
}
|
||||
.admin-tab.active { background: rgba(124, 92, 255, 0.16); color: #c9bfff; }
|
||||
.admin-stack { display: flex; flex-direction: column; gap: 14px; }
|
||||
.admin-action-grid { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.admin-guard { max-width: 620px; }
|
||||
.ts-admin-tree { display: flex; flex-direction: column; gap: 7px; }
|
||||
.ts-admin-channel {
|
||||
border-left: 1px solid rgba(255, 255, 255, 0.08);
|
||||
padding: 7px 0 2px 10px;
|
||||
}
|
||||
.ts-admin-channel-head {
|
||||
display: flex; align-items: center; gap: 7px; flex-wrap: wrap;
|
||||
min-height: 34px;
|
||||
}
|
||||
.ts-admin-channel-head .ts-capacity { margin-left: 0; margin-right: auto; }
|
||||
.ts-admin-client {
|
||||
display: grid; grid-template-columns: minmax(180px, 0.8fr) minmax(250px, 1.2fr) auto;
|
||||
gap: 10px; align-items: center; margin: 5px 0 5px 20px; padding: 8px 10px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.055); border-radius: 9px;
|
||||
background: rgba(255, 255, 255, 0.018);
|
||||
}
|
||||
.ts-admin-client-main, .ts-admin-private, .ts-admin-actions {
|
||||
display: flex; align-items: center; gap: 7px; min-width: 0; flex-wrap: wrap;
|
||||
}
|
||||
.ts-admin-private { font: 10px var(--font-mono); }
|
||||
.ts-admin-actions { justify-content: flex-end; }
|
||||
.ts-admin-actions .btn, .ts-admin-channel-head .btn { padding: 5px 8px; font-size: 10px; }
|
||||
.ts-ban-row {
|
||||
display: grid; grid-template-columns: 1fr auto auto; gap: 12px;
|
||||
align-items: center; padding: 9px 0; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.ts-admin-client { grid-template-columns: 1fr; }
|
||||
.ts-admin-actions { justify-content: flex-start; }
|
||||
}
|
||||
|
||||
/* Announce composer modal (item 14). */
|
||||
.modal-backdrop {
|
||||
position: fixed; inset: 0; z-index: 100; display: flex;
|
||||
@@ -721,66 +688,240 @@ select:focus:not(:focus-visible) { outline: none; }
|
||||
.ts-markup details { margin: 0.4em 0; }
|
||||
.ts-markup summary { cursor: pointer; font-weight: 600; }
|
||||
|
||||
/* Watch Together room switcher (item 3). */
|
||||
.pill-room { cursor: pointer; border: none; font: inherit; }
|
||||
.rooms-panel {
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
padding: 12px; margin: 4px 0 2px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
/* ── Updates control plane ──────────────────────────────────────────────
|
||||
The update surface keeps the dashboard's violet language, but uses a
|
||||
denser instrument-panel rhythm: version rails, status lamps, and a faint
|
||||
technical grid make trust and activation state scannable at a glance. */
|
||||
.updates-view {
|
||||
position: relative;
|
||||
}
|
||||
.rooms-list { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.room-chip {
|
||||
background: rgba(255, 255, 255, 0.06); border: 1px solid transparent;
|
||||
border-radius: 8px; padding: 5px 10px; cursor: pointer;
|
||||
color: inherit; font: inherit; font-size: 13px;
|
||||
.updates-view::before {
|
||||
content: ''; position: absolute; inset: -8px 0 auto; height: 250px;
|
||||
pointer-events: none; opacity: .18;
|
||||
background-image:
|
||||
linear-gradient(rgba(124, 92, 255, .12) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(124, 92, 255, .12) 1px, transparent 1px);
|
||||
background-size: 28px 28px;
|
||||
mask-image: linear-gradient(to bottom, #000, transparent);
|
||||
}
|
||||
.room-chip.active { border-color: #7c5cff; color: #b28dff; }
|
||||
.rooms-create { display: flex; gap: 8px; }
|
||||
.rooms-create input { flex: 1; }
|
||||
.update-command-bar {
|
||||
position: relative; display: flex; align-items: center;
|
||||
justify-content: space-between; gap: 16px; margin-bottom: 16px;
|
||||
padding: 14px 16px; border: 1px solid rgba(124, 92, 255, .23);
|
||||
border-radius: 13px;
|
||||
background: linear-gradient(110deg, rgba(124, 92, 255, .11), rgba(255, 255, 255, .025) 58%);
|
||||
}
|
||||
.update-command-state { display: flex; align-items: center; gap: 12px; min-width: 0; }
|
||||
.update-command-state p { margin-top: 2px; font-size: 12px; }
|
||||
.update-beacon {
|
||||
width: 11px; height: 11px; border-radius: 50%; flex: none;
|
||||
background: var(--faint); box-shadow: 0 0 0 6px rgba(106, 106, 120, .1);
|
||||
}
|
||||
.update-beacon.active {
|
||||
background: var(--green);
|
||||
box-shadow: 0 0 0 6px rgba(63, 208, 122, .1), 0 0 18px rgba(63, 208, 122, .4);
|
||||
}
|
||||
.update-live-region { min-height: 18px; color: var(--muted-2); font-size: 12px; }
|
||||
.update-component-grid {
|
||||
position: relative; display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px; margin: 2px 0 18px;
|
||||
}
|
||||
.update-component-card {
|
||||
position: relative; overflow: hidden; display: flex; flex-direction: column;
|
||||
min-height: 260px; padding: 16px; border: 1px solid var(--line);
|
||||
border-radius: var(--radius); background: rgba(14, 14, 21, .93);
|
||||
}
|
||||
.update-component-card::after {
|
||||
content: ''; position: absolute; right: -32px; top: -32px;
|
||||
width: 110px; height: 110px; border-radius: 50%;
|
||||
background: rgba(124, 92, 255, .08); filter: blur(4px);
|
||||
}
|
||||
.update-component-head {
|
||||
position: relative; z-index: 1; display: grid;
|
||||
grid-template-columns: auto 1fr auto; align-items: center; gap: 10px;
|
||||
}
|
||||
.update-component-head h2 { font-size: 15px; }
|
||||
.update-component-head p { margin-top: 2px; font-size: 10px; }
|
||||
.update-component-mark {
|
||||
width: 35px; height: 35px; border-radius: 10px;
|
||||
display: grid; place-items: center; font: 700 13px var(--font-mono);
|
||||
color: #d7d0ff; border: 1px solid rgba(124, 92, 255, .28);
|
||||
background: rgba(124, 92, 255, .13);
|
||||
}
|
||||
.update-component-mark.core { color: #8fe8b4; border-color: rgba(63, 208, 122, .25); background: rgba(63, 208, 122, .1); }
|
||||
.update-component-mark.plugins { color: #ffe08d; border-color: rgba(255, 207, 74, .25); background: rgba(255, 207, 74, .1); }
|
||||
.update-version-line {
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
|
||||
align-items: center; gap: 10px; margin: 20px 0 12px;
|
||||
}
|
||||
.update-version-line > div { min-width: 0; }
|
||||
.update-version-line span {
|
||||
display: block; color: var(--faint); font-size: 9px; font-weight: 700;
|
||||
letter-spacing: .09em; text-transform: uppercase;
|
||||
}
|
||||
.update-version-line strong {
|
||||
display: block; overflow: hidden; margin-top: 3px;
|
||||
font: 700 14px var(--font-mono); text-overflow: ellipsis;
|
||||
}
|
||||
.update-version-arrow { color: var(--accent-text) !important; font-size: 16px !important; }
|
||||
.update-badges { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||
.update-badge {
|
||||
display: inline-flex; align-items: center; width: fit-content;
|
||||
padding: 3px 7px; border-radius: 999px;
|
||||
font: 700 9px var(--font-mono); letter-spacing: .03em;
|
||||
text-transform: uppercase; white-space: nowrap;
|
||||
color: var(--muted); border: 1px solid rgba(255, 255, 255, .08);
|
||||
background: rgba(255, 255, 255, .04);
|
||||
}
|
||||
.update-badge.success { color: var(--green-text); border-color: rgba(63, 208, 122, .22); background: rgba(63, 208, 122, .09); }
|
||||
.update-badge.warning { color: var(--yellow-text); border-color: rgba(255, 207, 74, .22); background: rgba(255, 207, 74, .09); }
|
||||
.update-badge.danger { color: var(--red-text); border-color: rgba(255, 92, 92, .24); background: rgba(255, 92, 92, .09); }
|
||||
.update-card-message { margin-top: 10px; color: var(--muted-2); font-size: 12px; line-height: 1.45; }
|
||||
.update-card-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: auto; padding-top: 18px; }
|
||||
.update-card-actions .btn { padding: 7px 10px; font-size: 11px; }
|
||||
.updates-two-column {
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 18px; align-items: start;
|
||||
}
|
||||
.update-plugin-list { display: flex; flex-direction: column; }
|
||||
.update-plugin-row {
|
||||
display: grid; grid-template-columns: minmax(120px, 1.2fr) auto minmax(105px, .7fr) auto;
|
||||
align-items: center; gap: 10px; padding: 9px 2px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-plugin-row:last-child { border-bottom: 0; }
|
||||
.update-plugin-main { display: flex; flex-direction: column; min-width: 0; }
|
||||
.update-plugin-main strong, .update-plugin-main span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.update-plugin-main span { font-size: 10px; margin-top: 2px; }
|
||||
.update-plugin-version { color: var(--muted); font-size: 11px; }
|
||||
.update-plugin-actions { display: flex; gap: 5px; }
|
||||
.update-plugin-actions .btn { padding: 5px 8px; font-size: 10px; }
|
||||
.update-history-scroll { max-height: 350px; overflow: auto; }
|
||||
.update-history-table { width: 100%; border-collapse: collapse; font-size: 11px; }
|
||||
.update-history-table th {
|
||||
position: sticky; top: 0; z-index: 1; padding: 7px 8px;
|
||||
text-align: left; color: var(--faint); background: #111119;
|
||||
font-size: 9px; letter-spacing: .08em; text-transform: uppercase;
|
||||
}
|
||||
.update-history-table td { padding: 8px; border-bottom: 1px solid var(--line); vertical-align: middle; }
|
||||
.update-history-table td:first-child { white-space: nowrap; color: var(--muted-2); }
|
||||
.update-history-table td small { display: block; margin-top: 2px; color: var(--faint); font: 9px var(--font-mono); }
|
||||
.update-config { margin-top: 8px; }
|
||||
.update-config-title, .update-sources-head {
|
||||
display: flex; align-items: flex-end; justify-content: space-between;
|
||||
gap: 16px; margin: 27px 0 13px;
|
||||
}
|
||||
.update-config-title h2 { font-size: 22px; margin: 2px 0 3px; }
|
||||
.update-kicker {
|
||||
color: var(--accent-text); font: 700 9px var(--font-mono);
|
||||
letter-spacing: .16em;
|
||||
}
|
||||
.update-automation-card { border-color: rgba(124, 92, 255, .18); }
|
||||
.update-automation-grid {
|
||||
display: grid; grid-template-columns: repeat(6, minmax(100px, 1fr));
|
||||
gap: 12px; align-items: end;
|
||||
}
|
||||
.update-master-switch { grid-column: span 2; align-self: center; }
|
||||
.update-field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }
|
||||
.update-field > span {
|
||||
color: var(--muted-2); font-size: 10px; font-weight: 700;
|
||||
letter-spacing: .035em;
|
||||
}
|
||||
.update-field input, .update-field select, .update-override-row input,
|
||||
.update-override-row select {
|
||||
width: 100%; min-width: 0; color: var(--text);
|
||||
background: rgba(255, 255, 255, .045); border: 1px solid var(--line);
|
||||
border-radius: 9px; padding: 9px 10px; outline: none; font: inherit;
|
||||
font-size: 12px;
|
||||
}
|
||||
.update-field input:focus, .update-field select:focus,
|
||||
.update-override-row input:focus, .update-override-row select:focus {
|
||||
border-color: rgba(124, 92, 255, .48);
|
||||
}
|
||||
.update-field select option, .update-override-row select option { color: #111; }
|
||||
.update-field small { color: var(--faint); font-size: 10px; line-height: 1.35; }
|
||||
.update-switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; color: var(--muted); font-size: 11px; }
|
||||
.update-switch input { width: 15px; height: 15px; accent-color: var(--accent); }
|
||||
.update-policy-list { display: flex; flex-direction: column; }
|
||||
.update-policy-row {
|
||||
display: grid; grid-template-columns: minmax(150px, .8fr) minmax(130px, .8fr) minmax(130px, 1fr) auto;
|
||||
align-items: end; gap: 12px; padding: 12px 2px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-policy-row:last-child { border-bottom: 0; }
|
||||
.update-policy-name { display: flex; flex-direction: column; gap: 6px; align-self: center; }
|
||||
.update-auto-switch { min-height: 36px; align-self: end; }
|
||||
.update-managed-only { margin-top: 12px; }
|
||||
.update-override-list { display: flex; flex-direction: column; }
|
||||
.update-override-row {
|
||||
display: grid; grid-template-columns: minmax(140px, 1fr) minmax(120px, .7fr) minmax(120px, .8fr) auto auto;
|
||||
align-items: center; gap: 9px; padding: 8px 0; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.update-override-id { overflow: hidden; text-overflow: ellipsis; }
|
||||
.update-empty-inline { padding: 10px 2px; font-size: 12px; }
|
||||
.update-source-list { display: flex; flex-direction: column; gap: 13px; }
|
||||
.update-source-card {
|
||||
min-width: 0; padding: 16px; border: 1px solid var(--line);
|
||||
border-radius: var(--radius); background: var(--panel);
|
||||
}
|
||||
.update-source-card legend {
|
||||
display: flex; align-items: center; gap: 8px; padding: 0 8px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.update-source-grid {
|
||||
display: grid; grid-template-columns: minmax(240px, 1.4fr) minmax(220px, 1fr) auto;
|
||||
align-items: start; gap: 12px; margin-bottom: 17px;
|
||||
}
|
||||
.update-unsigned-switch { min-height: 55px; align-self: end; color: var(--yellow-text); }
|
||||
.update-key-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
|
||||
.update-key-head p { margin-top: 2px; font-size: 11px; }
|
||||
.update-key-list { display: flex; flex-direction: column; }
|
||||
.update-key-row {
|
||||
display: grid; grid-template-columns: minmax(130px, .45fr) minmax(220px, 1.55fr) auto;
|
||||
align-items: end; gap: 8px; padding: 7px 0;
|
||||
}
|
||||
.update-key-remove { margin-bottom: 1px; }
|
||||
.update-source-foot { display: flex; justify-content: flex-end; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line); }
|
||||
|
||||
/* Watch search (item 20). */
|
||||
.watch-search { position: relative; margin-bottom: 8px; }
|
||||
.watch-search-results {
|
||||
position: absolute; z-index: 30; left: 0; right: 0; top: 100%;
|
||||
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 10px; margin-top: 4px; max-height: 320px; overflow: auto;
|
||||
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
|
||||
@media (max-width: 1200px) {
|
||||
.update-component-grid { grid-template-columns: 1fr; }
|
||||
.update-component-card { min-height: 0; }
|
||||
.update-automation-grid { grid-template-columns: repeat(3, minmax(120px, 1fr)); }
|
||||
.update-master-switch { grid-column: span 1; }
|
||||
}
|
||||
.watch-search-item {
|
||||
display: flex; align-items: center; gap: 10px; width: 100%;
|
||||
padding: 6px 10px; background: transparent; border: none; cursor: pointer;
|
||||
color: inherit; text-align: left; font: inherit;
|
||||
}
|
||||
.watch-search-item:hover { background: rgba(255, 255, 255, 0.06); }
|
||||
.watch-search-item .track-cover { width: 48px; height: 27px; flex: none; border-radius: 4px; }
|
||||
.watch-search-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
/* Emoji picker + custom emojis (item 16). */
|
||||
.emoji-anchor { position: relative; display: inline-flex; }
|
||||
.emoji-trigger { padding: 6px 8px; }
|
||||
.emoji-picker {
|
||||
position: absolute; bottom: 100%; left: 0; z-index: 40; width: 300px;
|
||||
max-height: 320px; overflow-y: auto; margin-bottom: 6px; padding: 8px;
|
||||
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
border-radius: 12px; box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
|
||||
@media (max-width: 1000px) {
|
||||
.updates-two-column { grid-template-columns: 1fr; }
|
||||
.update-source-grid { grid-template-columns: 1fr 1fr; }
|
||||
.update-unsigned-switch { grid-column: 1 / -1; min-height: auto; }
|
||||
}
|
||||
.emoji-section { margin-bottom: 8px; }
|
||||
.emoji-section-label {
|
||||
font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase;
|
||||
color: #8a8a98; margin: 4px 2px;
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.update-command-bar, .update-config-title, .update-sources-head {
|
||||
align-items: stretch; flex-direction: column;
|
||||
}
|
||||
.update-command-bar .row-gap, .update-config-title .row-gap { justify-content: flex-end; }
|
||||
.update-automation-grid, .update-source-grid { grid-template-columns: 1fr; }
|
||||
.update-policy-row { grid-template-columns: 1fr 1fr; }
|
||||
.update-policy-name { grid-column: 1 / -1; }
|
||||
.update-override-row { grid-template-columns: 1fr 1fr; }
|
||||
.update-override-id { grid-column: 1 / -1; }
|
||||
.update-key-row { grid-template-columns: 1fr; padding: 11px 0; }
|
||||
.update-key-remove { justify-self: start; }
|
||||
.update-plugin-row { grid-template-columns: minmax(0, 1fr) auto; }
|
||||
.update-plugin-version { grid-column: 1; }
|
||||
.update-plugin-actions { grid-column: 2; grid-row: 2; }
|
||||
}
|
||||
.emoji-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; }
|
||||
.emoji-btn {
|
||||
background: transparent; border: none; cursor: pointer; font-size: 20px;
|
||||
line-height: 1; padding: 4px; border-radius: 6px;
|
||||
|
||||
@media (max-width: 460px) {
|
||||
.update-policy-row, .update-override-row { grid-template-columns: 1fr; }
|
||||
.update-policy-name, .update-override-id { grid-column: auto; }
|
||||
.update-version-line { grid-template-columns: 1fr; }
|
||||
.update-version-arrow { transform: rotate(90deg); width: fit-content; }
|
||||
.update-history-table th:nth-child(3), .update-history-table td:nth-child(3) { display: none; }
|
||||
}
|
||||
.emoji-btn:hover { background: rgba(255, 255, 255, 0.08); }
|
||||
.emoji-img { width: 20px; height: 20px; vertical-align: middle; object-fit: contain; }
|
||||
.emoji-img-lg { width: 30px; height: 30px; object-fit: contain; }
|
||||
.emoji-manage-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-bottom: 12px; }
|
||||
.emoji-manage-grid { display: flex; flex-wrap: wrap; gap: 12px; }
|
||||
.emoji-manage-item {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
background: rgba(255, 255, 255, 0.05); border-radius: 8px; padding: 6px 10px;
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.update-beacon { box-shadow: none; }
|
||||
}
|
||||
+123
-12
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, type CSSProperties } from 'react';
|
||||
import { appStore, loadFavorites, safeCall, showView, toast } from '../lib/app';
|
||||
import { useStore } from '../lib/store';
|
||||
import { PlayerControls } from '../components/PlayerControls';
|
||||
@@ -15,8 +15,9 @@ import {
|
||||
SkipPrevIcon,
|
||||
} from '../components/icons';
|
||||
import { t, tf } from '../i18n';
|
||||
import type { PublicDashboardChannel } from '../lib/types';
|
||||
|
||||
const VIDEO_PREF_KEY = 'echoion.npVideo';
|
||||
const DASHBOARD_VIDEO_PREF_KEY = 'echoion.npVideo';
|
||||
|
||||
async function togglePlay() {
|
||||
const st = appStore.get().status || {};
|
||||
@@ -24,10 +25,62 @@ async function togglePlay() {
|
||||
else await safeCall('Resume');
|
||||
}
|
||||
|
||||
export function NowView() {
|
||||
function ChannelNode({
|
||||
channel,
|
||||
depth = 0,
|
||||
}: {
|
||||
channel: PublicDashboardChannel;
|
||||
depth?: number;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className="ts-channel"
|
||||
style={{ '--tree-depth': depth } as CSSProperties}
|
||||
>
|
||||
<div className="ts-channel-row">
|
||||
<span className="ts-channel-caret" aria-hidden="true">
|
||||
{channel.channels.length || channel.clients.length ? '⌄' : '·'}
|
||||
</span>
|
||||
<span className="ts-channel-name">{channel.name}</span>
|
||||
{channel.default && <span className="ts-tag">{t('default')}</span>}
|
||||
{channel.password && (
|
||||
<span className="ts-tag" title={t('Password protected')}>
|
||||
{t('locked')}
|
||||
</span>
|
||||
)}
|
||||
<span className="ts-capacity">
|
||||
{channel.currentClients}/
|
||||
{channel.maxClients > 0 ? channel.maxClients : '∞'}
|
||||
</span>
|
||||
</div>
|
||||
{channel.clients.map((client, index) => (
|
||||
<div
|
||||
className="ts-client-row"
|
||||
key={`${client.nickname}-${index}`}
|
||||
>
|
||||
<span
|
||||
className={'ts-presence' + (client.talking ? ' talking' : '')}
|
||||
aria-label={client.talking ? t('Talking') : t('Online')}
|
||||
/>
|
||||
<span className="ts-client-name">{client.nickname}</span>
|
||||
<div className="ts-client-flags">
|
||||
{client.away && <span title={t('Away')}>away</span>}
|
||||
{client.muted && <span title={t('Muted')}>mic off</span>}
|
||||
{client.deafened && <span title={t('Deafened')}>sound off</span>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{channel.channels.map((child) => (
|
||||
<ChannelNode key={child.id} channel={child} depth={depth + 1} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DashboardView() {
|
||||
const s = useStore(appStore);
|
||||
const [videoOn, setVideoOn] = useState(
|
||||
localStorage.getItem(VIDEO_PREF_KEY) === '1'
|
||||
localStorage.getItem(DASHBOARD_VIDEO_PREF_KEY) === '1'
|
||||
);
|
||||
const track = s.current;
|
||||
const videoId = youtubeIdFromUrl(track?.url);
|
||||
@@ -50,7 +103,7 @@ export function NowView() {
|
||||
const needed = st.skipVotesNeeded || 0;
|
||||
|
||||
return (
|
||||
<section className="view" id="view-now">
|
||||
<section className="view" id="view-dashboard">
|
||||
<div className="now-grid">
|
||||
<div className="card np-card">
|
||||
{showVideo && videoId ? (
|
||||
@@ -72,7 +125,7 @@ export function NowView() {
|
||||
const next = !videoOn;
|
||||
setVideoOn(next);
|
||||
localStorage.setItem(
|
||||
VIDEO_PREF_KEY,
|
||||
DASHBOARD_VIDEO_PREF_KEY,
|
||||
next ? '1' : '0'
|
||||
);
|
||||
}}
|
||||
@@ -94,7 +147,7 @@ export function NowView() {
|
||||
playing={playing}
|
||||
positionMs={s.positionMs}
|
||||
durationMs={durationMs}
|
||||
canControl
|
||||
canControl={!!s.identity}
|
||||
volumePct={volumePct}
|
||||
onTogglePlay={togglePlay}
|
||||
onSeekMs={(ms) =>
|
||||
@@ -108,7 +161,7 @@ export function NowView() {
|
||||
? () => safeCall('Skip', { count: 1 })
|
||||
: undefined
|
||||
}
|
||||
extra={
|
||||
extra={s.identity ? (
|
||||
<>
|
||||
<button
|
||||
className={
|
||||
@@ -210,8 +263,8 @@ export function NowView() {
|
||||
</span>
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
extraLocal={
|
||||
) : undefined}
|
||||
extraLocal={s.identity ? (
|
||||
<label className="toggle-row">
|
||||
<span className="muted">{t('Radio')}</span>
|
||||
<button
|
||||
@@ -251,11 +304,66 @@ export function NowView() {
|
||||
<span className="knob" />
|
||||
</button>
|
||||
</label>
|
||||
}
|
||||
) : undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col">
|
||||
<div className="card ts-directory-card">
|
||||
<div className="card-head ts-server-head">
|
||||
<div>
|
||||
<h2>
|
||||
{s.publicDashboard?.server.name ||
|
||||
t('TeamSpeak server')}
|
||||
</h2>
|
||||
<span className="muted">
|
||||
{t('Complete channel directory')}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
className={
|
||||
'pill ' +
|
||||
(s.publicDashboard?.server.connected
|
||||
? 'ts-connected'
|
||||
: 'ts-disconnected')
|
||||
}
|
||||
>
|
||||
{s.publicDashboard?.server.connected
|
||||
? t('Connected')
|
||||
: t('Disconnected')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="ts-summary">
|
||||
<div>
|
||||
<strong>
|
||||
{s.publicDashboard?.server.clientCount || 0}
|
||||
</strong>
|
||||
<span>{t('clients')}</span>
|
||||
</div>
|
||||
<div>
|
||||
<strong>
|
||||
{s.publicDashboard?.server.channelCount || 0}
|
||||
</strong>
|
||||
<span>{t('channels')}</span>
|
||||
</div>
|
||||
<div>
|
||||
<strong>
|
||||
{s.publicDashboard?.server.maxClients || '∞'}
|
||||
</strong>
|
||||
<span>{t('capacity')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ts-tree">
|
||||
{s.publicDashboard?.channels.length ? (
|
||||
s.publicDashboard.channels.map((channel) => (
|
||||
<ChannelNode key={channel.id} channel={channel} />
|
||||
))
|
||||
) : (
|
||||
<EmptyRow text={t('No channels available')} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{s.identity && (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h2>{t('Up Next')}</h2>
|
||||
@@ -286,7 +394,9 @@ export function NowView() {
|
||||
})()}
|
||||
</div>
|
||||
</div>
|
||||
<LyricsPanel />
|
||||
)}
|
||||
{s.identity && <LyricsPanel />}
|
||||
{s.identity && (
|
||||
<div className="card">
|
||||
<div className="card-head">
|
||||
<h3>{t('Listening now')}</h3>
|
||||
@@ -311,6 +421,7 @@ export function NowView() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user