diff --git a/.github/actions/brain-deb-check/action.yml b/.github/actions/brain-deb-check/action.yml new file mode 100644 index 00000000..efd08eed --- /dev/null +++ b/.github/actions/brain-deb-check/action.yml @@ -0,0 +1,98 @@ +name: brain-deb-check +description: >- + Install a teaport-brain .deb and check the installed package: the self-check (as the runner + user and as root), dpkg -V and file ownership, and that Depends covers every system library + the venv links against. ci.yml runs it on its own build of every commit; release-deb.yml on + the release .deb, after its sha256 is printed. +inputs: + deb: + description: the .deb, relative to the workspace + required: true +runs: + using: composite + steps: + - name: Install it + shell: bash + env: + DEB: ${{ inputs.deb }} + run: sudo apt-get install -y "./$DEB" + - name: Self-check the installed package + # From /, isolated (-I), as the runner user and then as root. Root is the strict + # case: a root python writes a __pycache__ wherever a .pyc is missing or stale, + # which the next step would see as a file the package does not own, or as a + # changed one. The run user on the box cannot write the tree at all, so a stale + # .pyc there would cost a recompile on every start instead. + shell: bash + run: | + cd / + /opt/teaport/brain/bin/python -I -m teaport_brain.selfcheck + sudo /opt/teaport/brain/bin/python -I -m teaport_brain.selfcheck + /opt/teaport/brain/bin/teaport-brain --help >/dev/null + test -x /usr/bin/teaport && bash -n /usr/bin/teaport + # compile(), not py_compile: that would write a __pycache__ beside the helper. + for p in /usr/lib/teaport/config_apply.py /usr/lib/teaport/update_apply.py /usr/lib/teaport/wifi_apply.py /usr/lib/teaport/login_apply.py /usr/lib/teaport/license_accept.py /usr/lib/teaport/license_link.py /usr/lib/teaport/manifest_sig.py /usr/lib/teaport/license_key.py; do + /usr/bin/python3 -I -c 'import sys; p = sys.argv[1]; compile(open(p).read(), p, "exec")' "$p" + done + # The update's unit, as systemd reads it (it is static: nothing enables it). + systemd-analyze verify /usr/lib/systemd/system/teaport-update.service + [ "$(systemctl show -p UnitFileState --value teaport-update.service)" = static ] + # The owner's license retry (#465): enabled by the package's own link. + systemd-analyze verify /usr/lib/systemd/system/teaport-license-owner.service /usr/lib/systemd/system/teaport-license-owner.timer + [ "$(readlink /usr/lib/systemd/system/timers.target.wants/teaport-license-owner.timer)" = /usr/lib/systemd/system/teaport-license-owner.timer ] + # The engine license key's renewal (#474), enabled the same way. + systemd-analyze verify /usr/lib/systemd/system/teaport-license-renew.service /usr/lib/systemd/system/teaport-license-renew.timer + [ "$(readlink /usr/lib/systemd/system/timers.target.wants/teaport-license-renew.timer)" = /usr/lib/systemd/system/teaport-license-renew.timer ] + # The engine's license files are never the package's (an upgrade or a purge would + # replace or remove a box's key), and nothing of the engine's issuer ships here. + if dpkg -L teaport-brain | grep -E '^/etc/teaport/license|/tools/license(/|$)|/license_keys(/|$)'; then + echo "teaport-brain ships an engine license file or the issuer's tools"; exit 1 + fi + if dpkg-query --control-show teaport-brain conffiles 2>/dev/null | grep -E '/etc/teaport/license'; then + echo "teaport-brain lists an engine license file as a conffile"; exit 1 + fi + - name: dpkg -V is clean, and the package owns every file under its root + shell: bash + run: | + out="$(dpkg -V teaport-brain)" + [ -z "$out" ] || { printf '%s\n' "$out"; echo "dpkg -V: files changed after install"; exit 1; } + stray="$(comm -13 <(dpkg -L teaport-brain | sort -u) <(find /opt/teaport/brain | sort -u))" + [ -z "$stray" ] || { printf '%s\n' "$stray" | head -50; echo "files under /opt/teaport/brain that the package does not own (written at run time?)"; exit 1; } + echo "dpkg -V clean; $(dpkg -L teaport-brain | wc -l) paths owned" + - name: Shared libraries (what Depends must cover) + # Every ELF object in the venv, through ldd. Anything unresolved fails the job. + # Anything resolved OUTSIDE the venv is a system library the package relies on: + # listed with the Debian package that ships it and one .so that needs it, and + # every such package must be named in the .deb's Depends: (what dpkg-shlibdeps + # would have derived, for a package nfpm builds without it). + shell: bash + run: | + find /opt/teaport/brain -type f \( -name '*.so' -o -name '*.so.*' \) > "$RUNNER_TEMP/elfs" + echo "$(wc -l < "$RUNNER_TEMP/elfs") shared objects in the venv" + missing=0; : > "$RUNNER_TEMP/sys" + while IFS= read -r f; do + out="$(ldd "$f" 2>&1 || true)" + if grep -q 'not found' <<<"$out"; then echo "UNRESOLVED in $f:"; grep 'not found' <<<"$out"; missing=1; fi + awk -v so="${f#/opt/teaport/brain/lib/python3.12/site-packages/}" \ + '/=> \//{print $3, so} /^\t\/[^ ]+ \(/{print $1, so}' <<<"$out" \ + | grep -v '^/opt/teaport/brain/' >> "$RUNNER_TEMP/sys" || true + done < "$RUNNER_TEMP/elfs" + # dpkg -S by the path ldd printed, then by its resolved one: since the /usr + # merge a library can be registered under either spelling. Diversion notes + # (the dynamic loader has one) are not owners. + owner() { { dpkg -S "$1"; dpkg -S "$(readlink -f "$1")"; } 2>/dev/null | grep -v '^diversion by' | head -1 | cut -d: -f1; } + echo "system libraries the venv links against:" + : > "$RUNNER_TEMP/pkgs" + while read -r lib so; do + pkg="$(owner "$lib" || true)" + printf ' %-44s %-12s e.g. %s\n' "$lib" "${pkg:-?}" "$so" + echo "${pkg:-?}" >> "$RUNNER_TEMP/pkgs" + done < <(sort -u -k1,1 "$RUNNER_TEMP/sys") + echo "packages: $(sort -u "$RUNNER_TEMP/pkgs" | paste -sd' ')" + depends="$(dpkg-query -W -f='${Depends}' teaport-brain)" + echo "Depends: $depends" + # Package names only (version constraints dropped), matched as whole lines. + sed 's/ *([^)]*)//g; s/, */\n/g' <<<"$depends" > "$RUNNER_TEMP/depends" + for pkg in $(sort -u "$RUNNER_TEMP/pkgs"); do + if ! grep -qxF "$pkg" "$RUNNER_TEMP/depends"; then echo "not in Depends: $pkg"; missing=1; fi + done + [ "$missing" = 0 ] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 21b61135..a3c59f14 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,8 +3,9 @@ name: ci on: push: branches: [main] - # brain-v: brain-deb builds the release package. It is uploaded as a run - # artifact like any other build; publishing it is a separate, manual step. + # brain-v: brain-deb builds the tag here too, and brain-deb-check installs and + # checks that build. The release .deb itself (published, and signed for) is + # release-deb.yml's, a workflow of the tag alone. tags: ["brain-v*"] pull_request: @@ -67,8 +68,8 @@ jobs: run: | pip install uv==0.9.24 uv sync --locked --no-editable --project brain - - name: Brain self-check (what the brain-deb job runs against the built package) - # The same gate the brain-deb job applies to the built package: import both + - name: Brain self-check (what the brain-deb-check job runs against the built package) + # The same gate the brain-deb-check job applies to the built package: import both # front-ends and push audio through Silero VAD + Smart Turn v3, the compiled # extensions (onnxruntime, loudness) a numpy major would break. brain-deb builds # on the arm runner only; this step runs on both legs, so it is also what checks @@ -111,8 +112,10 @@ jobs: group: ci-brain-deb-${{ github.ref }} cancel-in-progress: false timeout-minutes: 30 + # This job only builds and uploads; the self-check and the other checks of the package + # run in brain-deb-check. steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: ref: ${{ github.event.pull_request.head.sha || github.sha }} - name: Build the .deb @@ -133,72 +136,7 @@ jobs: # The checksum names the file, not dist/: `sha256sum -c` works from wherever # the artifact is downloaded. ls -l "$deb"; (cd dist && sha256sum "$(basename "$deb")" | tee "$(basename "$deb").sha256") - - name: Install it - run: sudo apt-get install -y "./$DEB" - - name: Self-check the installed package - # From /, isolated (-I), as the runner user and then as root. Root is the strict - # case: a root python writes a __pycache__ wherever a .pyc is missing or stale, - # which the next step would see as a file the package does not own, or as a - # changed one. The run user on the box cannot write the tree at all, so a stale - # .pyc there would cost a recompile on every start instead. - run: | - cd / - /opt/teaport/brain/bin/python -I -m teaport_brain.selfcheck - sudo /opt/teaport/brain/bin/python -I -m teaport_brain.selfcheck - /opt/teaport/brain/bin/teaport-brain --help >/dev/null - test -x /usr/bin/teaport && bash -n /usr/bin/teaport - # compile(), not py_compile: that would write a __pycache__ beside the helper. - for p in /usr/lib/teaport/config_apply.py /usr/lib/teaport/update_apply.py /usr/lib/teaport/wifi_apply.py /usr/lib/teaport/login_apply.py; do - /usr/bin/python3 -I -c 'import sys; p = sys.argv[1]; compile(open(p).read(), p, "exec")' "$p" - done - # The update's unit, as systemd reads it (it is static: nothing enables it). - systemd-analyze verify /usr/lib/systemd/system/teaport-update.service - [ "$(systemctl show -p UnitFileState --value teaport-update.service)" = static ] - - name: dpkg -V is clean, and the package owns every file under its root - run: | - out="$(dpkg -V teaport-brain)" - [ -z "$out" ] || { printf '%s\n' "$out"; echo "dpkg -V: files changed after install"; exit 1; } - stray="$(comm -13 <(dpkg -L teaport-brain | sort -u) <(find /opt/teaport/brain | sort -u))" - [ -z "$stray" ] || { printf '%s\n' "$stray" | head -50; echo "files under /opt/teaport/brain that the package does not own (written at run time?)"; exit 1; } - echo "dpkg -V clean; $(dpkg -L teaport-brain | wc -l) paths owned" - - name: Shared libraries (what Depends must cover) - # Every ELF object in the venv, through ldd. Anything unresolved fails the job. - # Anything resolved OUTSIDE the venv is a system library the package relies on: - # listed with the Debian package that ships it and one .so that needs it, and - # every such package must be named in the .deb's Depends: (what dpkg-shlibdeps - # would have derived, for a package nfpm builds without it). - run: | - find /opt/teaport/brain -type f \( -name '*.so' -o -name '*.so.*' \) > "$RUNNER_TEMP/elfs" - echo "$(wc -l < "$RUNNER_TEMP/elfs") shared objects in the venv" - missing=0; : > "$RUNNER_TEMP/sys" - while IFS= read -r f; do - out="$(ldd "$f" 2>&1 || true)" - if grep -q 'not found' <<<"$out"; then echo "UNRESOLVED in $f:"; grep 'not found' <<<"$out"; missing=1; fi - awk -v so="${f#/opt/teaport/brain/lib/python3.12/site-packages/}" \ - '/=> \//{print $3, so} /^\t\/[^ ]+ \(/{print $1, so}' <<<"$out" \ - | grep -v '^/opt/teaport/brain/' >> "$RUNNER_TEMP/sys" || true - done < "$RUNNER_TEMP/elfs" - # dpkg -S by the path ldd printed, then by its resolved one: since the /usr - # merge a library can be registered under either spelling. Diversion notes - # (the dynamic loader has one) are not owners. - owner() { { dpkg -S "$1"; dpkg -S "$(readlink -f "$1")"; } 2>/dev/null | grep -v '^diversion by' | head -1 | cut -d: -f1; } - echo "system libraries the venv links against:" - : > "$RUNNER_TEMP/pkgs" - while read -r lib so; do - pkg="$(owner "$lib" || true)" - printf ' %-44s %-12s e.g. %s\n' "$lib" "${pkg:-?}" "$so" - echo "${pkg:-?}" >> "$RUNNER_TEMP/pkgs" - done < <(sort -u -k1,1 "$RUNNER_TEMP/sys") - echo "packages: $(sort -u "$RUNNER_TEMP/pkgs" | paste -sd' ')" - depends="$(dpkg-query -W -f='${Depends}' teaport-brain)" - echo "Depends: $depends" - # Package names only (version constraints dropped), matched as whole lines. - sed 's/ *([^)]*)//g; s/, */\n/g' <<<"$depends" > "$RUNNER_TEMP/depends" - for pkg in $(sort -u "$RUNNER_TEMP/pkgs"); do - if ! grep -qxF "$pkg" "$RUNNER_TEMP/depends"; then echo "not in Depends: $pkg"; missing=1; fi - done - [ "$missing" = 0 ] - - uses: actions/upload-artifact@v6 + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: teaport-brain-deb path: | @@ -207,6 +145,29 @@ jobs: if-no-files-found: error compression-level: 0 # already compressed + brain-deb-check: + # The package itself, installed and run (the brain's code, as root too). A release's + # .deb, its hash for the signing laptop and the same checks of it are release-deb.yml's. + needs: brain-deb + runs-on: ubuntu-24.04-arm + timeout-minutes: 30 + permissions: + contents: read + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: teaport-brain-deb + path: dist + - name: The .deb + run: echo "DEB=$(ls dist/teaport-brain_*.deb)" >> "$GITHUB_ENV" + - uses: ./.github/actions/brain-deb-check + with: + deb: ${{ env.DEB }} + plugin: runs-on: ubuntu-latest steps: @@ -301,12 +262,22 @@ jobs: done - name: Installer dry-run (voice-only path) # No Jetson, no sandbox, not a TTY: exercises the full dry-run without touching the box. - run: TEAPORT_ALLOW_NON_JETSON=1 TEAPORT_MANIFEST_URL="$PWD/manifest/stable.json" bash install.sh --dry-run + # The checkout's manifest is verified with the .sig beside it. Read unsigned only while + # the tree has no stable.json.sig at all (before signing was turned on). Once it has + # one, a manifest PR fails here until its new .sig is committed: the .sig in the tree + # is the previous release's, and does not verify the edited file. That is by design. + run: | + unsigned=0; [ -f manifest/stable.json.sig ] || unsigned=1 + TEAPORT_ALLOW_NON_JETSON=1 TEAPORT_MANIFEST_URL="$PWD/manifest/stable.json" \ + TEAPORT_MANIFEST_UNSIGNED="$unsigned" bash install.sh --dry-run - name: Installer dry-run (--install-agent) # The agent-install plan (Node from NodeSource, the pinned OpenClaw, its onboarding) # in front of the same full dry-run; nothing is installed, so the rest is voice-only. + # The checkout's manifest, verified as in the step above. run: | - out="$(TEAPORT_ALLOW_NON_JETSON=1 TEAPORT_MANIFEST_URL="$PWD/manifest/stable.json" bash install.sh --install-agent --dry-run)" + unsigned=0; [ -f manifest/stable.json.sig ] || unsigned=1 + export TEAPORT_ALLOW_NON_JETSON=1 TEAPORT_MANIFEST_URL="$PWD/manifest/stable.json" TEAPORT_MANIFEST_UNSIGNED="$unsigned" + out="$(bash install.sh --install-agent --dry-run)" printf '%s\n' "$out" for want in 'agent: installing OpenClaw (openclaw@' 'npm install -g openclaw@' '--allow-scripts=openclaw,' 'openclaw onboard --non-interactive' '--auth-choice skip' '--skip-daemon'; do case "$out" in *"$want"*) ;; *) echo "::error::the --install-agent dry-run does not show: $want"; exit 1 ;; esac @@ -320,10 +291,16 @@ jobs: if [ "$rc" != 2 ]; then echo "::error::$what: exit $rc, not 2 (a usage error)"; printf '%s\n' "$err"; exit 1; fi case "$err" in *"$words"*) ;; *) echo "::error::$what: not refused for that reason"; printf '%s\n' "$err"; exit 1 ;; esac } - export TEAPORT_ALLOW_NON_JETSON=1 TEAPORT_MANIFEST_URL="$PWD/manifest/stable.json" refused "--only brain --install-agent" "--install-agent is part of a full run" bash install.sh --only brain --install-agent --dry-run + refused "--only license --install-agent" "--install-agent is part of a full run" bash install.sh --only license --install-agent --dry-run refused "TEAPORT_INSTALL_AGENT=nemoclaw" "unknown agent 'nemoclaw'" env TEAPORT_INSTALL_AGENT=nemoclaw bash install.sh --dry-run - name: Installer dry-run (--only brain) # The incremental brain update path. Off-appliance it warns that there is no # install to update and shows the plan anyway: stage, self-check, swap, restart. - run: bash install.sh --only brain --dry-run + # Against the checkout's manifest, as the step above, so CI reads nothing from the + # bucket: verified with the .sig beside it, unsigned only while the tree has none, and + # failing on a manifest PR until its new .sig is committed (as the step above). + run: | + unsigned=0; [ -f manifest/stable.json.sig ] || unsigned=1 + TEAPORT_MANIFEST_URL="$PWD/manifest/stable.json" TEAPORT_MANIFEST_UNSIGNED="$unsigned" \ + bash install.sh --only brain --dry-run diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 18479458..3632a954 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -14,20 +14,72 @@ name: publish # file back from the public URL. A manifest therefore goes up only when its artifacts # are already in the bucket; upload the artifacts first, then merge. # -# The upload runs in the r2-publish environment. Its secrets are read by the upload step -# only and never on pull_request. Restrict the environment's deployment branches to -# main (Settings > Environments) so no other branch's workflow can read them: +# Signatures: boxes install nothing from a manifest whose signature does not verify against +# the release keys (manifest/allowed_signers), so the check verifies manifest/.json.sig +# first, and the upload carries it with the manifest. Nothing here can sign: the signature is +# made offline with a key CI never sees (packaging/RELEASING.md) and committed beside the +# manifest. The bucket's token can replace a manifest, but not make boxes install from it. +# check.py --boxes-signers holds each manifest to more than this commit's keys, with all +# trust state taken from git at --base (the commit last uploaded; see below), never from the +# bucket: +# - every release's brain.commit carries exactly this tree's manifest/allowed_signers (and +# its .deb the commit's), so a key swapped at a tagged commit fails whoever signed; +# - the signature must also verify with the keys boxes on the channel have: the signers +# file at the brain.commit --base's manifest/.json names (not the newest +# release tag, which a release pushes before its manifest PR), or, while that names no +# release with keys, the keys of --base's install-bootstrap.sh; a key change passes +# only signed by a key they already carry; +# - the one manifest let through with other keys than the tree's is a re-signature: byte +# for byte --base's, naming the release --base names (a rotation PR's). +# --base is what was actually uploaded: the head commit of the last of main's own publish runs +# (push or dispatch, this repository's workflow file, any attempt) whose upload and read-back +# both succeeded, taken from GitHub's record of the runs (manifest/last_upload.py, actions: +# read), and an ancestor of main; a PR (into main only) is measured against its base, and its +# merge's run again against the last upload. While another of main's publish runs is still +# running the lookup stops (re-run when it finishes): it may be uploading. A run that went +# red before its upload (missing credentials included) changed nothing and +# is answered by a revert or a fix, measured against the last upload; one whose upload ran +# but did not read back may have changed the bucket, and the next lookup stops and asks for +# an explicit base. A renamed job or step stops it too (keep the names). GitHub drops a +# queued run when a newer one queues in the same group: wait for each manifest or bootstrap +# merge's run to finish green before merging the next (above all before a rotation PR), and +# dispatch a dropped one with base = the last uploaded commit. --base must resolve and the +# lookup must answer, or the job fails; with no upload yet, the fallback (main before the +# push, HEAD weekly) holds only while signing is not on there. The check is a tripwire, not +# a barrier: whoever can push can edit this file. +# The bootstrap (/teaport) is signed the same way, in its own namespace (teaport-bootstrap), +# and goes up as /teaport.sig, then /teaport. It carries the keys itself and verifies the +# manifest before it clones anything; its signature must verify with the keys --base's +# bootstrap carries too, so a key a push adds is not taken until a trusted key signs for it. +# None of this is the real control: the signer reviewing the commit, keys included, is +# (packaging/RELEASING.md), and what protects boxes from whatever the bucket serves is the +# box side, which verifies every manifest itself. +# The .sig goes up first, then the manifest: R2 swaps no two objects at once, so for the +# seconds between the two a box reads a manifest and a signature that do not match, and +# refuses it (no install, no update offered; the next look gets the pair). That window fails +# closed, which is the side to fail on. +# +# The upload runs in the r2-publish environment. Its secrets are read by the credentials +# check and the upload step only, and never on pull_request. Restrict the environment's +# deployment branches to main (Settings > Environments) so no other branch's workflow can +# read them: # R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY an R2 API token with write access to the # teaport-get bucket # R2_ENDPOINT https://.r2.cloudflarestorage.com # # The engine's files and models are gated (manifest access.gated: the download gate Worker # in worker/ serves them from a private bucket, only with a token). The check downloads them -# with DL_CHECK_TOKEN, a repository secret equal to the Worker's CHECK_TOKEN, on every run -# but a pull request's; a pull request's run checks only that each refuses a download -# without a token. Every run also checks that none is served at a percent-encoded path -# around the Worker's routes (a copy left in teaport-get), and the weekly run fails while -# the gate is open. +# with DL_CHECK_TOKEN, equal to the Worker's CHECK_TOKEN, on every run but a pull request's. +# It is a secret of the gate-check environment, never the repository's: that environment's +# deployment branches are main only, with no reviewer (the weekly run uses it unattended), +# and only the artifacts job of a run on main enters it. A workflow on any other branch, a +# pull request's run included, cannot read it. A pull request's run checks only that each +# gated file refuses a download without a token and is not served around the gate; its +# sha256 is compared by the merge's run (and by the release PR's local check, RELEASING.md). +# Every run also checks that none is served at a percent-encoded path around the Worker's +# routes (a copy left in teaport-get), and the weekly run fails while the gate is open. Run +# it by hand (workflow_dispatch) from main: from another branch, the artifacts job stops at +# gate-check's branch policy. on: push: @@ -35,19 +87,39 @@ on: paths: - manifest/** - install-bootstrap.sh + - install-bootstrap.sh.sig - .github/workflows/publish.yml pull_request: + # Only a PR into main: it is measured against main (its base). `edited` covers a PR + # retargeted onto main; last_upload.py refuses any other base branch as well. + branches: [main] + types: [opened, synchronize, reopened, edited] paths: - manifest/** - install-bootstrap.sh + - install-bootstrap.sh.sig - .github/workflows/publish.yml schedule: - cron: "17 6 * * 1" workflow_dispatch: + inputs: + base: + description: >- + The commit this run is measured against (check.py --base), as a commit id. Empty + (the default): the last commit a publish run uploaded and read back. Name one after + a hand upload, or for a run that GitHub dropped. + required: false + default: "" +# Concurrency groups are repository-wide: a fork PR's own workflow file could join these +# and cancel or hold a publish run. Requiring approval for all external contributors' fork +# PR workflows is what keeps outsiders out (packaging/RELEASING.md, GitHub settings). # Never two uploads at once, and never cancel one halfway; a PR's newer push replaces # its older check. The weekly check has its own group: queued behind a merge's run it # would otherwise displace that run while it waits, and the merge would go unpublished. +# The base step stops while another of main's runs is in flight (a queued one too) and +# never counts its own run: a running run that stops for a queued one ends, which starts +# the queued one, whose lookup then finds nothing in flight. Nothing waits: no deadlock. concurrency: group: publish-${{ github.event_name == 'schedule' && 'weekly' || github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} @@ -57,18 +129,45 @@ permissions: jobs: artifacts: + name: artifacts runs-on: ubuntu-latest + # The gate's check token: only on main's runs (push, dispatch, the weekly one), from the + # gate-check environment (main only). A pull request's run has no environment, no token. + environment: ${{ github.event_name != 'pull_request' && 'gate-check' || '' }} + permissions: + contents: read + actions: read # the publish runs' record (the base step) timeout-minutes: 30 steps: - uses: actions/checkout@v5 with: persist-credentials: false + fetch-depth: 1 # other commits are fetched by id when needed (last_upload.py, check.py) - name: The bootstrap parses # ci.yml checks it too, but publish does not wait for ci.yml. run: bash -n install-bootstrap.sh + - name: The base this run is measured against + # check.py --base (manifest/last_upload.py): the PR's base on pull_request; a + # dispatch's explicit `base`; else the last commit a publish run uploaded and read + # back, from GitHub's own record of the runs (actions: read). With no upload yet, + # main before the push (HEAD for the weekly run) only while signing is not on there. + # A lookup that fails fails the job: never a guess. + id: base + env: + GITHUB_TOKEN: ${{ github.token }} + EVENT: ${{ github.event_name }} + PR_BASE: ${{ github.event.pull_request.base.sha }} + BASE_REF: ${{ github.base_ref }} + BEFORE: ${{ github.event.before }} + INPUT: ${{ inputs.base }} + run: | + base="$(python3 manifest/last_upload.py base --event "$EVENT" --pr-base "$PR_BASE" \ + --base-ref "$BASE_REF" --before "$BEFORE" --input "$INPUT")" + echo "base=$base" >> "$GITHUB_OUTPUT" - name: The manifests name everything install.sh needs, published as named # Downloads every artifact (~4.6 GB, mostly the Voxtral model): a few minutes. env: + BASE: ${{ steps.base.outputs.base }} DL_CHECK_TOKEN: ${{ github.event_name != 'pull_request' && secrets.DL_CHECK_TOKEN || '' }} EVENT: ${{ github.event_name }} run: | @@ -83,19 +182,27 @@ jobs: # Every other run warns (packaging/RELEASING.md). strict=() if [ "$EVENT" = schedule ]; then strict=(--require-enforce); fi - python3 manifest/check.py "${strict[@]}" manifest/stable.json - python3 manifest/check.py "${strict[@]}" --placeholders-ok manifest/beta.json + python3 manifest/check.py "${strict[@]}" --base "$BASE" --boxes-signers manifest/stable.json + python3 manifest/check.py "${strict[@]}" --base "$BASE" --boxes-signers --placeholders-ok manifest/beta.json + python3 manifest/check.py --base "$BASE" --boxes-signers --bootstrap install-bootstrap.sh publish: + # The name the base step looks for (manifest/last_upload.py JOB): keep it, and the upload + # and read-back steps' names, as they are. + name: publish needs: artifacts if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 10 environment: r2-publish + permissions: + contents: read + actions: read # the publish runs' record (the base step) steps: - uses: actions/checkout@v5 with: persist-credentials: false + fetch-depth: 1 # other commits are fetched by id when needed (last_upload.py, check.py) - name: Only what main serves now is published # A re-run of an older run checks out that run's commit: uploading it would put # an older manifest over a newer one. So compare this commit's files with main's @@ -105,30 +212,79 @@ jobs: id: tip run: | git fetch --no-tags --depth=1 "https://github.com/${GITHUB_REPOSITORY}.git" refs/heads/main - if git diff --quiet "$GITHUB_SHA" FETCH_HEAD -- manifest/stable.json manifest/beta.json install-bootstrap.sh; then + if git diff --quiet "$GITHUB_SHA" FETCH_HEAD -- manifest/stable.json manifest/beta.json \ + manifest/stable.json.sig manifest/beta.json.sig install-bootstrap.sh install-bootstrap.sh.sig; then echo "publish=1" >> "$GITHUB_OUTPUT" else echo "::notice::main's tip $(git rev-parse FETCH_HEAD) has other manifests or bootstrap than ${GITHUB_SHA}: not publishing an older commit (the later commit's own run publishes)" fi - - name: Upload to the download bucket + - name: The base this run is measured against + # check.py --base (manifest/last_upload.py): the PR's base on pull_request; a + # dispatch's explicit `base`; else the last commit a publish run uploaded and read + # back, from GitHub's own record of the runs (actions: read). With no upload yet, + # main before the push (HEAD for the weekly run) only while signing is not on there. + # A lookup that fails fails the job: never a guess. + id: base + env: + GITHUB_TOKEN: ${{ github.token }} + EVENT: ${{ github.event_name }} + PR_BASE: ${{ github.event.pull_request.base.sha }} + BASE_REF: ${{ github.base_ref }} + BEFORE: ${{ github.event.before }} + INPUT: ${{ inputs.base }} + run: | + base="$(python3 manifest/last_upload.py base --event "$EVENT" --pr-base "$PR_BASE" \ + --base-ref "$BASE_REF" --before "$BEFORE" --input "$INPUT")" + echo "base=$base" >> "$GITHUB_OUTPUT" + - name: The signatures still verify + # The artifacts job checked this commit; this is the same check (no downloads), + # right before the upload, on the files about to go up. + if: steps.tip.outputs.publish == '1' + env: + BASE: ${{ steps.base.outputs.base }} + run: | + python3 manifest/check.py --signature-only --base "$BASE" --boxes-signers manifest/stable.json + python3 manifest/check.py --signature-only --base "$BASE" --boxes-signers --placeholders-ok manifest/beta.json + python3 manifest/check.py --base "$BASE" --boxes-signers --bootstrap install-bootstrap.sh + - name: The bucket's credentials are set + # Its own step, so that missing secrets leave the upload step skipped: the lookup + # (last_upload.py) then reads the run as one that uploaded nothing, which it is. if: steps.tip.outputs.publish == '1' env: AWS_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }} - AWS_DEFAULT_REGION: auto R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }} run: | if [ -z "$AWS_ACCESS_KEY_ID" ] || [ -z "$AWS_SECRET_ACCESS_KEY" ] || [ -z "$R2_ENDPOINT" ]; then echo "::error::R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY / R2_ENDPOINT are not set in the r2-publish environment: nothing was published" exit 1 fi + - name: Upload to the download bucket + if: steps.tip.outputs.publish == '1' + env: + AWS_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: auto + R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }} + run: | put() { # put : the types the bucket already serves aws s3 cp "$1" "s3://teaport-get/$2" --endpoint-url "$R2_ENDPOINT" \ --content-type "$3" --only-show-errors echo "uploaded $1 -> https://get.teaspoon.tech/$2" } - put manifest/stable.json manifest/stable.json application/json - put manifest/beta.json manifest/beta.json application/json + # Each manifest after its signature (see the top). A manifest the check let go + # unsigned (all placeholders, --placeholders-ok) takes any older signature down + # with it: a stale one would only make boxes refuse it for the wrong reason. + for ch in stable beta; do + if [ -f "manifest/$ch.json.sig" ]; then + put "manifest/$ch.json.sig" "manifest/$ch.json.sig" text/plain + else + aws s3 rm "s3://teaport-get/manifest/$ch.json.sig" --endpoint-url "$R2_ENDPOINT" --only-show-errors + fi + put "manifest/$ch.json" "manifest/$ch.json" application/json + done + # The bootstrap after its signature, the same way (the check above requires one). + put install-bootstrap.sh.sig teaport.sig text/plain put install-bootstrap.sh teaport text/x-shellscript - name: Read each file back from get.teaspoon.tech if: steps.tip.outputs.publish == '1' @@ -136,8 +292,10 @@ jobs: # the bucket holds. A cache rule on the domain would make it fail here, loudly. run: | for pair in manifest/stable.json:manifest/stable.json manifest/beta.json:manifest/beta.json \ - install-bootstrap.sh:teaport; do + manifest/stable.json.sig:manifest/stable.json.sig manifest/beta.json.sig:manifest/beta.json.sig \ + install-bootstrap.sh.sig:teaport.sig install-bootstrap.sh:teaport; do file="${pair%%:*}"; key="${pair#*:}" + [ -f "$file" ] || continue # an unsigned placeholder channel has no .sig curl -fsS "https://get.teaspoon.tech/$key" | cmp - "$file" \ || { echo "::error::https://get.teaspoon.tech/$key does not serve $file"; exit 1; } echo "ok https://get.teaspoon.tech/$key == $file" diff --git a/.github/workflows/release-deb.yml b/.github/workflows/release-deb.yml new file mode 100644 index 00000000..b46cde8d --- /dev/null +++ b/.github/workflows/release-deb.yml @@ -0,0 +1,146 @@ +name: release-deb + +# A brain-vX.Y.Z (or brain-vX.Y.Z-rcN) tag's .deb and its sha256, for the signing laptop, in +# a workflow of its own: no other job shares its run, so nothing else in the repository runs +# beside the jobs here, and only release-deb-check, after the hash, runs the package's code. +# release-deb-build builds the package from the tag (packaging/build-deb.sh, whose tools and +# build backend are pinned) and uploads it; brain-deb-sha256 has no checkout and no +# repository code: it checks GitHub's record of that one artifact (by its id) carries the +# digest the build job reported, downloads it (digest-checked), checks the .deb's sha256 +# against the build's, and prints the sha256 as a check-run annotation +# (teaport-brain-deb-sha256). The signing helper reads it anonymously through GitHub's API, +# from this workflow file only, as a cross-check of its own reading of the .deb +# (packaging/RELEASING.md). Its artifact is teaport-brain-release-deb (ci.yml's builds are +# teaport-brain-deb). No job here takes a name main's ruleset requires (ci.yml's brain, +# brain-deb, plugin, worker, formal, installer; docs.yml's docs): a tag's run must not +# stand in for them. Keep the file, job, artifact and annotation names. + +on: + push: + tags: ["brain-v*"] + +permissions: {} + +concurrency: + group: release-deb-${{ github.ref }} + cancel-in-progress: false + +jobs: + release-deb-build: + runs-on: ubuntu-24.04-arm + timeout-minutes: 30 + permissions: + contents: read + outputs: + artifact-id: ${{ steps.upload.outputs.artifact-id }} + artifact-digest: ${{ steps.upload.outputs.artifact-digest }} + deb-sha256: ${{ steps.build.outputs.deb-sha256 }} + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + - name: Build the .deb + id: build + shell: bash + run: | + # checkout fetched the commit, not the tag; build-deb.sh checks HEAD is it. + git fetch --no-tags --depth=1 origin "+$GITHUB_REF:$GITHUB_REF" + export TEAPORT_DEB_VERSION="${GITHUB_REF_NAME#brain-v}" + packaging/build-deb.sh + cd dist + debs=(teaport-brain_*.deb) + [ "${#debs[@]}" = 1 ] || { echo "not exactly one .deb: ${debs[*]}"; exit 1; } + sha256sum "${debs[0]}" | tee "${debs[0]}.sha256" + echo "deb-sha256=$(sha256sum "${debs[0]}" | cut -d' ' -f1)" >> "$GITHUB_OUTPUT" + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + id: upload + with: + name: teaport-brain-release-deb + path: | + dist/teaport-brain_*.deb + dist/teaport-brain_*.deb.sha256 + if-no-files-found: error + compression-level: 0 # already compressed + + brain-deb-sha256: + needs: release-deb-build + runs-on: ubuntu-latest + permissions: + actions: read + steps: + - name: The artifact is the one the build uploaded + # GitHub's record of the artifact (by the id the build reported) must carry the digest + # the build reported; download-artifact then checks what it downloads against that record. + shell: bash + env: + GH_TOKEN: ${{ github.token }} + ARTIFACT_ID: ${{ needs.release-deb-build.outputs.artifact-id }} + WANT_DIGEST: ${{ needs.release-deb-build.outputs.artifact-digest }} + run: | + [ -n "$ARTIFACT_ID" ] && [ -n "$WANT_DIGEST" ] || { echo "the build reported no artifact id or digest"; exit 1; } + got="$(curl -fsS -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" \ + "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID" | jq -r .digest)" + [ "${got#sha256:}" = "${WANT_DIGEST#sha256:}" ] || { echo "artifact $ARTIFACT_ID has digest $got, not $WANT_DIGEST"; exit 1; } + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.release-deb-build.outputs.artifact-id }} + path: dist + merge-multiple: true + digest-mismatch: error + - name: The .deb's sha256 + shell: bash + env: + WANT_SHA256: ${{ needs.release-deb-build.outputs.deb-sha256 }} + run: | + cd dist + debs=(teaport-brain_*.deb) + [ "${#debs[@]}" = 1 ] || { echo "not exactly one .deb: ${debs[*]}"; exit 1; } + got="$(sha256sum "${debs[0]}" | cut -d' ' -f1)" + [ "$got" = "$WANT_SHA256" ] || { echo "the downloaded .deb is not the one built"; exit 1; } + sha256sum -c "${debs[0]}.sha256" + echo "::notice title=teaport-brain-deb-sha256::$(sha256sum "${debs[0]}")" + + release-deb-check: + # The release .deb itself, installed and checked as ci.yml checks every build (the + # brain's code runs here, as root too). It runs only after the sha256 is printed, and + # takes the artifact by the build's id, checked against the build's digest: nothing here + # can change what was hashed, and what is checked is what was hashed. + needs: [release-deb-build, brain-deb-sha256] + runs-on: ubuntu-24.04-arm + timeout-minutes: 30 + permissions: + contents: read + actions: read + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + - name: The artifact is the one the build uploaded + shell: bash + env: + GH_TOKEN: ${{ github.token }} + ARTIFACT_ID: ${{ needs.release-deb-build.outputs.artifact-id }} + WANT_DIGEST: ${{ needs.release-deb-build.outputs.artifact-digest }} + run: | + [ -n "$ARTIFACT_ID" ] && [ -n "$WANT_DIGEST" ] || { echo "the build reported no artifact id or digest"; exit 1; } + got="$(curl -fsS -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" \ + "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID" | jq -r .digest)" + [ "${got#sha256:}" = "${WANT_DIGEST#sha256:}" ] || { echo "artifact $ARTIFACT_ID has digest $got, not $WANT_DIGEST"; exit 1; } + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + artifact-ids: ${{ needs.release-deb-build.outputs.artifact-id }} + path: dist + merge-multiple: true + digest-mismatch: error + - name: The .deb, the one hashed + shell: bash + env: + WANT_SHA256: ${{ needs.release-deb-build.outputs.deb-sha256 }} + run: | + debs=(dist/teaport-brain_*.deb) + [ "${#debs[@]}" = 1 ] || { echo "not exactly one .deb: ${debs[*]}"; exit 1; } + [ "$(sha256sum "${debs[0]}" | cut -d' ' -f1)" = "$WANT_SHA256" ] || { echo "not the .deb hashed"; exit 1; } + echo "DEB=${debs[0]}" >> "$GITHUB_ENV" + - uses: ./.github/actions/brain-deb-check + with: + deb: ${{ env.DEB }} diff --git a/README.md b/README.md index d3e45c88..bfda2618 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,10 @@ full procedure. - `manifest/` — the release manifest for the installer and `teaport update`. Merging a change to it, or to `install-bootstrap.sh` (the one-liner), publishes it to get.teaspoon.tech (`.github/workflows/publish.yml`), after checking that every - artifact the manifest names is already uploaded with that sha256. Upload a release's - artifacts first, then merge its manifest. + artifact the manifest names is already uploaded with that sha256, and that each file's + `.sig` verifies against the release keys in `manifest/allowed_signers`. Upload a + release's artifacts first, sign its manifest offline (`packaging/RELEASING.md`), then + merge. - `install.sh` · `cli/teaport` · `systemd/` — install and operate the product - `docs/` — the documentation site, published at [docs.teaspoon.tech](https://docs.teaspoon.tech): installation, guides, and the diff --git a/brain/build-requirements.txt b/brain/build-requirements.txt new file mode 100644 index 00000000..e2faf102 --- /dev/null +++ b/brain/build-requirements.txt @@ -0,0 +1,6 @@ +# The build backend packaging/build-deb.sh builds the brain with: teaport-brain and the +# lock's one sdist (docopt). uv.lock records no build dependencies, so this file pins it, by +# version and sha256 (installed with --require-hashes, then used with --no-build-isolation). +# It must satisfy [build-system] requires and [tool.uv] build-constraint-dependencies in +# pyproject.toml (test_manifest_sig.py checks). Change it with a green release build. +setuptools==80.10.2 --hash=sha256:95b30ddfb717250edb492926c92b5221f7ef3fbcc2b07579bcd4a27da21d0173 diff --git a/brain/teaport_brain/config_apply.py b/brain/teaport_brain/config_apply.py index 40d9ebb0..a56c10df 100644 --- a/brain/teaport_brain/config_apply.py +++ b/brain/teaport_brain/config_apply.py @@ -68,6 +68,18 @@ STOPPABLE = ("teaport-wifi-setup",) MAX_BYTES = 64 * 1024 BACKUPS = 5 +# The engine's license files (teaport#474 F1): nothing here writes, renames or removes them, +# whatever a path above comes to name. The same tuple in every root helper the run user +# reaches (license_link.PROTECTED is the one list; tests hold the copies to it). +PROTECTED = ("/etc/teaport/license.json", "/etc/teaport/license-revocations.json", + "/etc/teaport/license-link.secret") + + +def protected(path: str) -> bool: + """`path` is one of PROTECTED, by name or through a link.""" + return os.path.abspath(path) in PROTECTED or os.path.realpath(path) in PROTECTED + + # Only backups THIS code named are ever pruned. Operators keep their own beside # them (brain.env.bak-gptoss, brain.env.bak-20260901-154338-stopsecs on the dev # box) and those are not ours to rotate out. @@ -102,6 +114,8 @@ def write(name: str, content: str) -> str: if content and not content.endswith("\n"): content += "\n" path = os.path.join(ETC, name) + if protected(path): + raise SystemExit(f"refusing to write {name!r}: it is the engine's license") mode, uid, gid = 0o640, 0, int(os.environ.get("SUDO_GID", "0")) if os.path.exists(path): st = os.stat(path) @@ -138,7 +152,8 @@ def _backup(path: str, mode: int, uid: int, gid: int) -> None: older = sorted(f for f in os.listdir(os.path.dirname(path)) if f.startswith(base + ".bak-") and BACKUP_RE.search(f)) for name in older[:-BACKUPS]: - os.unlink(os.path.join(os.path.dirname(path), name)) + if not protected(os.path.join(os.path.dirname(path), name)): + os.unlink(os.path.join(os.path.dirname(path), name)) def restart(unit: str) -> None: diff --git a/brain/teaport_brain/config_schema.toml b/brain/teaport_brain/config_schema.toml index 4648def7..5a80dc0b 100644 --- a/brain/teaport_brain/config_schema.toml +++ b/brain/teaport_brain/config_schema.toml @@ -2373,6 +2373,18 @@ tier = "installer" help = "Refuse to serve if the AI watermark is not loaded (its weights missing from /opt/teaport/bin/watermark/, or VOX_TTS_WATERMARK=0), rather than speak without the machine-readable mark synthetic audio must carry. Engines before 1.7 ignore it." source = "install.sh" +[[settings]] +name = "VOX_LICENSE_MODE" +store = "engine_env" +group = "engine_service" +type = "enum" +values = ["", "off", "warn", "on"] +default = "" +read = "startup" +tier = "installer" +help = "Whether the engine needs a valid license key (/etc/teaport/license.json, teaport#474). Unset or empty: the engine build's default, warn. warn: it runs without one and says so. on: it refuses to start without one (exit 78, which the unit does not retry) and refuses new sessions once the key stops being valid. off: no check. Any other value fails closed, as on. An engine built to enforce ignores a looser value. The installer writes it only when TEAPORT_LICENSE_MODE asks, and only as off, warn or on; teaport doctor reports any other value." +source = ["install.sh", "cli/teaport"] + # ================================================================ teaport-sip.conf [[settings]] diff --git a/brain/teaport_brain/config_ui.py b/brain/teaport_brain/config_ui.py index ca7025cf..a8d2ffbf 100644 --- a/brain/teaport_brain/config_ui.py +++ b/brain/teaport_brain/config_ui.py @@ -13,6 +13,10 @@ POST /api/restart {unit} — deferred restart through config_apply GET /api/login whether the owner's login is pending (#421), and its words POST /api/login {password, again} — creates it, through owner_login + GET /api/eula whether the owner's license step is pending (#465), the + license's text, and the step's words + POST /api/eula {email, accept, eula_sha256} — the owner accepts it, through + owner_license GET /licenses the open-source licenses page (static/licenses.html); its data is GET /api/licenses and GET /api/licenses/{package} (licenses.py) @@ -907,14 +911,92 @@ async def login_create(request: Request): password, again = _login_body(await request.json()) except ValueError: raise HTTPException(status_code=400, detail="the request is not JSON") from None + t = _reader(request) + # Setup is unfinished until the license is accepted, as on the setup page, where it comes + # first (#465): while it waits, the login waits for it too. + from teaport_brain import owner_license + if await asyncio.to_thread(_owner_license().pending): + logger.info("config: the owner's login not created (the license first) from Settings") + return {"ok": False, "why": "license_first", + "message": owner_license.say(t, owner_license.TEXT["login_first"])} ok, why = await asyncio.to_thread(_owner_login().create, password, again) logger.info("config: the owner's login " + ("created" if ok else f"not created ({why})") + " from Settings") - t = _reader(request) msgid = owner_login.TEXT["created"] if ok else owner_login.WHY[why] return {"ok": ok, "why": why or None, "message": owner_login.say(t, msgid)} +# ------------------------------------------------------------------ the owner's license +# The "Read the license" card (#465), beside "Create your login": offered while setup is +# unfinished on a box provisioning marked for it and nobody has accepted the license there +# yet, for an owner whose box got online without the setup page (or whose setup page had no +# copy of the license to show). Setup finishes only once it is accepted, and the login card +# waits for it (login_create); nothing else on the box does (the engine runs under the box's +# appliance key). An acceptance made, while it may still be replaced, shows its email masked, +# with "Not you? Accept again". The recording is +# owner_license's, through license_accept and license_link as root; the email goes there +# and nowhere else (no log line, no answer). + + +def _owner_license(): + """Replaced in tests.""" + from teaport_brain import owner_license + return owner_license.License() + + +@router.get("/api/eula") +async def eula_state(request: Request): + """Whether the card is offered, the license's text when it is, and the card's words in + the reader's language. The text is the helper's (the channel's manifest, checked).""" + from teaport_brain import owner_license + _authorize(request) + t = _reader(request) + lic = _owner_license() + state = await asyncio.to_thread(lic.state) + # Accepted while setup is unfinished: whose email (masked), and whether it may still be + # replaced ("Not you? Accept again"; license_accept.py says why it is shown). + accepted = await asyncio.to_thread(lic.accepted) if state in (owner_license.QUEUED, owner_license.RECORDED) else None + wanted = state == owner_license.PENDING or bool(accepted and accepted["replaceable"]) + doc = await asyncio.to_thread(lic.text) if wanted else None + words = {k: owner_license.say(t, v) for k, v in owner_license.TEXT.items() if k != "accepted_as"} + if accepted: + words["accepted_as"] = owner_license.say(t, owner_license.TEXT["accepted_as"], email=accepted["email"]) + lost = await asyncio.to_thread(lic.link_lost) + if lost: + words["link_lost"] = owner_license.say(t, owner_license.TEXT[lost]) + return {"offered": state == owner_license.PENDING, "state": state, "accepted": accepted, "link_lost": bool(lost), + "license": doc, "lang": t.lang.replace("_", "-"), "dir": t.dir, "text": words, + "why_unavailable": (owner_license.say(t, owner_license.WHY["unavailable"]) + if wanted and doc is None else None)} + + +@router.post("/api/eula") +async def eula_accept(request: Request): + """{email, accept: true, eula_sha256 (of the text shown), owner_use (personal or + business), replace}: the owner's + acceptance, recorded (or queued) and linked; with replace, in place of the one on the box + while it may still be replaced. {ok, why, state, message}: a refusal is a 200 with ok + false, as the card shows it in place.""" + from teaport_brain import owner_license + _authorize(request) + try: + body = await request.json() + except ValueError: + raise HTTPException(status_code=400, detail="the request is not JSON") from None + if not isinstance(body, dict) or not isinstance(body.get("email"), str) \ + or not isinstance(body.get("eula_sha256"), str): + raise HTTPException(status_code=400, detail="email and eula_sha256 must be text") + ok, why = await asyncio.to_thread(_owner_license().accept, body["email"], body["eula_sha256"], + body.get("accept") is True, body.get("owner_use"), + body.get("replace") is True) + logger.info("config: the owner's license acceptance " + (why if ok else f"not recorded ({why})") + + " from Settings") + t = _reader(request) + msgid = owner_license.TEXT[why] if ok else owner_license.WHY[why] + return {"ok": ok, "why": None if ok else why, "state": why if ok else None, + "message": owner_license.say(t, msgid)} + + @router.post("/api/restart") async def restart(request: Request): _authorize(request) diff --git a/brain/teaport_brain/license_accept.py b/brain/teaport_brain/license_accept.py new file mode 100644 index 00000000..1bc2e0a1 --- /dev/null +++ b/brain/teaport_brain/license_accept.py @@ -0,0 +1,696 @@ +# +# teaport — the owner's acceptance of the Teaport Engine License at setup (#465): the one +# way the run user can have the box record who accepted it. As root, behind sudo. +# +# A factory box ships with its engine installed under Teaspoon AI's maker record and its +# appliance key (#464, #474), and no one's acceptance of the license: its owner accepts it +# at setup, on the setup page (wifi_setup.py, offline) or in Settings (config_ui.py, +# online), both through owner_license.py. This helper records that acceptance, and nothing +# else. The run user is the agent's (#416, #418): it may ask, never decide. So: +# - it takes the owner's email and nothing else that says who accepted: never an +# acceptance id (a request that names one, or anything not listed below, is refused). +# It makes POST /accept itself and records the id the license server returns, so +# the record can only ever name an acceptance made here, with the email the owner typed; +# - for the run user, it works only while setup is unfinished: while provisioning's marker +# (GATE_PATH, in the same root-only directory as the login's, login_apply.py) is there. +# An acceptance recorded (RECORD_PATH) or queued (QUEUE_PATH) is replaced only by a +# request that says so (replace: the page's "Not you? Accept again", shown with the +# recorded email masked, status), only until the link is made (license_link.py removes +# the marker then) and only while the owner's login is still to be made (the login's +# marker, LOGIN_PENDING_PATH): the window an agent could accept first in, with any email, +# is the login's, and the page shows the owner whose email is recorded, so they can take +# it back (docs: security.md); +# - an administrator (sudo with their password: SUDO_UID is not the run user's), or root, +# may accept, and replace, at any time, after the link too: the owner holding the box +# puts their own acceptance on it and links it (license_link.py), which is support's +# re-link for a wrong link (the owner's decision, 2026-11-28): possession of the box +# outranks any record. Only online then: no timer sends a queue after setup; +# - the text the owner accepts is the one the page showed: the page names its SHA-256 +# (eula_sha256), and the helper refuses it unless it is the current license's, read +# from the channel's manifest and checked against it (text). +# The record is install.sh's own receipt, /var/lib/teaport/eula-accepted.json (root's, +# 0600): a later `install.sh` or `teaport update` gets its download tokens with it, as from +# an acceptance made at the installer. Never the run user's $STATE: the record is what the +# link helper (license_link.py) puts on the box's license key, so the run user must not be +# able to write it. Beside it, the accepted text (EULA-v.txt, 0644), as install.sh +# keeps it. +# +# Offline (the setup page has no internet: the box is not on the owner's network yet), the +# email waits in QUEUE_PATH, root's 0600, and this helper sends it itself when the box is +# next online: `flush`, which teaport-license-owner.timer runs as root (OnBootSec, then every +# few minutes, only while a queue or the marker is there). A timer, not NetworkManager's +# dispatcher or the brain's own online watcher (first_boot.py): the watcher runs as the run +# user, and a dispatcher hook runs once per event while a POST can fail for a reason that +# lasts (the license server busy, a captive network): it needs a retry either way, and a +# timer is that retry, from boot, whatever brought the box online. A queued acceptance the +# server refuses for good (the license changed meanwhile: 409 eula_changed; or a request it +# does not take) is dropped, and the setup step is offered again; anything else stays queued. +# +# Where: the license server is API, built in, never the manifest's access.api nor a record's: +# the installed manifest and an older installer's receipt may be files the run user could +# write, and the email (and, through the link, the box's secret) would go wherever they said. +# A manifest naming any other server, or a text off its origin, is no license here. +# +# Which device: a factory box (/etc/appliance-id, the serial the station assigned) sends +# SHA-256 of "teaport-appliance:" and its serial, as the station's maker record does +# (docs/engine-license-data.md), so the owner's acceptance and the maker's match; any other +# box, SHA-256 of "teaport-device:" and its machine id, as install.sh sends. Which use: +# "personal", the one POST /api/accept takes without a license_id, and owner_use, what the +# owner says the box is for ("personal" or "business": the step asks; migrations/0006). +# Not "licensed" with the box's key's id: the license server cannot check that id, so it +# would be a link from an email to a key that anyone could claim; the box's key is linked +# to its owner only by the link, with the box's secret (licenses.acceptance_id). Method: +# "tty", as an acceptance read and made at the installer's prompt (the license server's +# acceptances.method takes tty or flag only, a CHECK that only a table rebuild could +# widen), and the installer field says where: "setup:" and the brain's revision. The box's +# own record says "setup". +# +# Verbs (the only argument; the request is a JSON object on stdin, the reply one on stdout; +# a request this does not do gets {"refused": why, "why": code} and exit 2): +# status {state, email, replaceable}: PENDING (setup unfinished, nothing accepted), +# QUEUED, RECORDED (an acceptance is on the box, the installer's included), +# NOT_OFFERED (no marker: a box no provisioning marked, or a setup that finished); +# the accepted email masked (mask(): o***@e***.com), and whether accept with +# replace may still replace it; +# text {version, sha256, text}: the license to accept now, only while the marker is +# there: from the channel's manifest (the installed one when offline) and the text +# kept on the box, or downloaded and checked against the manifest's SHA-256; +# accept {email, eula_sha256, owner_use, replace} -> {ok, state}: RECORDED, or QUEUED +# (offline); +# flush {} -> {ok, state}: a queued acceptance sent, if there is one (while the marker +# is there). +# One send at a time (LOCK_NAME, an flock in the state directory): accept and the timer's +# flush at once would each POST the queue; and each queued acceptance carries a request_id +# of its own (random), sent with every try, so one sent again after its answer was lost (a +# caller killed mid-POST) is one row at the license server, not two (migrations/0006). A request waits for it at most LOCK_SECS, well +# within the caller's own limit (owner_license.HELPER_SECS), then is refused as BUSY. The email reaches the license server, the queue +# and the record, and nothing else: no reply carries it but masked, no log line or error. Nothing here writes, renames or removes +# PROTECTED (the engine's license files, teaport#474 F1). +# +# Run as the sudoers line (packaging/deb/sudoers-sync) names it: +# /usr/bin/python3 /usr/lib/teaport/license_accept.py +# the root-owned copy the teaport-brain package ships, on the SYSTEM python, never the +# venv's (like login_apply.py). Standard library only. Tests run it in-process (handle()) +# against a pretend license server and a temporary tree (Box). +# +import fcntl +import hashlib +import json +import os +import pwd +import re +import secrets +import stat +import subprocess +import sys +import tempfile +import time +import unicodedata +import urllib.error +import urllib.request + +STATE_DIR = "/var/lib/teaport" +RECORD_PATH = STATE_DIR + "/eula-accepted.json" # install.sh's EULA_RECEIPT +QUEUE_PATH = STATE_DIR + "/eula-queued.json" +# Setup is unfinished while this is there: provisioning writes it at seal (beside the +# login's pending marker, Teaspoon-AI/teaport-appliance#3), the link helper removes it once +# the owner's acceptance is on the box's key (license_link.py). Nothing in this package +# writes it. +GATE_PATH = "/var/lib/teaport-owner/license-pending" +INSTALLED_MANIFEST = "/opt/teaport/manifest.json" +# The license server and the files it publishes: install.sh's own (its default manifest, +# https://get.teaspoon.tech/manifest/stable.json, whose access.api this is). +ORIGIN = "https://get.teaspoon.tech" +API = ORIGIN + "/api" +MANIFEST_BASE = ORIGIN + "/manifest" +LINKED_PATH = STATE_DIR + "/license-link.json" # license_link.LINKED_PATH +LOCK_NAME = ".eula-accept.lock" +LOCK_SECS = 30 +# The owner's login is still to be made while this is there (login_apply.PENDING_PATH). +LOGIN_PENDING_PATH = "/var/lib/teaport-owner/pending" +BRAIN_UNIT = "teaport-brain.service" +TOOL_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"} +OWNER_USES = ("personal", "business") +APPLIANCE_ID = "/etc/appliance-id" +MACHINE_ID = "/etc/machine-id" +BUILD_RECORD = "/opt/teaport/brain/teaport-build.json" +# The engine's license files (teaport#474 F1): no root helper the run user reaches writes, +# renames or removes them. The same tuple in every one of them (tests hold them equal). +PROTECTED = ("/etc/teaport/license.json", "/etc/teaport/license-revocations.json", + "/etc/teaport/license-link.secret") +CHANNELS = ("stable", "beta") +MAX_REQUEST = 4096 +MAX_MANIFEST = 1 << 20 +MAX_TEXT = 1 << 20 +NET_SECS = 20 +# The license server's own rule for an email (worker/src/index.js accept()), so a typo is +# the page's to show, not a queued request the server later refuses. +EMAIL = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$") +CONTROL = re.compile(r"[\x00-\x1f\x7f]") +ACCEPTANCE_ID = re.compile(r"[A-Za-z0-9_-]{8,64}") +# status's answers. +PENDING, QUEUED, RECORDED, NOT_OFFERED = "pending", "queued", "recorded", "not_offered" +# Why a request was refused, as codes; owner_license.py turns them into the words people see. +REFUSED, ACCEPTED, EMAIL_BAD, CHANGED, UNAVAILABLE, DROPPED, FAILED, USE, BUSY = ( + "refused", "accepted", "email", "changed", "unavailable", "dropped", "failed", "use", "busy") +# What each verb takes: nothing else, an acceptance id least of all. +FIELDS = {"status": set(), "text": set(), "accept": {"email", "eula_sha256", "owner_use", "replace"}, + "flush": set()} + + +class Refused(Exception): + """A request this helper does not do. `why` is one of the codes above.""" + + def __init__(self, text: str, why: str = REFUSED): + super().__init__(text) + self.why = why + + +def guard(path: str) -> str: + """`path`, unless it is one of PROTECTED, by name or through a link (teaport#474 F1).""" + if os.path.abspath(path) in PROTECTED or os.path.realpath(path) in PROTECTED: + raise Refused(f"{path} is the engine's license, which this helper never writes") + return path + + +class Marker: + """Provisioning's marker: there, and root's alone (login_apply.Marker's rule): one in a + directory the run user can write, or a file that is not root's or is a link, is none.""" + + def __init__(self, path: str = GATE_PATH, owner: int = 0): + self.path, self.owner = path, owner + + def _roots(self, st: os.stat_result, kind) -> bool: + return kind(st.st_mode) and st.st_uid == self.owner and not st.st_mode & 0o022 + + def present(self) -> bool: + try: + directory = os.lstat(os.path.dirname(self.path)) + marker = os.lstat(self.path) + except FileNotFoundError: + return False + return self._roots(directory, stat.S_ISDIR) and self._roots(marker, stat.S_ISREG) + + +def _no_redirect(): + """An opener that follows no redirect: every URL here is https and named by the + manifest, and a redirect would let whoever answers send the email elsewhere.""" + class Refuse(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + return urllib.request.build_opener(Refuse) + + +def fetch(url: str, body: dict | None = None, limit: int = MAX_MANIFEST) -> tuple[int, bytes]: + """GET `url`, or POST `body` as JSON: (status, at most `limit` bytes of the answer); + status 0 when there is no answer (offline, a timeout, a URL that is not https).""" + if not url.startswith("https://"): + return 0, b"" + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(url, data=data, method="POST" if data is not None else "GET", + headers={"content-type": "application/json", + "user-agent": "teaport-license-accept"}) + try: + with _no_redirect().open(req, timeout=NET_SECS) as r: # noqa: S310 -- https only + return r.status, r.read(limit + 1)[:limit] + except urllib.error.HTTPError as e: + try: + return e.code, e.read(limit) + except OSError: + return e.code, b"" + except (OSError, ValueError): + return 0, b"" + + +class Box: + """Where this helper reads and writes, and how it reaches the network (a test's own).""" + + def __init__(self, state_dir: str = STATE_DIR, gate: Marker | None = None, + installed_manifest: str = INSTALLED_MANIFEST, appliance_id: str = APPLIANCE_ID, + machine_id: str = MACHINE_ID, build_record: str = BUILD_RECORD, + net=fetch, now=time.time, login: Marker | None = None, + caller: int | None = None, run_uid=None, token=lambda: secrets.token_urlsafe(18)): + """`login`: the login's pending marker; `caller`: SUDO_UID as sudo set it (None: + root's own call); `run_uid`: the brain's user's uid, or a function giving it (None: + it cannot be told). The defaults are a test's: root's own call.""" + self.state_dir, self.gate = state_dir, gate or Marker() + self.login = login or Marker(LOGIN_PENDING_PATH) + self.caller, self._run_uid = caller, run_uid + self.token = token # a queued acceptance's own request_id (send()) + self.record = os.path.join(state_dir, os.path.basename(RECORD_PATH)) + self.queue = os.path.join(state_dir, os.path.basename(QUEUE_PATH)) + self.installed_manifest, self.appliance_id = installed_manifest, appliance_id + self.machine_id, self.build_record = machine_id, build_record + self.linked = os.path.join(state_dir, os.path.basename(LINKED_PATH)) + self.lock = os.path.join(state_dir, LOCK_NAME) + self.net, self.now = net, now + + def text_path(self, version: str) -> str: + return os.path.join(self.state_dir, f"EULA-v{version}.txt") + + def run_uid(self) -> int | None: + return self._run_uid() if callable(self._run_uid) else self._run_uid + + def by_run_user(self) -> bool: + """The request is the run user's (its sudoers line), or cannot be told from one: + SUDO_UID is set, not root's, and is the brain's user's or that cannot be told.""" + if self.caller is None or self.caller == 0: + return False + run = self.run_uid() + return run is None or self.caller == run + + @classmethod + def real(cls) -> "Box": + raw = os.environ.get("SUDO_UID") # sudo sets it itself: the run user cannot + return cls(caller=int(raw) if raw and raw.isdigit() else None, run_uid=_run_uid) + + +def _run_uid() -> int | None: + """The brain's User='s uid (as sudoers-sync reads it), None when it cannot be told.""" + try: + p = subprocess.run(["systemctl", "show", "-p", "User", "--value", BRAIN_UNIT], + capture_output=True, text=True, timeout=10, env=TOOL_ENV) + return pwd.getpwnam(p.stdout.strip()).pw_uid if p.returncode == 0 and p.stdout.strip() else None + except (OSError, KeyError, subprocess.SubprocessError): + return None + + +# ------------------------------------------------------------------ files + +def _read_json(path: str, limit: int = MAX_MANIFEST) -> dict | None: + """A JSON object from a regular file (not a link), else None.""" + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + return None + data = json.loads(f.read(limit + 1)[:limit]) + except (OSError, ValueError): + return None + return data if isinstance(data, dict) else None + + +def _read_text(path: str) -> str | None: + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "rb") as f: + return f.read(MAX_TEXT + 1)[:MAX_TEXT].decode("utf-8") if stat.S_ISREG(os.fstat(f.fileno()).st_mode) else None + except (OSError, ValueError): + return None + + +def write_file(path: str, data: bytes, mode: int) -> None: + """`data` into `path`, whole or not at all: a temporary file of root's own in the same + directory (made root's 0755 if it is not there), at `mode` before a byte is written, + synced, renamed into place, and the directory synced.""" + guard(path) + directory = os.path.dirname(path) + os.makedirs(directory, mode=0o755, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=directory, prefix="." + os.path.basename(path) + ".") + try: + os.fchmod(fd, mode) + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + dfd = os.open(directory, os.O_RDONLY) + try: + os.fsync(dfd) + finally: + os.close(dfd) + + +def _remove(path: str) -> None: + guard(path) + try: + os.unlink(path) + except FileNotFoundError: + pass + + +# ------------------------------------------------------------------ what the box is + +def device_id(box: Box) -> str: + """Which device the acceptance names (the module comment): the appliance serial's hash + on a factory box, the machine id's elsewhere; "" when the box has neither.""" + serial = _read_text(box.appliance_id) + if serial is not None: + serial = serial[:-1] if serial.endswith("\n") else serial + if serial and not re.search(r"\s", serial) and not CONTROL.search(serial): + return hashlib.sha256(f"teaport-appliance:{serial}".encode()).hexdigest() + machine = re.sub(r"\s", "", _read_text(box.machine_id) or "") + return hashlib.sha256(f"teaport-device:{machine}".encode()).hexdigest() if machine else "" + + +def installer(box: Box) -> str: + """Where the acceptance was made, for its `installer` (the license server's rule: at + most 64 of [A-Za-z0-9._:+-]): the setup page, and the brain's revision.""" + rev = (_read_json(box.build_record) or {}).get("revision") + if isinstance(rev, str) and re.fullmatch(r"[0-9a-f]{7,40}(-dirty)?", rev): + return f"setup:git:{rev}"[:64] + return "setup:unknown" + + +def _eula_of(manifest: dict) -> dict | None: + """{channel, version, url, sha256} of a manifest's license; None when it has no released + license, or names a license server other than API or a text off ORIGIN.""" + e = (manifest.get("engine") or {}).get("eula") if isinstance(manifest.get("engine"), dict) else None + api = (manifest.get("access") or {}).get("api") if isinstance(manifest.get("access"), dict) else None + if not isinstance(e, dict) or not isinstance(api, str) or api.rstrip("/") != API: + return None # another license server, whoever wrote the manifest: no license here + version, url, sha = e.get("version"), e.get("url"), e.get("sha256") + if not (isinstance(version, str) and re.fullmatch(r"[A-Za-z0-9._-]{1,32}", version) + and isinstance(url, str) and url.startswith(ORIGIN + "/") and "TODO" not in url + and isinstance(sha, str) and re.fullmatch(r"[0-9a-f]{64}", sha)): + return None + channel = manifest.get("channel") if manifest.get("channel") in CHANNELS else "stable" + return {"channel": channel, "version": version, "url": url, "sha256": sha} + + +def current(box: Box) -> dict | None: + """The license to accept now (_eula_of): the channel's manifest, else (offline) the + installed one's.""" + installed = _read_json(box.installed_manifest) or {} + channel = installed.get("channel") if installed.get("channel") in CHANNELS else "stable" + status, data = box.net(f"{MANIFEST_BASE}/{channel}.json") + if status == 200: + try: + fresh = _eula_of(json.loads(data)) + except ValueError: + fresh = None + if fresh: + return fresh + return _eula_of(installed) + + +def license_text(box: Box, eula: dict) -> str | None: + """The text of `eula`, checked against its SHA-256: the copy on the box, else downloaded + and kept there (0644, as install.sh keeps it); None when neither can be had.""" + path = box.text_path(eula["version"]) + try: + with open(path, "rb") as f: + data = f.read(MAX_TEXT + 1) + except OSError: + data = None + if data is None or hashlib.sha256(data).hexdigest() != eula["sha256"]: + status, data = box.net(eula["url"], limit=MAX_TEXT) + if status != 200 or hashlib.sha256(data).hexdigest() != eula["sha256"]: + return None + write_file(path, data, 0o644) + try: + return data.decode("utf-8") + except ValueError: + return None + + +# ------------------------------------------------------------------ the record + +def recorded(box: Box) -> dict | None: + """The acceptance on the box: a receipt with an acceptance id that is not the factory's + (install.sh's, or this helper's), else None.""" + r = _read_json(box.record) + if not r or r.get("method") == "factory": + return None + aid = r.get("acceptance_id") + return r if isinstance(aid, str) and ACCEPTANCE_ID.fullmatch(aid) and not aid.startswith("maker-") else None + + +def valid_email(email) -> bool: + """An address the license server takes (its own rule, worker/src/index.js accept()): at + most 254 bytes of UTF-8 (both count bytes); no control or format character anywhere + (Unicode Cc, Cf: a zero-width space, a right-to-left override; also ZWNJ and ZWJ, which + some Persian and Indic domains need: refused all the same, a trade-off accepted); and as + NFKC leaves it (a fullwidth letter, a Kelvin sign, a Roman numeral would read as another + address's, and the mask's IDNA step would fold them): what would make one address look + like another.""" + if not isinstance(email, str): + return False + e = email.strip() + return (len(e.encode("utf-8", "surrogatepass")) <= 254 and bool(EMAIL.match(e)) + and not any(unicodedata.category(c) in ("Cc", "Cf", "Cs") for c in email) + and unicodedata.normalize("NFKC", email) == email) + + +def mask(email) -> str | None: + """An email as the page shows it, to tell the owner whose it is without saying it whole + to the run user: the whole domain, in its ASCII form (IDNA, punycode: a lookalike letter + from another script shows as xn--), and of the part before it the first and last + character, with one * for each in between, so its length shows (owner@example.com: + o***r@example.com; ox@ex.com: o*@ex.com). A hint, not a proof: another address with the + same first and last character, length and domain looks the same, and support re-links + a box whose acceptance is not its owner's (docs: security.md).""" + if not isinstance(email, str) or "@" not in email: + return None + local, _, domain = email.strip().rpartition("@") + try: + domain = domain.encode("idna").decode("ascii") + except UnicodeError: + domain = "".join(c if c.isascii() else "?" for c in domain) + if len(local) == 1: + return f"*@{domain}" # its one character would be all of it + if len(local) == 2: + return f"{local[0]}*@{domain}" + return f"{local[0]}{'*' * (len(local) - 2)}{local[-1]}@{domain}" + + +def linked(box: Box, aid: str) -> bool: + """`aid` is on the box's key already (license_link.py's record of the link).""" + done = _read_json(box.linked) or {} + return done.get("linked") is True and done.get("acceptance_id") == aid + + +def state(box: Box) -> str: + """QUEUED while an acceptance waits to be sent during setup, even one in place of the + record (the newer one), else RECORDED, PENDING or NOT_OFFERED.""" + if box.gate.present() and _read_json(box.queue): + return QUEUED + if recorded(box): + return RECORDED + return PENDING if box.gate.present() else NOT_OFFERED + + +def open_to(box: Box) -> bool: + """Who asks may accept here now: anyone while setup is unfinished (the marker), and an + administrator (sudo with their password, or root) at any time: the owner holding the box + puts their own acceptance on it (support's re-link: possession outranks any record).""" + return box.gate.present() or not box.by_run_user() + + +def replaceable(box: Box) -> bool: + """The acceptance on the box may still be replaced (accept with replace), by whoever asks: + this helper's, recorded or queued. For the run user, only while setup is unfinished, + before its link is made and while the owner's login is still to be made; for an + administrator, at any time (open_to).""" + rec = recorded(box) + if not box.by_run_user(): + return rec is None or rec.get("method") == "setup" + if not box.gate.present() or not box.login.present(): + return False + if rec: + return rec.get("method") == "setup" and not linked(box, rec["acceptance_id"]) + return _read_json(box.queue) is not None + + +def status(box: Box) -> dict: + got = state(box) + who = (recorded(box) or {}).get("email") if got == RECORDED else (_read_json(box.queue) or {}).get("email") + return {"state": got, "email": mask(who) if got in (QUEUED, RECORDED) else None, + "replaceable": got in (QUEUED, RECORDED) and replaceable(box)} + + +class _Locked: + """One send at a time (the module comment): an flock on root's own file in the state + directory, held until the block ends. A second one waits for the first, at most `wait` + seconds: then BUSY, said as "busy, try again".""" + + def __init__(self, box: Box, wait: float | None = None): + self.path, self.fd, self.wait = guard(box.lock), None, LOCK_SECS if wait is None else wait + + def __enter__(self): + os.makedirs(os.path.dirname(self.path), mode=0o755, exist_ok=True) + self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) + deadline = time.monotonic() + self.wait + while True: + try: + fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + return self + except BlockingIOError: + if time.monotonic() >= deadline: + os.close(self.fd) + raise Refused("another acceptance is being sent: try again in a moment", BUSY) from None + time.sleep(0.2) + + def __exit__(self, *exc): + os.close(self.fd) # the lock goes with it + + +def send(box: Box) -> str: + """The queued acceptance, sent to API: RECORDED (the record written, the queue gone), + QUEUED (no answer, or one that may change: it waits), or DROPPED (refused for good: the + queue goes, and the step is offered again). The caller holds _Locked.""" + q = _read_json(box.queue) + if not q: + return RECORDED if recorded(box) else PENDING + body = {"channel": q.get("channel"), "eula_version": q.get("version"), "eula_sha256": q.get("sha256"), + "email": q.get("email"), "use": "personal", "owner_use": q.get("owner_use"), + "device_id": q.get("device_id") or None, "method": "tty", "installer": q.get("installer")} + # The queue's own id, the same at every send of it: a send whose answer was lost (the + # caller killed mid-POST, the network) and is sent again records no second row. + if isinstance(q.get("request_id"), str): + body["request_id"] = q["request_id"] + status, data = box.net(f"{API}/accept", body) + try: + answer = json.loads(data) if status else {} + except ValueError: + answer = {} + aid = answer.get("acceptance_id") if isinstance(answer, dict) else None + if status == 200 and isinstance(aid, str) and ACCEPTANCE_ID.fullmatch(aid) and not aid.startswith("maker-"): + rec = {"version": q["version"], "sha256": q["sha256"], + "date": time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime(box.now())), + "method": "setup", "acceptance_id": aid, "recorded_with": API, + "email": q["email"], "use": "personal", "owner_use": q.get("owner_use"), + "channel": q["channel"]} + # The record first, then the queue: a cut between the two leaves both, and the next + # flush sends the queue again, which its request_id makes the same acceptance. + write_file(box.record, (json.dumps(rec) + "\n").encode(), 0o600) + _remove(box.queue) + return RECORDED + if status in (400, 404, 409): # the license changed meanwhile, or a request it refuses + _remove(box.queue) + return DROPPED + return QUEUED + + +def text(box: Box) -> dict: + if not open_to(box): + raise Refused("setup is finished on this box: the license is accepted through it no more", NOT_OFFERED) + eula = current(box) + body = license_text(box, eula) if eula else None + if body is None: + raise Refused("the license text is not on this box, and it cannot be fetched now", UNAVAILABLE) + return {"version": eula["version"], "sha256": eula["sha256"], "text": body} + + +def accept(box: Box, req: dict) -> dict: + with _Locked(box): + if not open_to(box): + raise Refused("setup is finished on this box: the license is accepted through it no more", NOT_OFFERED) + replace = req.get("replace", False) + if replace not in (True, False): + raise Refused("replace is true or false") + if recorded(box) or _read_json(box.queue): + if not replace: + raise Refused("the license is already accepted on this box", ACCEPTED) + if not replaceable(box): + raise Refused("the license's acceptance on this box is no longer replaced from here: " + "it is linked to the box's key, or the owner's login is made", ACCEPTED) + email = req.get("email") + if not valid_email(email): + raise Refused("that is not an email address", EMAIL_BAD) + if req.get("owner_use") not in OWNER_USES: + raise Refused("owner_use: personal or business", USE) + eula = current(box) + if not eula or license_text(box, eula) is None: + raise Refused("the license text is not on this box, and it cannot be fetched now", UNAVAILABLE) + if req.get("eula_sha256") != eula["sha256"]: + raise Refused("the license shown is not the current one: read it again", CHANGED) + q = {"email": email.strip(), "channel": eula["channel"], "version": eula["version"], + "sha256": eula["sha256"], "owner_use": req["owner_use"], "device_id": device_id(box), + "installer": installer(box), "request_id": box.token(), + "queued_at": int(box.now())} + # Replaced (checked above): the queue takes its place, and the record stays until the + # new one is recorded (send() writes it over then): a send that fails, waits or is + # dropped leaves the box's receipt as it was, which install.sh and `teaport update` + # get their tokens with. + write_file(box.queue, (json.dumps(q) + "\n").encode(), 0o600) + got = send(box) + if got == QUEUED and not box.gate.present(): + # An administrator's, after setup: no timer sends a queue then (flush()), so it + # is sent now or not at all. + _remove(box.queue) + raise Refused("the license server cannot be reached now: try again online", UNAVAILABLE) + if got == DROPPED: + return {"ok": False, "why": DROPPED} + return {"ok": True, "state": got} + + +def flush(box: Box) -> dict: + """The queued acceptance, sent; only while setup is unfinished, as a queue is written only + then (and the marker goes only once its acceptance is recorded and linked): a queue found + without it was not this helper's.""" + with _Locked(box): + if not box.gate.present(): + return {"ok": True, "state": RECORDED if recorded(box) else NOT_OFFERED, "sent": False} + queued = _read_json(box.queue) is not None + got = send(box) + return {"ok": got != DROPPED, "state": got, "sent": queued, + **({"why": DROPPED} if got == DROPPED else {})} + + +def handle(box: Box, verb: str, req) -> dict: + """One request: check it, do it, say how it went. Raises Refused for anything else.""" + if not isinstance(req, dict): + raise Refused("the request must be a JSON object") + if verb not in FIELDS: + raise Refused(f"unknown request {verb!r}") + extra = set(req) - FIELDS[verb] + if extra: + # An acceptance id above all: this helper records the one the license server + # returns, never one it is given. + raise Refused(f"{verb} takes no {', '.join(sorted(extra))}") + if verb == "status": + return status(box) + if verb == "text": + return text(box) + if verb == "accept": + return accept(box, req) + return flush(box) + + +def _reply(obj: dict) -> None: + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + +def main(argv: list[str] | None = None, box: Box | None = None) -> int: + argv = sys.argv[1:] if argv is None else argv + if box is None and os.geteuid() != 0: + _reply({"refused": "run as root, through the sudoers line", "why": REFUSED}) + return 2 + if len(argv) != 1: + _reply({"refused": "usage: license_accept.py (the request as JSON on stdin)", "why": REFUSED}) + return 2 + try: + data = sys.stdin.read(MAX_REQUEST + 1) if not sys.stdin.isatty() else "" + if len(data) > MAX_REQUEST: + raise Refused("the request is too long") + try: + req = json.loads(data) if data.strip() else {} + except ValueError: + raise Refused("the request is not JSON") from None + reply = handle(box or Box.real(), argv[0], req) + except Refused as e: + _reply({"refused": str(e), "why": e.why}) + return 2 + except Exception as e: # noqa: BLE001 -- by its type alone: an exception's text can quote the email + sys.stderr.write(f"license_accept: {type(e).__name__}\n") + _reply({"ok": False, "why": FAILED}) + return 1 + if argv[0] == "flush" and reply.get("sent"): + sys.stderr.write(f"license_accept: the queued acceptance: {reply.get('state')}\n") # the timer's journal + _reply(reply) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/brain/teaport_brain/license_key.py b/brain/teaport_brain/license_key.py new file mode 100644 index 00000000..9e014279 --- /dev/null +++ b/brain/teaport_brain/license_key.py @@ -0,0 +1,892 @@ +# +# teaport — the box's engine license key (teaport#474 I1): asks the license server for it +# (POST /license), renews it, and installs one a customer got by hand. The one writer of +# /etc/teaport/license.json, and of /etc/teaport/license-link.secret at a factory box's first +# issue. Root only: install.sh runs it from its checkout after the engine download (a full +# run, --only engine, --only license), teaport-license-renew.timer runs the package's copy +# (/usr/lib/teaport/license_key.py) every day, and teaport update starts that timer's +# service after every run. No sudoers line reaches it: the run user (the agent included) +# cannot run it as root. +# +# What it sends: ids only, never audio, transcripts or conversations (docs/engine-license-data.md): +# - a first key: {acceptance_id, device} for an acceptance made with install.sh (a personal +# key; a licensed acceptance is refused by the server, its key comes by hand), or +# {maker_id, device} on a factory box, from the maker receipt (an appliance key); +# - a renewal: {license_id, device}, from the key the box holds. A personal key gets another +# year, an appliance key is signed again under the server's current key. +# `device` is `voxtral --device-id`, run as the engine's user with /etc/teaport/engine.env +# (CUDA_VISIBLE_DEVICES decides which GPU's UUID it hashes), as the engine computes it. +# +# What it writes: +# - license.json: {payload, signature} and nothing else (the engine's strict parser refuses +# any other field, link_secret above all), root: 0640, whole or +# not at all (a temporary file beside it, synced, renamed). Every new key is staged and +# checked first, by the engine itself (`voxtral --license-status --license-file`, as the +# engine's user): one the engine refuses never replaces a key it accepts (KEPT_VALID: a +# key signed under a key this engine does not trust yet, say), and goes in only when the +# box holds no key the engine accepts (before the key ceremony no key verifies, and +# under warn an unverified key is harmless). A symbolic link at license.json is a key +# installed by hand, whatever it points to: never replaced here; +# - license-link.secret: the link secret a factory first issue (or a move of the key to a +# newer maker record) answers beside the document, root:root 0600 from the moment the +# file exists (it is created with that mode, before a byte is written), whole or not at +# all. A factory first issue that answers none is a failed provisioning (FATAL: install.sh +# dies, the box is provisioned again, never sealed): no file is written. A renewal never +# touches the file: every link rotates the secret, and license_link.py owns it after the +# first issue. The secret is never printed, logged or put in the status; +# - STATUS_NAME in the state directory, root's 0600: what the last ask got, and on a +# factory box which maker record's secret this box wrote, for which key, and the +# secret's SHA-256 (the binding), written before the secret itself: a re-ask of that +# record (which answers no secret) is told from a failed provisioning by it, even after a +# crash between the writes. PUBLIC_NAME beside it, 0644: the same without the binding, +# for `teaport status` and `teaport doctor`. Both inside the lock; +# - nothing else: no other path, whatever an answer says. +# The owner's acceptance is linked to an appliance key by license_link.py (its timer), never +# from here. +# +# What it never does: delete a key (a refused renewal keeps the key the box has, which works +# to its expiry; the engine decides), replace a commercial key (one a customer installed by +# hand: renewed by Teaspoon AI, never here), or send anything to any other server than API. +# +# The answers it handles (worker/src/index.js, license()): +# 200: written as above (the device id changed under a key the engine still accepts: nothing +# is asked; a transient misread of the GPU never takes a personal key's device slot). 503 license_unavailable (the server cannot sign yet): nothing +# written; the engine's build default is warn, so the box runs without a key until a later +# ask. 409 eula_changed on a renewal: asked again with the receipt's acceptance, which +# renews the key once it is of the current license (install.sh asked for it again); else +# the key is kept, and `teaport status` asks for the license to be accepted again. 403 (device_cap, revoked, released, licensed_use, ...): +# nothing written, the server's message said with its licensing contact. 404 +# unknown_license / 403 released on a renewal: a first key is asked for, from the receipt. +# No answer, 429 or 5xx: asked again at the next run. +# +# Verbs (argv[1]); each prints one JSON object on stdout and exits 0, FATAL_EXIT for a failed +# provisioning, 2 for a refused request (install: the file is not a valid license here): +# fetch [--run-user U] [--engine BIN] [--engine-env FILE] [--state DIR] +# install --file PATH [--run-user U] [--engine BIN] [--engine-env FILE] [--state DIR] +# check --file PATH [...]: install's check alone, nothing written (CANNOT_CHECK_EXIT when +# this engine cannot check a license file) +# +# The SYSTEM python3, standard library only. Tests run it in-process (fetch(), install()) +# against a pretend license server and a temporary tree (Box). +# +import fcntl +import hashlib +import json +import os +import pwd +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request + +ORIGIN = "https://get.teaspoon.tech" # license_accept.ORIGIN, license_link.ORIGIN +API = ORIGIN + "/api" # license_accept.API, license_link.API +LICENSE_PATH = "/etc/teaport/license.json" +SECRET_PATH = "/etc/teaport/license-link.secret" +STATE_DIR = "/var/lib/teaport" +RECEIPT_NAME = "eula-accepted.json" # install.sh's EULA_RECEIPT +STATUS_NAME = "license-key.json" # root's 0600: with the factory binding +PUBLIC_NAME = "license-key-status.json" # 0644: the same without it +LOCK_NAME = ".license-key.lock" +ENGINE = "/opt/teaport/bin/voxtral" +ENGINE_ENV = "/etc/teaport/engine.env" +ENGINE_UNIT = "teaport-engine.service" +MAX_LICENSE = 64 * 1024 # the engine's own limit +NET_SECS = 30 +TOOL_SECS = 60 +LOCK_SECS = 120 +FATAL_EXIT = 3 +CANNOT_CHECK_EXIT = 5 +TOOL_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"} +# The only values the engine takes as written (anything else fails closed: on). +MODES = ("off", "warn", "on") +LICENSE_ID = re.compile(r"[A-Z0-9][A-Z0-9-]{3,39}") +TPDEV2 = re.compile(r"tpdev2-[0-9a-f]{32}") +ACCEPTANCE_ID = re.compile(r"[A-Za-z0-9_-]{8,64}") +MAKER_ID = re.compile(r"maker-[A-Za-z0-9_-]{24}") +SECRET = re.compile(r"[A-Za-z0-9_-]{43}") # license_link.SECRET, without its newline +SIGNATURE = re.compile(r"[A-Za-z0-9+/]+={0,2}") +SERVER_CODE = re.compile(r"[a-z_]{1,40}") +ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") +TIERS = ("personal", "commercial", "appliance") +# Who may be named in a message: the server's licensing contact, an email address of its own. +CONTACT = re.compile(r"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}") + +# States (the reply's and STATUS_NAME's "state"). +ISSUED, RENEWED, KEPT, KEPT_VALID, NONE, UNAVAILABLE, REFUSED, EULA_CHANGED, UNREACHABLE, FAILED, FATAL, \ + INSTALLED, VALID = ("issued", "renewed", "kept", "kept_valid", "none", "unavailable", "refused", + "eula_changed", "unreachable", "failed", "fatal", "installed", "valid") +# The factory binding (STATUS_NAME): kept from run to run, whatever a run's outcome. +BINDING = ("maker_id", "secret_for", "secret_sha256") +PUBLIC = ("state", "why", "message", "contact", "license_id", "tier", "expires_at", "eula_version", "mode_problem") + + +class Refused(Exception): + """A request this does not do, or a file that is not a license here.""" + + +class CannotCheck(Refused): + """This engine cannot check a license file (one before license keys, or none).""" + + +class Box: + """Where this reads and writes, as whom the engine runs, and how it reaches the license + server and the engine (a test's own).""" + + def __init__(self, license_path: str = LICENSE_PATH, secret_path: str = SECRET_PATH, + state: str = STATE_DIR, engine: str = ENGINE, engine_env: str = ENGINE_ENV, + run_user: str | None = None, net=None, tool=None, now=time.time, + root: bool | None = None, log=None): + self.license_path, self.secret_path, self.state = license_path, secret_path, state + self.engine, self.engine_env, self.now = engine, engine_env, now + self.run_user = run_user if run_user is not None else engine_user() + self.net = net or post + self.tool = tool or run_tool + self.root = (os.geteuid() == 0) if root is None else root + self.log = log or (lambda line: sys.stderr.write(f"license_key: {line}\n")) + + @property + def receipt(self) -> str: + return os.path.join(self.state, RECEIPT_NAME) + + @property + def status_path(self) -> str: + return os.path.join(self.state, STATUS_NAME) + + @property + def public_path(self) -> str: + return os.path.join(self.state, PUBLIC_NAME) + + def gid(self) -> int: + """The engine user's primary group: license.json's group (0 for root, or a user that + is not there).""" + try: + return pwd.getpwnam(self.run_user).pw_gid + except (KeyError, TypeError): + return 0 + + +def engine_user(run=subprocess.run) -> str: + """teaport-engine.service's User= ("root" when it names none, or cannot be read).""" + try: + p = run(["systemctl", "show", "-p", "User", "--value", ENGINE_UNIT], + capture_output=True, text=True, timeout=10, env=TOOL_ENV) + return (p.stdout.strip() if p.returncode == 0 else "") or "root" + except (OSError, subprocess.SubprocessError): + return "root" + + +# ------------------------------------------------------------------------- the engine + +def env_file(path: str) -> dict: + """An EnvironmentFile as systemd reads it, for what the engine's checks see: KEY=VALUE + lines, the last assignment winning, whitespace around the key, the = and the value + dropped, and one pair of surrounding quotes removed. {} when it cannot be read.""" + out = {} + try: + with open(path, encoding="utf-8", errors="replace") as f: + text = f.read(1 << 20) + except OSError: + return out + for line in text.splitlines(): + line = line.strip() + if not line or line[0] in "#;" or "=" not in line: + continue + k, v = line.split("=", 1) + k, v = k.strip(), v.strip() + if not ENV_NAME.fullmatch(k): + continue + if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'": + v = v[1:-1] + out[k] = v + return out + + +def mode_problem(value: str | None) -> str | None: + """Why VOX_LICENSE_MODE's value is not one the engine takes as written; None when it is + (unset or empty is the build default).""" + if value is None or value == "" or value in MODES: + return None + return (f"VOX_LICENSE_MODE={value!r} is not off, warn or on: the engine fails closed to on, " + "and refuses to start without a valid license key") + + +def run_tool(box: Box, argv: list[str]) -> tuple[int, str, str]: + """`argv` as the engine's user, with the engine's environment (engine.env's values over + TOOL_ENV, nothing of this process's own). Python's own switch (subprocess's user, group + and extra_groups: the user's groups from the group database, as initgroups gives them, + video and render among them for the GPU) in the child, after the fork: engine.env (which + the run user's config page writes) reaches the engine through execve's environment + alone, never a root process's environment, and never an argv (/proc//cmdline).""" + env = {**TOOL_ENV, **env_file(box.engine_env)} + switch = {} + if box.root and box.run_user != "root": + try: + pw = pwd.getpwnam(box.run_user) + except KeyError: + return 127, "", f"the engine's user {box.run_user!r} does not exist" + switch = {"user": pw.pw_uid, "group": pw.pw_gid, + "extra_groups": os.getgrouplist(box.run_user, pw.pw_gid)} + try: + p = subprocess.run(list(argv), capture_output=True, text=True, timeout=TOOL_SECS, env=env, + stdin=subprocess.DEVNULL, cwd="/", **switch) + except (OSError, subprocess.SubprocessError) as e: + return 127, "", type(e).__name__ + return p.returncode, p.stdout, p.stderr + + +def engine_has(box: Box, flag: str) -> bool: + """The engine's --help lists `flag`. Asked first, every time: an engine release before + license keys is never handed a flag it does not know (one that took it for a run would + load its models beside the live engine's, on a box with no memory to spare).""" + rc, out, err = box.tool(box, [box.engine, "--help"]) + return re.search(rf"(?m)^\s+{re.escape(flag)}(\s|$)", out + err) is not None + + +NO_KEYS = "this engine release has no license keys (it predates them): there is no key to ask for" + + +def device_id(box: Box) -> tuple[str | None, str]: + """(this box's tpdev2 id, why not), as the engine computes it.""" + if not os.path.isfile(box.engine): + return None, f"no engine at {box.engine}" + if not engine_has(box, "--device-id"): + return None, NO_KEYS + rc, out, err = box.tool(box, [box.engine, "--device-id"]) + dev = out.strip() + if rc == 0 and TPDEV2.fullmatch(dev): + return dev, "" + last = "".join(ch for ch in (err.strip().splitlines() or [""])[-1] if ch.isprintable())[:200] + return None, (f"voxtral --device-id failed (exit {rc}){': ' + last if last else ''}: " + "an engine before license keys, or one that cannot read this box's identity") + + +def engine_status(box: Box, path: str | None = None) -> tuple[int, dict]: + """`voxtral --license-status [--license-file path]`: (exit status, its fields by name: + "Result", "Tier", ...). No "Result" field: an engine without license keys.""" + if not engine_has(box, "--license-status"): + return 2, {} + argv = [box.engine, "--license-status"] + (["--license-file", path] if path else []) + rc, out, _ = box.tool(box, argv) + fields = {} + for line in out.splitlines(): + k, sep, v = line.partition(":") + if sep and k and not k.startswith(" ") and k not in fields: + fields[k.strip()] = v.strip() + return rc, fields + + +def verdict(box: Box, path: str) -> tuple[str, dict]: + """The engine's verdict on the license file at `path`, on this box: ("valid" | "invalid" + | "unknown", its fields); unknown for an engine that cannot say.""" + rc, fields = engine_status(box, path) + if "Result" not in fields: + return "unknown", fields + return ("valid" if rc == 0 and fields["Result"].startswith("VALID") else "invalid"), fields + + +# ------------------------------------------------------------------------- files + +def _read_json(path: str, limit: int = MAX_LICENSE): + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + return None + data = f.read(limit + 1) + except OSError: + return None + if len(data) > limit: + return None + try: + return json.loads(data) + except ValueError: + return None + + +def held_key(box: Box) -> dict | None: + """The payload of the key the box holds ({} fields checked as the engine names them), or + None for no key, or a file that is not one.""" + doc = _read_json(box.license_path) + if not isinstance(doc, dict) or set(doc) != {"payload", "signature"}: + return None + p = doc["payload"] + if not isinstance(p, dict) or p.get("tier") not in TIERS: + return None + if not (isinstance(p.get("license_id"), str) and LICENSE_ID.fullmatch(p["license_id"])): + return None + if not (isinstance(p.get("device"), str) and TPDEV2.fullmatch(p["device"])): + return None + return p + + +def receipt(box: Box) -> tuple[str, str] | None: + """What a first key is asked with, from the box's receipt: ("maker_id", id) on a factory + box, ("acceptance_id", id) for an acceptance made with install.sh; None for none (no + receipt, or the owner's acceptance from setup: an appliance's key comes from its maker + record, never from its owner's personal acceptance).""" + r = _read_json(box.receipt) + if not isinstance(r, dict): + return None + aid = r.get("acceptance_id") + if not isinstance(aid, str): + return None + if r.get("method") == "factory": + return ("maker_id", aid) if MAKER_ID.fullmatch(aid) else None + if r.get("method") == "setup" or aid.startswith("maker-") or not ACCEPTANCE_ID.fullmatch(aid): + return None + return "acceptance_id", aid + + +def _sync_dir(directory: str) -> None: + dfd = os.open(directory, os.O_RDONLY) + try: + os.fsync(dfd) + finally: + os.close(dfd) + + +def _write_new(path: str, data: bytes, mode: int, uid: int, gid: int, root: bool) -> None: + """`data` as `path`, whole or not at all: a new file beside it, created with `mode` (so it + has it before a byte is in it), given its owner, written, synced, renamed over `path`; + the directory synced.""" + directory = os.path.dirname(path) + tmp = os.path.join(directory, f".{os.path.basename(path)}.{os.getpid()}.{time.monotonic_ns()}") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode) + try: + os.fchmod(fd, mode) # the umask took nothing from it + if root: + os.fchown(fd, uid, gid) + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + os.fsync(fd) + os.close(fd) + fd = -1 + os.replace(tmp, path) + except BaseException: + if fd >= 0: + os.close(fd) + try: + os.unlink(tmp) + except OSError: + pass + raise + _sync_dir(directory) + + +STAGED = ".license.json.check" + + +def _staged(box: Box, data: bytes, directory: str | None = None) -> str: + """`data` as a new file beside license.json (root: 0640, so the engine's user + reads it as the engine will), for the engine to check before it goes in place; in + `directory` instead for a check alone.""" + staged = os.path.join(directory or os.path.dirname(box.license_path), STAGED) + _unstage(staged) # a stale one; _write_new's rename replaces it anyway + _write_new(staged, data, 0o640, 0, box.gid(), box.root) + return staged + + +def _unstage(staged: str) -> None: + """Best effort, in a finally: never masks the error the block raised.""" + try: + os.unlink(staged) + except OSError: + pass + + +SCRATCH_PREFIX = ".license-check." + + +def _sweep_scratch(box: Box) -> None: + """Remove check directories a killed run left in the state directory. Called under the + lock, which every check holds while its directory exists: any one there now is stale.""" + try: + names = os.listdir(box.state) + except OSError: + return + for name in names: + if name.startswith(SCRATCH_PREFIX): + shutil.rmtree(os.path.join(box.state, name), ignore_errors=True) + + +def put_license(box: Box, doc: dict, held_ok: bool) -> tuple[bool, dict]: + """{payload, signature}, nothing else, as license.json (root: 0640), once the + engine has checked it: in place when the engine accepts it, or when the box holds no key + it accepts (`held_ok` False); else not, the held key kept. (written, the engine's fields).""" + data = (json.dumps({"payload": doc["payload"], "signature": doc["signature"]}, indent=2, sort_keys=True) + + "\n").encode() + staged = _staged(box, data) + try: + v, fields = verdict(box, staged) + if v != "valid" and held_ok: + return False, fields + os.replace(staged, box.license_path) + _sync_dir(os.path.dirname(box.license_path)) + return True, fields + finally: + _unstage(staged) + + +def write_secret(box: Box, secret: str) -> None: + """The link secret, as license-link.secret: root:root 0600 from its creation.""" + _write_new(box.secret_path, (secret + "\n").encode("ascii"), 0o600, 0, 0, box.root) + + +def _secret_sha256(box: Box) -> str | None: + """SHA-256 of the secret the box holds (its file as written), None for none.""" + try: + fd = os.open(box.secret_path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + with os.fdopen(fd, "rb") as f: + return hashlib.sha256(f.read(256)).hexdigest() + + +def write_status(box: Box, reply: dict, binding: dict | None = None) -> None: + """The run's outcome: STATUS_NAME (0600) with the factory binding, the one given or the + one recorded before (every outcome carries it forward), and PUBLIC_NAME (0644) without.""" + public = {k: reply[k] for k in PUBLIC if reply.get(k) is not None} + public["at"] = int(box.now()) + prev = last_status(box) + bind = binding if binding is not None else {k: prev[k] for k in BINDING if isinstance(prev.get(k), str)} + try: + _write_new(box.status_path, (json.dumps({**public, **bind}) + "\n").encode(), 0o600, 0, 0, box.root) + _write_new(box.public_path, (json.dumps(public) + "\n").encode(), 0o644, 0, 0, box.root) + except OSError as e: + box.log(f"could not record the license key's state in {box.status_path}: {type(e).__name__}") + + +def last_status(box: Box) -> dict: + s = _read_json(box.status_path) + return s if isinstance(s, dict) else {} + + +class _Locked: + """One ask at a time (install.sh and the timer): an flock on root's file in the state dir.""" + + def __init__(self, box: Box): + self.path, self.fd = os.path.join(box.state, LOCK_NAME), None + + def __enter__(self): + self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) + deadline = time.monotonic() + LOCK_SECS + while True: + try: + fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + return self + except BlockingIOError: + if time.monotonic() >= deadline: + os.close(self.fd) + raise Refused("another ask for the license key is still running") from None + time.sleep(0.5) + + def __exit__(self, *exc): + os.close(self.fd) + + +# ------------------------------------------------------------------------- the server + +def _no_redirect(): + class Refuse(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + return urllib.request.build_opener(Refuse) + + +def post(url: str, body: dict) -> tuple[int, bytes]: + """POST `body` as JSON to an https `url`: (status, the answer); 0 for no answer. No + redirect is followed: the answer may carry the link secret.""" + if not url.startswith("https://"): + return 0, b"" + req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", + headers={"content-type": "application/json", + "user-agent": "teaport-license-key"}) + try: + with _no_redirect().open(req, timeout=NET_SECS) as r: # noqa: S310 -- https only + return r.status, r.read(MAX_LICENSE + 4096) + except urllib.error.HTTPError as e: + try: + return e.code, e.read(65536) + except OSError: + return e.code, b"" + except (OSError, ValueError): + return 0, b"" + + +def ask(box: Box, body: dict) -> tuple[int, dict]: + status_code, data = box.net(f"{API}/license", body) + try: + answer = json.loads(data) if status_code else {} + except ValueError: + answer = {} + return status_code, answer if isinstance(answer, dict) else {} + + +def _said(answer: dict) -> dict: + """The server's refusal, as this says it: its code, its message (printable, cut short) and + its licensing contact (its own field, else the address its message names).""" + code = answer.get("error") if isinstance(answer.get("error"), str) and SERVER_CODE.fullmatch(answer["error"]) else None + msg = answer.get("message") if isinstance(answer.get("message"), str) else "" + msg = "".join(ch for ch in msg if ch.isprintable())[:500] + contact = answer.get("contact") if isinstance(answer.get("contact"), str) else None + if not (contact and CONTACT.fullmatch(contact)): + found = CONTACT.search(msg) + contact = found.group(0) if found else None + out = {"why": code, "message": msg} + if contact: + out["contact"] = contact + ver = answer.get("eula_version") + if isinstance(ver, str) and re.fullmatch(r"[0-9A-Za-z._-]{1,32}", ver): + out["eula_version"] = ver + return out + + +def _document(answer: dict, device: str, tier: str, license_id: str | None = None) -> dict | None: + """{payload, signature} out of an answer, when it is a key of `tier` for `device` (and of + `license_id`, for a renewal); None when it is not.""" + p, sig = answer.get("payload"), answer.get("signature") + if not isinstance(p, dict) or not (isinstance(sig, str) and len(sig) < MAX_LICENSE and SIGNATURE.fullmatch(sig)): + return None + if p.get("tier") != tier or p.get("device") != device: + return None + if not (isinstance(p.get("license_id"), str) and LICENSE_ID.fullmatch(p["license_id"])): + return None + if license_id is not None and p["license_id"] != license_id: + return None + return {"payload": p, "signature": sig} + + +def _summary(doc: dict) -> dict: + p = doc["payload"] + return {"license_id": p["license_id"], "tier": p["tier"], "expires_at": p.get("expires_at")} + + +def _refusal(status_code: int, answer: dict, what: str) -> dict: + said = _said(answer) + if status_code == 503 and said["why"] == "license_unavailable": + return {"state": UNAVAILABLE, **said, + "message": "the license server cannot issue license keys yet: the engine runs without one " + "(its default is warn), and the box asks again every day"} + if status_code == 409 and said["why"] == "eula_changed": + return {"state": EULA_CHANGED, **said} + if status_code in (400, 403, 404, 409) and said["why"] not in (None, "conflict"): + return {"state": REFUSED, **said} + return {"state": UNREACHABLE, "why": said["why"] or (str(status_code) if status_code else "no_answer"), + "message": f"the license server could not be asked for {what} now " + f"(HTTP {status_code or 'none'}): the box asks again every day"} + + +# ------------------------------------------------------------------------- fetch + +def fetch(box: Box) -> dict: + """Ask for this box's key, or renew the one it holds (the module comment). The outcome is + recorded inside the lock: a run that follows sees it.""" + os.makedirs(box.state, exist_ok=True) + with _Locked(box): + reply = _fetch(box) + problem = mode_problem(env_file(box.engine_env).get("VOX_LICENSE_MODE")) + if problem: + reply["mode_problem"] = problem + write_status(box, reply) + if reply["state"] in (KEPT_VALID, FATAL): + box.log(reply["message"]) + return reply + + +def _kept_valid(held: dict, fields: dict, what: str) -> dict: + return {"state": KEPT_VALID, "why": "new_key_refused_here", "license_id": held["license_id"], + "tier": held["tier"], "expires_at": held.get("expires_at"), + "message": f"the license server's {what} is not one this engine accepts " + f"({fields.get('Result', 'no verdict')}): kept the key this box holds, which it accepts"} + + +def _write(box: Box, doc: dict, held: dict | None, held_ok: bool, ok: dict, what: str) -> dict: + """put_license, said: `ok` when the new key went in, KEPT_VALID when the held one stayed.""" + written, fields = put_license(box, doc, held_ok) + return ok if written else _kept_valid(held, fields, what) + + +def _fetch(box: Box) -> dict: + if os.path.islink(box.license_path): + # Installed by hand, as a link to wherever: whatever it points to is the owner's. + return {"state": KEPT, "why": "symlink", + "message": f"{box.license_path} is a symbolic link (a key installed by hand): never replaced here"} + device, why = device_id(box) + if not device: + if why == NO_KEYS: + return {"state": NONE, "why": "no_license_keys", "message": why} + return {"state": FAILED, "why": "no_device_id", "message": why} + held = held_key(box) + if held and held["tier"] == "commercial": + # A customer's key, installed by hand: Teaspoon AI renews it, by hand. + return {"state": KEPT, "why": "commercial", "license_id": held["license_id"], "tier": "commercial", + "expires_at": held.get("expires_at"), + "message": "a commercial license key, installed by hand: Teaspoon AI renews it"} + held_ok = bool(held) and verdict(box, box.license_path)[0] == "valid" + if held and held["device"] != device: + if held_ok: + # The engine accepts it here: this read of the device id was the odd one out (a GPU + # not ready, say). Nothing is asked: a misread never takes a device slot. + return {"state": KEPT, "why": "device_id_misread", "license_id": held["license_id"], + "tier": held["tier"], "expires_at": held.get("expires_at"), + "message": f"the device id read {device} this time, but the engine accepts the key this box " + "holds: kept, nothing asked"} + # The engine refuses it here too: a new device (a module or GPU swap). Read once more: + # only an id that reads the same twice is asked for. + again, _ = device_id(box) + if again != device: + return {"state": FAILED, "why": "device_id_unstable", "license_id": held["license_id"], + "message": "this box's device id read differently twice: nothing asked; the box asks again next time"} + held = None + first = receipt(box) + # A factory box asks with its maker record, a key or none: the first issue, a re-ask of + # the same record, or the move of the box's key to a newer record of it (provisioned again). + # A refusal of the record (past its time, revoked) leaves a box that holds its key to renew it. + if first and first[0] == "maker_id": + out = _appliance(box, first[1], device, held, held_ok) + if out["state"] in (ISSUED, RENEWED, KEPT_VALID, FATAL) or not held: + return out + box.log(f"the factory record gets no key now ({out.get('why')}): renewing the key the box holds") + first = None + if held: + status_code, answer = ask(box, {"license_id": held["license_id"], "device": device}) + if status_code == 200: + doc = _document(answer, device, held["tier"], held["license_id"]) + if doc is None: + return {"state": FAILED, "why": "bad_answer", "license_id": held["license_id"], + "message": "the license server answered something that is not this box's key: kept the one it has"} + return _write(box, doc, held, held_ok, {"state": RENEWED, **_summary(doc), "message": "renewed"}, + "renewed key") + said = _said(answer) + if status_code == 409 and said["why"] == "eula_changed" and first and first[0] == "acceptance_id": + # The key's own acceptance is of an older license; the box's receipt may hold the + # acceptance of the current one (install.sh asked again), which renews it (the + # Worker's personalLicense: the key the device holds under that person, another year). + status_code, answer = ask(box, {"acceptance_id": first[1], "device": device}) + if status_code == 200: + doc = _document(answer, device, "personal") + if doc is None: + return {"state": FAILED, "why": "bad_answer", "license_id": held["license_id"], + "message": "the license server answered something that is not this box's key: kept the one it has"} + return _write(box, doc, held, held_ok, {"state": RENEWED, **_summary(doc), + "message": "renewed under the acceptance of the current license"}, "renewed key") + said = _said(answer) + if not ((status_code == 404 and said["why"] == "unknown_license") + or (status_code == 403 and said["why"] == "released")): + out = _refusal(status_code, answer, "a renewal") + out.update(license_id=held["license_id"], tier=held["tier"], expires_at=held.get("expires_at")) + if out["state"] == EULA_CHANGED: + out["message"] = (f"the engine license changed{' to v' + out['eula_version'] if out.get('eula_version') else ''}: " + "run install.sh again to read and accept it; the key the box holds works until it expires") + elif out["state"] == REFUSED: + out["message"] = f"the license server refuses to renew this box's key: {out['message']}" + return out + box.log(f"the license server has no key {held['license_id']} for this box any more ({said['why']}): asking for a new one") + if not first: + return {"state": NONE, "why": "no_acceptance", + "message": "this box has no acceptance to ask for a key with (an appliance's key comes from " + "the factory; a commercial one is installed with install.sh --license-file)"} + status_code, answer = ask(box, {"acceptance_id": first[1], "device": device}) + if status_code == 200: + doc = _document(answer, device, "personal") + if doc is None: + return {"state": FAILED, "why": "bad_answer", + "message": "the license server answered something that is not a personal key for this box: nothing written"} + return _write(box, doc, held, held_ok, {"state": ISSUED, **_summary(doc), "message": "issued"}, "new key") + out = _refusal(status_code, answer, "a key") + if out["state"] == EULA_CHANGED: + out["message"] = (f"the engine license changed{' to v' + out['eula_version'] if out.get('eula_version') else ''} " + "since it was accepted on this box: run install.sh again to read and accept it") + return out + + +def _bind(box: Box, maker_id: str, lid: str, secret: str) -> None: + """Record, before the secret is written, that this box writes `maker_id`'s secret for key + `lid` (the binding, STATUS_NAME): what a later re-ask of the record is checked against. + Raises when it cannot be recorded: the secret is then not written either.""" + prev = last_status(box) + rec = {k: prev[k] for k in PUBLIC if prev.get(k) is not None} + rec.update(at=int(box.now()), maker_id=maker_id, secret_for=lid, + secret_sha256=hashlib.sha256((secret + "\n").encode("ascii")).hexdigest()) + _write_new(box.status_path, (json.dumps(rec) + "\n").encode(), 0o600, 0, 0, box.root) + + +def _bound(box: Box, maker_id: str, lid: str) -> bool: + """This box wrote `maker_id`'s secret for key `lid`, and holds it still, unchanged.""" + b = last_status(box) + return (b.get("maker_id") == maker_id and b.get("secret_for") == lid + and isinstance(b.get("secret_sha256"), str) and b["secret_sha256"] == _secret_sha256(box)) + + +def _appliance(box: Box, maker_id: str, device: str, held: dict | None, held_ok: bool) -> dict: + """A factory box's key, with its maker record (worker/src/index.js, applianceLicense).""" + status_code, answer = ask(box, {"maker_id": maker_id, "device": device}) + if status_code != 200: + return _refusal(status_code, answer, "this box's appliance key") + doc = _document(answer, device, "appliance") + if doc is None: + return {"state": FATAL, "why": "bad_answer", + "message": "the license server answered something that is not this box's appliance key: " + "nothing written; provision the box again"} + lid = doc["payload"]["license_id"] + secret = answer.get("link_secret") + if secret is None: + # Only the first issue (or a move) answers a secret. Without one, this is the same + # record asking again, which is fine only when this box wrote that record's secret + # for this key before and holds it still (the binding); anything else (someone asked + # with the maker id first, a key issued before the server kept secrets) is a box + # that cannot link its owner: a failed provisioning. + if _bound(box, maker_id, lid): + return _write(box, doc, held, held_ok, {"state": RENEWED, **_summary(doc), + "message": "signed again for this factory record (its link secret is the one already on the box)"}, + "re-signed key") + return {"state": FATAL, "why": "no_link_secret", "license_id": lid, + "message": "the license server issued this box's appliance key without its link secret " + "(the maker record had asked before): nothing written; this is a failed " + "provisioning: provision the box again, and never seal it"} + if not (isinstance(secret, str) and SECRET.fullmatch(secret)): + return {"state": FATAL, "why": "bad_link_secret", "license_id": lid, + "message": "the license server answered a link secret that is not one: nothing written; " + "provision the box again"} + # The binding, then the secret, then the key: a box holding the key without its secret + # could never link its owner, while a secret without the key is put right by asking + # again (the binding says it is this record's). The secret goes in whatever the engine + # says of the key: the server now knows only it. + try: + _bind(box, maker_id, lid, secret) + write_secret(box, secret) + except OSError as e: + # The server has minted the secret (and keeps only its hash): this box cannot link + # its owner without it, and the record answers no other. A failed provisioning. + return {"state": FATAL, "why": "secret_not_written", "license_id": lid, + "message": f"the license server minted this box's link secret, but it could not be written " + f"({type(e).__name__}: {e.strerror or 'error'}): this is a failed provisioning: " + "provision the box again, and never seal it"} + return _write(box, doc, held, held_ok, {"state": ISSUED, **_summary(doc), "message": "issued, with its link secret"}, + "appliance key") + + +# ------------------------------------------------------------------------- install + +def _read_file(path: str) -> bytes: + try: + with open(path, "rb") as f: + data = f.read(MAX_LICENSE + 1) + except OSError as e: + raise Refused(f"cannot read {path}: {e.strerror or type(e).__name__}") from None + if len(data) > MAX_LICENSE: + raise Refused(f"{path} is larger than 64 KiB: not a license file") + try: + doc = json.loads(data) + except ValueError: + raise Refused(f"{path} is not JSON: not a license file") from None + if not isinstance(doc, dict) or set(doc) != {"payload", "signature"}: + raise Refused(f"{path} is not a license file: it must hold exactly payload and signature") + return data + + +def install(box: Box, path: str, apply: bool = True) -> dict: + """A license file a customer got by hand (a commercial key), installed only once this + box's engine says it is valid here: copied as license.json beside it first (0640, so the + engine's user reads it as the engine will), checked with `voxtral --license-status + --license-file`, then renamed into place. A file the engine refuses changes nothing. + `apply` False: the check alone (install.sh's, before a run changes anything).""" + data = _read_file(path) + if not os.path.isfile(box.engine): + raise CannotCheck(f"no engine at {box.engine} to check the license file with") + os.makedirs(box.state, exist_ok=True) + with _Locked(box): + # A check alone stages in a directory of its own in the state directory (root's, + # 0750 to the engine's group), never in /etc/teaport: on a fresh box a run checks + # before anything has made /etc/teaport, and an aborted run leaves it as it was. + # A run killed with its directory in place (SIGKILL, a power cut) left it: gone now. + _sweep_scratch(box) + scratch = staged = None + try: + if not apply: + scratch = tempfile.mkdtemp(prefix=SCRATCH_PREFIX, dir=box.state) + os.chmod(scratch, 0o750) + if box.root: + os.chown(scratch, 0, box.gid()) + staged = _staged(box, data, scratch) + v, fields = verdict(box, staged) + if v == "unknown": + raise CannotCheck("this engine cannot check a license file (an engine before license keys): " + "update the engine first (install.sh --only engine)") + if v != "valid": + raise Refused(f"the engine refuses {path} on this box: {fields['Result']}" + + (f" (this device: {fields['This device']})" if fields.get("This device") else "")) + if apply: + os.replace(staged, box.license_path) + _sync_dir(os.path.dirname(box.license_path)) + finally: + # Whatever failed, and however: nothing left behind, and the error raised stays + # the one this says (a refusal is exit 2, not an OSError of the clean-up's). + if staged: + _unstage(staged) + if scratch: + shutil.rmtree(scratch, ignore_errors=True) + what = f"{fields.get('License id', '?')} ({fields.get('Tier', '?')}), expires {fields.get('Expires', '?')}" + if not apply: + return {"state": VALID, "license_id": fields.get("License id"), "message": f"valid here: {what}"} + reply = {"state": INSTALLED, "license_id": fields.get("License id"), "tier": fields.get("Tier"), + "message": f"installed: {what}"} + write_status(box, reply) + return reply + + +# ------------------------------------------------------------------------- main + +def _args(argv: list[str]) -> dict: + out, i = {}, 0 + names = {"--run-user": "run_user", "--engine": "engine", "--engine-env": "engine_env", + "--state": "state", "--file": "file"} + while i < len(argv): + if argv[i] not in names or i + 1 >= len(argv) or not argv[i + 1]: + raise Refused(f"unknown argument {argv[i]!r}") + out[names[argv[i]]] = argv[i + 1] + i += 2 + return out + + +def main(argv: list[str] | None = None, box: Box | None = None) -> int: + argv = sys.argv[1:] if argv is None else argv + def reply(obj, rc): + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + return rc + if box is None and os.geteuid() != 0: + return reply({"state": FAILED, "why": "not_root", "message": "run as root"}, 2) + try: + if not argv or argv[0] not in ("fetch", "install", "check"): + raise Refused("usage: license_key.py fetch|install|check [--file PATH] [--run-user U] [--engine BIN] " + "[--engine-env FILE] [--state DIR]") + a = _args(argv[1:]) + if box is None: + box = Box(**{k: v for k, v in a.items() if k != "file"}) + if argv[0] in ("install", "check"): + if not a.get("file"): + raise Refused(f"{argv[0]} needs --file PATH") + return reply(install(box, a["file"], apply=argv[0] == "install"), 0) + r = fetch(box) + return reply(r, FATAL_EXIT if r["state"] == FATAL else 0) + except CannotCheck as e: + return reply({"state": REFUSED, "why": "cannot_check", "message": str(e)}, CANNOT_CHECK_EXIT) + except Refused as e: + return reply({"state": REFUSED, "why": "refused", "message": str(e)}, 2) + except Exception as e: # noqa: BLE001 -- by its type alone: an answer may hold the secret + return reply({"state": FAILED, "why": "error", "message": type(e).__name__}, 1) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/brain/teaport_brain/license_link.py b/brain/teaport_brain/license_link.py new file mode 100644 index 00000000..95025eeb --- /dev/null +++ b/brain/teaport_brain/license_link.py @@ -0,0 +1,637 @@ +# +# teaport — the owner's acceptance put on the box's appliance key (#465): POST +# /license/link, as root, behind sudo, and from teaport-license-owner.timer. +# +# The box's engine license key (/etc/teaport/license.json, #474) holds no personal data: +# the license server links it to its owner's acceptance instead, which the owner made at +# setup (license_accept.py). The link needs proof that the box itself asks, since the box's +# agent can read license.json: the link secret the license server returned with the key at +# the factory, which install.sh is to keep (teaport#475, I1) in +# /etc/teaport/license-link.secret, root's 0600 (the run user, the agent included, cannot +# read it). This helper sends it, with ids only: +# - it takes no acceptance id, nor anything else (a request that names anything is +# refused). It links the acceptance on the box's record (/var/lib/teaport/eula-accepted.json, +# which only root writes: license_accept.py's, or install.sh's), the key in license.json +# and the secret, all three read here; +# - when the run user asks (through its sudoers line), only while setup is unfinished +# (provisioning's marker, GATE_PATH, is there). Setup finishes when the link is made: +# the marker goes. Not "while an owner's session from the setup page is open": the +# session (settings_access.py) is signed with a key in brain.env, which the run user +# reads, so the run user could make one, and no root helper can tell it from the +# owner's. The owner's own login (`teaport`, in the sudo group) reaches it through sudo +# with their password at any time, and root's own call (the timer) does: sudo sets +# SUDO_UID itself, so the run user cannot pass for either; +# - so a prompt-injected agent can at worst have the box linked to the acceptance on its +# own record, the owner's, again: a link to the acceptance already linked changes +# nothing (no request at all: LINKED_PATH says so), and the license server's answer for +# one sent anyway is the same. +# +# Where: API, built in (license_accept.API), never the record's recorded_with: an older +# installer's receipt may be a file the run user could write, and the secret would go wherever +# it said. A record naming another server is not linked at all. +# +# A box without the secret file (installed before install.sh writes it, teaport#475) is +# logged and left as it is: nothing is sent, no refusal remembered, the record and the marker +# kept, so the timer links it once the secret is there. A box with no appliance key, or no +# recorded acceptance, has nothing to link. The license server's answers: +# - linked: the link is recorded (LINKED_PATH) and the marker goes: setup is finished; +# - the acceptance is no longer one it links (409 eula_changed: the license changed before +# the link was made; 404 unknown_acceptance): the setup's record goes (the marker stays), +# so the setup step is offered again and the owner accepts the current license; +# - busy (409 conflict, 429, 5xx) or no answer: asked again, by the timer; +# - any other refusal (the secret, the key): remembered for that acceptance, key and secret +# (LINKED_PATH): root's own call does not ask again until one of them changes; the run +# user or the owner may. +# Every link rotates the secret (the handover): the answer carries a new one, written here +# (write_secret: root's 0600, atomically) in place of the old, and shown to the license +# server at once with the same link (the confirm, answered with no new secret); only then +# is the link recorded and the marker gone. Until the confirm, the license server still +# takes the old secret, so a write that failed, or a confirm that was lost, is retried with +# whichever secret the box holds. After it, a copy of an older secret (a previous owner had +# root on the box) links nothing. +# +# Whoever links first wins: a copy of the secret, made by someone who had root on the box (a +# previous owner), can take the link, and rotates it away from the box. Nothing can tell the +# real box from such a copy, so a contest is made visible and recoverable (the owner's +# decision, 2026-11-28: support fixes a wrong link): a 403 bad_link_secret for a secret that +# linked before is LOST, said in status (the setup page, Settings, `teaport status`) and the +# journal, not remembered as a refusal. Support verifies the owner and sets a one-time +# recovery code as the key's secret (packaging/RELEASING.md); the owner types it on the box +# (`sudo python3 license_link.py link --recovery-code`, at a prompt), it links once, before +# it runs out, and the rotation that follows gives the box a fresh secret (a lost answer +# can be asked again with the code until the confirm, for at most a day). A secret that +# never linked, refused with bad_link_secret (its first try or a later one), is LOST too, +# its cause unknown (CAUSE_UNKNOWN): a secret the factory wrote wrong, a key issued before +# its secret hash (migration 0005), a copy's holder who linked first, a handover answer +# lost; the box cannot tell which (an answer it got would have linked, and made the +# refusal a plain LOST), and only support puts any of them right. A run user that kills +# this helper mid-handover keeps the previous secret alive, which only the box (and +# root) holds: it gives a party without root nothing. +# +# One at a time with license_accept.py's sends (its lock, waited for at most LOCK_SECS, then +# BUSY): a replaced acceptance is never linked as the old one. +# +# Verbs (the only argument; the request is a JSON object on stdin, the reply one on stdout; +# a request this does not do gets {"refused": why, "why": code} and exit 2): +# status {state}: LINKED, UNLINKED, NO_SECRET, NO_KEY or NO_ACCEPTANCE; +# link {} -> {ok, linked, changed} or {ok: false, why}. +# The secret reaches the license server and nothing else: no reply, no log line, no error. +# Nothing here writes, renames or removes PROTECTED (the engine's license files, #474 F1). +# +# Run as the sudoers line (packaging/deb/sudoers-sync) names it: +# /usr/bin/python3 /usr/lib/teaport/license_link.py +# the root-owned copy the teaport-brain package ships, on the SYSTEM python, never the +# venv's. Standard library only. Tests run it in-process (handle()) against a pretend +# license server and a temporary tree (Box). +# +import fcntl +import hashlib +import json +import os +import pwd +import re +import stat +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request + +ORIGIN = "https://get.teaspoon.tech" # license_accept.ORIGIN +API = ORIGIN + "/api" # license_accept.API +RECORD_PATH = "/var/lib/teaport/eula-accepted.json" +LINKED_PATH = "/var/lib/teaport/license-link.json" +GATE_PATH = "/var/lib/teaport-owner/license-pending" # license_accept.GATE_PATH +LICENSE_PATH = "/etc/teaport/license.json" +SECRET_PATH = "/etc/teaport/license-link.secret" +# The engine's license files (teaport#474 F1): no root helper the run user reaches writes, +# renames or removes them, but for one write here: write_secret, the new link secret a link +# answers with (the handover). The one list: every other helper's copy must equal it (tests). +PROTECTED = ("/etc/teaport/license.json", "/etc/teaport/license-revocations.json", + "/etc/teaport/license-link.secret") +BRAIN_UNIT = "teaport-brain.service" +MAX_REQUEST = 4096 +NET_SECS = 20 +# The secret as install.sh writes it: 32 bytes, base64url without padding (43 characters), +# then at most a newline. +SECRET = re.compile(r"[A-Za-z0-9_-]{43}\n?") +ACCEPTANCE_ID = re.compile(r"[A-Za-z0-9_-]{8,64}") +LICENSE_ID = re.compile(r"[A-Z0-9][A-Z0-9-]{3,39}") +TPDEV2 = re.compile(r"tpdev2-[0-9a-f]{32}") +SERVER_CODE = re.compile(r"[a-z_]{1,40}") +LINKED, UNLINKED, NO_SECRET, NO_KEY, NO_ACCEPTANCE, LOST, QUEUED = ( + "linked", "unlinked", "no_secret", "no_key", "no_acceptance", "lost", "queued") +# A lost link whose secret never linked on this box, refused with bad_link_secret: the +# box cannot tell why (the module comment). Shown as LOST (status), told +# apart in the reply and log, in neutral words: the link failed, ask support. +CAUSE_UNKNOWN = "cause_unknown" +QUEUE_NAME = "eula-queued.json" # license_accept.QUEUE_PATH's +# A link's handover not yet settled: root's, written before the link, gone once it is +# confirmed or refused for good; teaport-license-owner.service runs while it is there. +HANDOVER_NAME = "license-handover" +HANDOVER_PATH = "/var/lib/teaport/" + HANDOVER_NAME +REFUSED, SETUP_DONE, UNREACHABLE, FAILED, OTHER_SERVER, ACCEPT_AGAIN = ( + "refused", "setup_done", "unreachable", "failed", "other_server", "accept_again") +# The license server's answers that mean the acceptance is no longer one it links: the setup +# step is offered again (the module comment). +STALE = {(409, "eula_changed"), (404, "unknown_acceptance")} +LOCK_NAME = ".eula-accept.lock" # license_accept.LOCK_NAME +LOCK_SECS = 30 # license_accept.LOCK_SECS +# A link and its confirm, and a retry of each: the handover (the module comment). +HANDOVERS = 4 +BUSY = "busy" +TOOL_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"} + + +class Refused(Exception): + def __init__(self, text: str, why: str = REFUSED): + super().__init__(text) + self.why = why + + +def guard(path: str) -> str: + """`path`, unless it is one of PROTECTED, by name or through a link (teaport#474 F1).""" + if os.path.abspath(path) in PROTECTED or os.path.realpath(path) in PROTECTED: + raise Refused(f"{path} is the engine's license, which this helper never writes") + return path + + +class Marker: + """Provisioning's marker (license_accept.Marker): there, and root's alone.""" + + def __init__(self, path: str = GATE_PATH, owner: int = 0): + self.path, self.owner = path, owner + + def _roots(self, st: os.stat_result, kind) -> bool: + return kind(st.st_mode) and st.st_uid == self.owner and not st.st_mode & 0o022 + + def present(self) -> bool: + try: + directory = os.lstat(os.path.dirname(self.path)) + marker = os.lstat(self.path) + except FileNotFoundError: + return False + return self._roots(directory, stat.S_ISDIR) and self._roots(marker, stat.S_ISREG) + + def remove(self) -> None: + guard(self.path) + try: + os.unlink(self.path) + except FileNotFoundError: + pass + + +def _no_redirect(): + class Refuse(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + return urllib.request.build_opener(Refuse) + + +def post(url: str, body: dict) -> tuple[int, bytes]: + """POST `body` as JSON to an https `url`: (status, the answer); 0 for no answer. No + redirect is followed: one would take the secret wherever it said.""" + if not url.startswith("https://"): + return 0, b"" + req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", + headers={"content-type": "application/json", + "user-agent": "teaport-license-link"}) + try: + with _no_redirect().open(req, timeout=NET_SECS) as r: # noqa: S310 -- https only + return r.status, r.read(65536) + except urllib.error.HTTPError as e: + try: + return e.code, e.read(65536) + except OSError: + return e.code, b"" + except (OSError, ValueError): + return 0, b"" + + +def run_user(run=subprocess.run) -> str: + """The brain's User= (as sudoers-sync reads it): "" when it cannot be told.""" + try: + p = run(["systemctl", "show", "-p", "User", "--value", BRAIN_UNIT], + capture_output=True, text=True, timeout=10, env=TOOL_ENV) + return p.stdout.strip() if p.returncode == 0 else "" + except (OSError, subprocess.SubprocessError): + return "" + + +def uid_of(name: str) -> int | None: + try: + return pwd.getpwnam(name).pw_uid + except (KeyError, TypeError): + return None + + +class Box: + """Where this helper reads and writes, who asks, and how it reaches the network (a + test's own). `caller`: SUDO_UID as sudo set it (None: root's own call, the timer); + `run_uid`: the brain's user's uid (None when it cannot be told).""" + + def __init__(self, record: str = RECORD_PATH, linked: str = LINKED_PATH, + gate: Marker | None = None, license_path: str = LICENSE_PATH, + secret: str = SECRET_PATH, net=post, caller: int | None = None, + run_uid=None, now=time.time, secret_owner: int = 0): + self.record, self.linked, self.gate = record, linked, gate or Marker() + self.license_path, self.secret, self.net, self.now = license_path, secret, net, now + self.caller, self.secret_owner = caller, secret_owner + self.recovery_prompt = _prompt # main()'s for --recovery-code (a test's own) + self._run_uid = run_uid + + def run_uid(self) -> int | None: + if callable(self._run_uid): + return self._run_uid() + return self._run_uid + + def by_run_user(self) -> bool: + """The request is the run user's (its sudoers line), or cannot be told from one + (license_accept.Box.by_run_user's rule).""" + if self.caller is None or self.caller == 0: + return False + run = self.run_uid() + return run is None or self.caller == run + + @classmethod + def real(cls) -> "Box": + raw = os.environ.get("SUDO_UID") + caller = int(raw) if raw and raw.isdigit() else None + return cls(caller=caller, run_uid=lambda: uid_of(run_user())) + + +def _read_json(path: str, limit: int = 65536) -> dict | None: + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except OSError: + return None + try: + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + return None + data = json.loads(f.read(limit + 1)[:limit]) + except (OSError, ValueError): + return None + return data if isinstance(data, dict) else None + + +def _handover(box: Box) -> str: + """The marker of a handover not yet settled (HANDOVER_NAME, beside the record).""" + return os.path.join(os.path.dirname(box.record), HANDOVER_NAME) + + +def write_secret(box: Box, secret: str) -> None: + """The new link secret a link answered with (the handover), in place of the box's: root's + alone (0600), whole or not at all (a temporary file beside it, synced, renamed, the + directory synced). The one write of a PROTECTED file any helper the run user reaches + makes, and only of what the license server answered over its own TLS to API: the run + user names nothing in it. Never through write_file, whose guard() refuses it.""" + directory = os.path.dirname(box.secret) + fd, tmp = tempfile.mkstemp(dir=directory, prefix=".license-link.secret.") + try: + os.fchmod(fd, 0o600) + if os.geteuid() == 0: + os.fchown(fd, box.secret_owner, 0) + with os.fdopen(fd, "wb") as f: + f.write((secret + "\n").encode("ascii")) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, box.secret) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + dfd = os.open(directory, os.O_RDONLY) + try: + os.fsync(dfd) + finally: + os.close(dfd) + + +def _remove(path: str) -> None: + guard(path) + try: + os.unlink(path) + except FileNotFoundError: + pass + + +def write_file(path: str, data: bytes, mode: int) -> None: + """Whole or not at all, as license_accept.write_file.""" + guard(path) + directory = os.path.dirname(path) + fd, tmp = tempfile.mkstemp(dir=directory, prefix="." + os.path.basename(path) + ".") + try: + os.fchmod(fd, mode) + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +# ------------------------------------------------------------------ what there is to link + +def acceptance(box: Box) -> tuple[str, str] | None: + """(acceptance id, the license server it was recorded with) from the box's record: an + acceptance's, not the factory's maker record; None when there is none. The server is + whatever the record says: link() sends nothing unless it is API.""" + r = _read_json(box.record) + if not r or r.get("method") == "factory": + return None + aid, api = r.get("acceptance_id"), r.get("recorded_with") + if not (isinstance(aid, str) and ACCEPTANCE_ID.fullmatch(aid) and not aid.startswith("maker-")): + return None + return aid, api.rstrip("/") if isinstance(api, str) else "" + + +def appliance_key(box: Box) -> tuple[str, str] | None: + """(license_id, device) of the box's appliance key, read only; None for no key, or one + of another tier (a personal key's acceptance is the one it was issued under).""" + doc = _read_json(box.license_path) or {} + p = doc.get("payload") if isinstance(doc.get("payload"), dict) else {} + lid, device = p.get("license_id"), p.get("device") + if p.get("tier") != "appliance" or not (isinstance(lid, str) and LICENSE_ID.fullmatch(lid)) \ + or not (isinstance(device, str) and TPDEV2.fullmatch(device)): + return None + return lid, device + + +def link_secret(box: Box) -> str | None: + """The secret, from a regular file of root's that nobody else can read or write; None + when there is no file. Refused when it is there but not so (it may have been read), or + not one.""" + try: + fd = os.open(box.secret, os.O_RDONLY | os.O_NOFOLLOW) + except FileNotFoundError: + return None + except OSError: + raise Refused(f"{box.secret} cannot be read", FAILED) from None + with os.fdopen(fd, "rb") as f: + st = os.fstat(f.fileno()) + if not stat.S_ISREG(st.st_mode) or st.st_uid != box.secret_owner or st.st_mode & 0o077: + raise Refused(f"{box.secret} must be a file of root's, mode 0600", FAILED) + data = f.read(64).decode("ascii", "replace") + if not SECRET.fullmatch(data): + raise Refused(f"{box.secret} is not a link secret", FAILED) + return data.rstrip("\n") + + +def _fingerprint(aid: str, lid: str, secret: str) -> str: + """What a remembered refusal was for: the acceptance, the key and the secret's hash.""" + return hashlib.sha256(f"{aid}\0{lid}\0{secret}".encode()).hexdigest() + + +def status(box: Box) -> dict: + acc, key = acceptance(box), appliance_key(box) + if not key: + return {"state": NO_KEY} + done = _read_json(box.linked) or {} + if done.get("lost") is True and done.get("license_id") == key[0]: + return {"state": LOST, "why": done.get("why") or LOST} + if not acc: + return {"state": NO_ACCEPTANCE} + if not os.path.lexists(box.secret): + return {"state": NO_SECRET} + ok = done.get("acceptance_id") == acc[0] and done.get("license_id") == key[0] and done.get("linked") is True + return {"state": LINKED if ok else UNLINKED} + + +def _allowed(box: Box) -> None: + """The run user asks only while setup is unfinished (the module comment). Who asks is + sudo's SUDO_UID: none is root's own call; one that is not the brain's user is another + administrator's, who gave sudo a password. A brain's user that cannot be told counts as + the caller's: refused unless setup is unfinished.""" + if box.caller is None or box.caller == 0: + return + run = box.run_uid() + if (run is None or box.caller == run) and not box.gate.present(): + raise Refused("setup is finished on this box: its owner's acceptance is linked through it no more", + SETUP_DONE) + + +class _Busy(Exception): + """The lock was held past LOCK_SECS.""" + + +class _Locked: + """license_accept's lock (the module comment): an flock on root's file beside the record.""" + + def __init__(self, box: Box): + self.path, self.fd = guard(os.path.join(os.path.dirname(box.record), LOCK_NAME)), None + + def __enter__(self): + self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) + deadline = time.monotonic() + LOCK_SECS + while True: + try: + fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + return self + except BlockingIOError: + if time.monotonic() >= deadline: + os.close(self.fd) + raise _Busy from None + time.sleep(0.2) + + def __exit__(self, *exc): + os.close(self.fd) + + +def link(box: Box, log=lambda line: sys.stderr.write(f"license_link: {line}\n"), + recovery: str | None = None) -> dict: + """The recorded acceptance on the box's key. `recovery`: a one-time recovery code support + gave the box's verified owner (the module comment), presented in place of the secret; + only an administrator's or root's (it was typed at their prompt, main).""" + _allowed(box) + if recovery is not None: + if box.by_run_user(): + raise Refused("a recovery code is an administrator's: run it with sudo, as your login") + if not (isinstance(recovery, str) and SECRET.fullmatch(recovery) and not recovery.endswith("\n")): + raise Refused("that is not a recovery code: 43 letters, digits, - and _", FAILED) + if not os.path.isdir(os.path.dirname(box.record)): + return {"ok": True, "linked": False, "why": NO_ACCEPTANCE} + try: + with _Locked(box): + return _link(box, log, recovery) + except _Busy: + # Held by a send or a link that takes its time: the next call (the timer's) links. + return {"ok": False, "why": BUSY} + + +def _link(box: Box, log, recovery: str | None = None) -> dict: + acc, key = acceptance(box), appliance_key(box) + if not key: + return {"ok": True, "linked": False, "why": NO_KEY} + if not acc: + return {"ok": True, "linked": False, "why": NO_ACCEPTANCE} + if os.path.lexists(os.path.join(os.path.dirname(box.record), QUEUE_NAME)): + # A newer acceptance waits to be sent (one in place of this record's): never link + # the one it replaces. The timer sends it, then links it. + return {"ok": True, "linked": False, "why": QUEUED} + secret = recovery or link_secret(box) + if secret is None: + log(f"no link secret on this box ({box.secret}, written by install.sh since teaport#475): " + "nothing is linked; Teaspoon AI links the owner by hand") + return {"ok": True, "linked": False, "why": NO_SECRET} + (aid, api), (lid, device) = acc, key + if api != API: + log("the box's record names another license server than this helper's: nothing is sent") + return {"ok": False, "why": OTHER_SERVER} + done = _read_json(box.linked) or {} + if recovery is None and done.get("acceptance_id") == aid and done.get("license_id") == lid \ + and done.get("linked") is True: + box.gate.remove() # linked already: setup is finished, if a cut left the marker + _remove(_handover(box)) # and the handover with it: a crash cannot keep the timer on + return {"ok": True, "linked": True, "changed": False} + # The secret has linked before (a link answered 200 for this key): a 403 for it now is a + # lost link, not a refusal (the module comment). + worked = done.get("license_id") == lid and done.get("worked") is True + mark = _fingerprint(aid, lid, secret) + if box.caller is None and recovery is None and mark in (done.get("refused_for"), done.get("lost_for")): + return {"ok": False, "why": done.get("why") or (LOST if done.get("lost_for") == mark else REFUSED)} + changed = False + # Until the handover settles (confirmed, or refused for good), the timer runs whatever + # setup's state (teaport-license-owner.service's conditions): a confirm lost after setup, + # or after an administrator's re-link, is sent again, before the license server lets the + # previous secret go (link_secret_prev_expires). + write_file(_handover(box), (json.dumps({"license_id": lid, "at": int(box.now())}) + "\n").encode(), 0o600) + for _ in range(HANDOVERS): + status_code, data = box.net(f"{API}/license/link", + {"acceptance_id": aid, "license_id": lid, "device": device, "link_secret": secret}) + try: + answer = json.loads(data) if status_code else {} + except ValueError: + answer = {} + answer = answer if isinstance(answer, dict) else {} + if not (status_code == 200 and answer.get("linked") is True): + break + changed = changed or answer.get("changed") is not False + worked = True + new = answer.get("link_secret") + if new is None: + # No new secret: the handover is confirmed (the one sent is the current one), so + # the link is made and setup is finished. + write_file(box.linked, (json.dumps({"acceptance_id": aid, "license_id": lid, "linked": True, + "worked": True, "at": int(box.now())}) + "\n").encode(), 0o600) + box.gate.remove() + _remove(_handover(box)) + log("the owner's acceptance is linked to this box's license key" + + ("" if changed else " (it was already)")) + return {"ok": True, "linked": True, "changed": changed} + # The handover (the module comment): the new secret written, then shown at once. A + # write that fails leaves the old one, which the license server still takes. + if not (isinstance(new, str) and SECRET.fullmatch(new) and not new.endswith("\n")): + log("the license server answered a link secret that is not one: nothing written") + return {"ok": False, "why": FAILED} + write_secret(box, new) + secret = new + # The secret has linked: a later 403 for it is a lost link (said, not remembered as a + # refusal), whatever comes of the confirm. + write_file(box.linked, (json.dumps({"license_id": lid, "acceptance_id": aid, "worked": True, + "at": int(box.now())}) + "\n").encode(), 0o600) + else: + log("the license server's handover did not settle: the timer asks again") + return {"ok": False, "why": UNREACHABLE} + code = answer.get("error") if isinstance(answer.get("error"), str) and SERVER_CODE.fullmatch(answer["error"]) else None + if (status_code, code) in STALE: + # Accepted again from the setup step: the setup's record goes, the marker stays. An + # installer's receipt is the installer's to ask again for. + rec = _read_json(box.record) or {} + if rec.get("method") == "setup" and rec.get("acceptance_id") == aid: + _remove(box.record) + write_file(box.linked, (json.dumps({"license_id": lid, "worked": worked, + "at": int(box.now())}) + "\n").encode(), 0o600) + _remove(_handover(box)) + log(f"the license server no longer links this acceptance (HTTP {status_code}, {code}): " + "the owner accepts the license again at setup") + return {"ok": False, "why": ACCEPT_AGAIN} + if status_code == 403 and code == "bad_link_secret" and recovery is None: + # Another link was made with a copy of this box's secret (someone who had root on it), + # and rotated it away from the box; or, a secret that never linked (on its first try + # too), a cause the box cannot tell (CAUSE_UNKNOWN). Either way only support can put + # it right, so it is said as lost, not remembered as an ordinary refusal. + why = LOST if worked else CAUSE_UNKNOWN + write_file(box.linked, (json.dumps({"license_id": lid, "worked": worked, "lost": True, "lost_for": mark, + "why": why, "at": int(box.now())}) + "\n").encode(), 0o600) + _remove(_handover(box)) + log("license link lost: this box's secret no longer links its license key (someone linked it " + "with a copy of the secret): contact Teaspoon AI support" if worked else + "license link failed: this box's secret, which never linked, is refused for its license " + "key (cause unknown): contact Teaspoon AI support") + return {"ok": False, "why": why} + if status_code in (400, 403, 404, 409) and code != "conflict": + write_file(box.linked, (json.dumps({"license_id": lid, "worked": worked, "refused_for": mark, + "why": code or REFUSED, "status": status_code, + "at": int(box.now())}) + "\n").encode(), 0o600) + _remove(_handover(box)) + log(f"the license server refused the link (HTTP {status_code}{', ' + code if code else ''})") + return {"ok": False, "why": code or REFUSED} + log(f"the license server could not be asked now (HTTP {status_code or 'none'}): the timer asks again") + return {"ok": False, "why": UNREACHABLE} + + +def handle(box: Box, verb: str, req, recovery: str | None = None) -> dict: + if not isinstance(req, dict): + raise Refused("the request must be a JSON object") + if verb not in ("status", "link"): + raise Refused(f"unknown request {verb!r}") + if req: + # An acceptance id above all: this links the one on the box's record, never one given. + raise Refused(f"{verb} takes nothing: not {', '.join(sorted(map(str, req)))}") + return status(box) if verb == "status" else link(box, recovery=recovery) + + +def _prompt() -> str: + import getpass + return getpass.getpass("Recovery code from Teaspoon AI support: ") + + +def _reply(obj: dict) -> None: + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + +def main(argv: list[str] | None = None, box: Box | None = None) -> int: + argv = sys.argv[1:] if argv is None else argv + if box is None and os.geteuid() != 0: + _reply({"refused": "run as root, through the sudoers line", "why": REFUSED}) + return 2 + recovering = argv == ["link", "--recovery-code"] + if len(argv) != 1 and not recovering: + _reply({"refused": "usage: license_link.py (nothing on stdin, or {}) | link --recovery-code", + "why": REFUSED}) + return 2 + try: + data = sys.stdin.read(MAX_REQUEST + 1) if not sys.stdin.isatty() else "" + if len(data) > MAX_REQUEST: + raise Refused("the request is too long") + try: + req = json.loads(data) if data.strip() else {} + except ValueError: + raise Refused("the request is not JSON") from None + # The code is typed at a prompt on the terminal, never a command line (ps shows those) + # nor stdin a caller could have filled. + code = (box.recovery_prompt if box is not None else _prompt)() if recovering else None + reply = handle(box or Box.real(), argv[0], req, recovery=code.strip() if code else None) + except Refused as e: + _reply({"refused": str(e), "why": e.why}) + return 2 + except Exception as e: # noqa: BLE001 -- by its type alone: never the secret + sys.stderr.write(f"license_link: {type(e).__name__}\n") + _reply({"ok": False, "why": FAILED}) + return 1 + _reply(reply) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/brain/teaport_brain/locale/ar/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/ar/LC_MESSAGES/teaport.mo index 834e8a1e..9de41f60 100644 Binary files a/brain/teaport_brain/locale/ar/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/ar/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/ar/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/ar/LC_MESSAGES/teaport.po index e883e196..c3ed4f2e 100644 --- a/brain/teaport_brain/locale/ar/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/ar/LC_MESSAGES/teaport.po @@ -872,3 +872,90 @@ msgstr "تعذّر على Teaport إنشاء حساب تسجيل الدخول. msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "تعذّر على Teaport إنشاء حساب تسجيل الدخول. يمكنك الاتصال الآن وإنشاؤه لاحقًا من الإعدادات." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "اقرأ الترخيص" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "يأتي محرك الكلام في Teaport مع ترخيص Teaport Engine License. اقرأه ثم وافق عليه لإكمال إعداد Teaport." + +msgid "Your email address" +msgstr "عنوان بريدك الإلكتروني" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "تسجّل Teaspoon AI من وافق على الترخيص، مع هذا العنوان." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "قرأت ترخيص Teaport Engine License وأوافق عليه." + +msgid "I accept" +msgstr "أوافق" + +msgid "Recording your acceptance…" +msgstr "جارٍ تسجيل موافقتك…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "شكرًا. تم تسجيل موافقتك على الترخيص." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "شكرًا. سيسجّل Teaport موافقتك لدى Teaspoon AI بمجرد اتصاله بالإنترنت." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "ستقرأ ترخيص Teaport Engine License وتوافق عليه في الإعدادات بعد اتصال Teaport بالإنترنت." + +msgid "Tick the box to accept the license." +msgstr "ضع علامة في المربع للموافقة على الترخيص." + +msgid "Enter your email address." +msgstr "أدخل عنوان بريدك الإلكتروني." + +msgid "The license is already accepted on this Teaport." +msgstr "تمت الموافقة على الترخيص بالفعل على جهاز Teaport هذا." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "الموافقة على الترخيص غير متاحة على جهاز Teaport هذا." + +msgid "The license changed while you were reading it. Read it again." +msgstr "تغيّر الترخيص أثناء قراءتك له. اقرأه مرة أخرى." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "لا يستطيع Teaport عرض الترخيص الآن. حاول مرة أخرى بعد اتصاله بالإنترنت." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "لم تقبل Teaspoon AI هذه الموافقة. اقرأ الترخيص مرة أخرى ووافق عليه." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "تعذّر على Teaport تسجيل موافقتك. حاول مرة أخرى." + +msgid "The license is accepted as {email}." +msgstr "تمت الموافقة على الترخيص باسم {email}." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "لست أنت؟ اقرأ الترخيص ووافق عليه مرة أخرى بعنوان بريدك الإلكتروني." + +msgid "Accept again" +msgstr "الموافقة مرة أخرى" + +msgid "Accept the license first, then create your login." +msgstr "وافق على الترخيص أولًا، ثم أنشئ حساب تسجيل الدخول." + +msgid "What will you use Teaport for?" +msgstr "لأي غرض ستستخدم Teaport؟" + +msgid "Personal use" +msgstr "استخدام شخصي" + +msgid "A business" +msgstr "نشاط تجاري" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "اختر ما إذا كان Teaport للاستخدام الشخصي أو لنشاط تجاري." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "يسجّل Teaport موافقة الآن. حاول مرة أخرى بعد قليل." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "فُقد ربط ترخيص جهاز Teaport هذا: رُبط مفتاح ترخيصه بنسخة من سرّ Teaport. تواصل مع دعم Teaspoon AI لاستعادته." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "فشل ربط ترخيص جهاز Teaport هذا. تواصل مع دعم Teaspoon AI." diff --git a/brain/teaport_brain/locale/de/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/de/LC_MESSAGES/teaport.mo index 36a60dd2..9a742ed5 100644 Binary files a/brain/teaport_brain/locale/de/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/de/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/de/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/de/LC_MESSAGES/teaport.po index d3fc6fed..4ea62a6c 100644 --- a/brain/teaport_brain/locale/de/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/de/LC_MESSAGES/teaport.po @@ -861,3 +861,90 @@ msgstr "Teaport konnte deine Anmeldung nicht erstellen. Versuch es noch einmal." msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport konnte deine Anmeldung nicht erstellen. Du kannst dich jetzt verbinden und die Anmeldung später in den Einstellungen erstellen." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "Lies die Lizenz" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "Die Sprach-Engine von Teaport kommt mit der Teaport Engine License. Lies sie und akzeptiere sie, um die Einrichtung von Teaport abzuschließen." + +msgid "Your email address" +msgstr "Deine E-Mail-Adresse" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI speichert mit dieser Adresse, wer die Lizenz akzeptiert hat." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "Ich habe die Teaport Engine License gelesen und akzeptiere sie." + +msgid "I accept" +msgstr "Ich akzeptiere" + +msgid "Recording your acceptance…" +msgstr "Deine Zustimmung wird gespeichert…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "Danke. Deine Zustimmung zur Lizenz ist gespeichert." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "Danke. Teaport meldet deine Zustimmung an Teaspoon AI, sobald es online ist." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Du liest und akzeptierst die Teaport Engine License in den Einstellungen, sobald Teaport online ist." + +msgid "Tick the box to accept the license." +msgstr "Setze das Häkchen, um die Lizenz zu akzeptieren." + +msgid "Enter your email address." +msgstr "Gib deine E-Mail-Adresse ein." + +msgid "The license is already accepted on this Teaport." +msgstr "Die Lizenz ist auf diesem Teaport schon akzeptiert." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "Die Lizenz kann auf diesem Teaport nicht akzeptiert werden." + +msgid "The license changed while you were reading it. Read it again." +msgstr "Die Lizenz hat sich geändert, während du sie gelesen hast. Lies sie noch einmal." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport kann die Lizenz gerade nicht anzeigen. Versuch es noch einmal, sobald es online ist." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI hat diese Zustimmung nicht angenommen. Lies die Lizenz noch einmal und akzeptiere sie." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport konnte deine Zustimmung nicht speichern. Versuch es noch einmal." + +msgid "The license is accepted as {email}." +msgstr "Die Lizenz ist akzeptiert als {email}." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "Nicht du? Lies die Lizenz und akzeptiere sie noch einmal mit deiner eigenen E-Mail-Adresse." + +msgid "Accept again" +msgstr "Erneut akzeptieren" + +msgid "Accept the license first, then create your login." +msgstr "Akzeptiere zuerst die Lizenz, dann erstelle deine Anmeldung." + +msgid "What will you use Teaport for?" +msgstr "Wofür nutzt du Teaport?" + +msgid "Personal use" +msgstr "Private Nutzung" + +msgid "A business" +msgstr "Ein Unternehmen" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Wähle, ob Teaport privat oder für ein Unternehmen genutzt wird." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport speichert gerade eine Zustimmung. Versuch es gleich noch einmal." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "Die Lizenzverknüpfung dieses Teaport ging verloren: Sein Lizenzschlüssel wurde mit einer Kopie des Geheimnisses dieses Teaport verknüpft. Wende dich an den Support von Teaspoon AI, um sie zurückzubekommen." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "Die Lizenzverknüpfung dieses Teaport ist fehlgeschlagen. Wende dich an den Support von Teaspoon AI." diff --git a/brain/teaport_brain/locale/es/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/es/LC_MESSAGES/teaport.mo index 43f119eb..b55cabcc 100644 Binary files a/brain/teaport_brain/locale/es/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/es/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/es/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/es/LC_MESSAGES/teaport.po index 25e1b40a..f34b7c5a 100644 --- a/brain/teaport_brain/locale/es/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/es/LC_MESSAGES/teaport.po @@ -863,3 +863,90 @@ msgstr "Teaport no pudo crear tu inicio de sesión. Inténtalo de nuevo." msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport no pudo crear tu inicio de sesión. Puedes conectarte ahora y crearlo más tarde en Ajustes." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "Lee la licencia" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "El motor de voz de Teaport viene con la Teaport Engine License. Léela y acéptala para terminar de configurar Teaport." + +msgid "Your email address" +msgstr "Tu correo electrónico" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI registra quién aceptó la licencia, con esta dirección." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "He leído la Teaport Engine License y la acepto." + +msgid "I accept" +msgstr "Acepto" + +msgid "Recording your acceptance…" +msgstr "Registrando tu aceptación…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "Gracias. Tu aceptación de la licencia está registrada." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "Gracias. Teaport registrará tu aceptación con Teaspoon AI cuando esté en línea." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Leerás y aceptarás la Teaport Engine License en Ajustes cuando Teaport esté en línea." + +msgid "Tick the box to accept the license." +msgstr "Marca la casilla para aceptar la licencia." + +msgid "Enter your email address." +msgstr "Escribe tu correo electrónico." + +msgid "The license is already accepted on this Teaport." +msgstr "La licencia ya está aceptada en este Teaport." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "Aceptar la licencia no está disponible en este Teaport." + +msgid "The license changed while you were reading it. Read it again." +msgstr "La licencia cambió mientras la leías. Vuelve a leerla." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport no puede mostrar la licencia ahora. Inténtalo de nuevo cuando esté en línea." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI no aceptó este registro. Vuelve a leer la licencia y acéptala." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport no pudo registrar tu aceptación. Inténtalo de nuevo." + +msgid "The license is accepted as {email}." +msgstr "La licencia está aceptada como {email}." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "¿No eres tú? Lee la licencia y vuelve a aceptarla con tu propio correo electrónico." + +msgid "Accept again" +msgstr "Aceptar de nuevo" + +msgid "Accept the license first, then create your login." +msgstr "Acepta primero la licencia y después crea tu inicio de sesión." + +msgid "What will you use Teaport for?" +msgstr "¿Para qué usarás Teaport?" + +msgid "Personal use" +msgstr "Uso personal" + +msgid "A business" +msgstr "Una empresa" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Elige si Teaport es para uso personal o para una empresa." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport está registrando una aceptación. Inténtalo de nuevo en un momento." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "Se perdió el vínculo de licencia de este Teaport: su clave de licencia se vinculó con una copia del secreto del Teaport. Contacta con el soporte de Teaspoon AI para recuperarlo." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "Falló el vínculo de licencia de este Teaport. Contacta con el soporte de Teaspoon AI." diff --git a/brain/teaport_brain/locale/fr/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/fr/LC_MESSAGES/teaport.mo index 43302b29..71c8c77e 100644 Binary files a/brain/teaport_brain/locale/fr/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/fr/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/fr/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/fr/LC_MESSAGES/teaport.po index 425c130c..0ed4cb44 100644 --- a/brain/teaport_brain/locale/fr/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/fr/LC_MESSAGES/teaport.po @@ -866,3 +866,90 @@ msgstr "Teaport n'a pas pu créer votre identifiant. Réessayez." msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport n'a pas pu créer votre identifiant. Vous pouvez vous connecter maintenant et le créer plus tard dans les Réglages." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "Lisez la licence" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "Le moteur vocal de Teaport est fourni avec la Teaport Engine License. Lisez-la, puis acceptez-la pour terminer la configuration de Teaport." + +msgid "Your email address" +msgstr "Votre adresse e-mail" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI enregistre, avec cette adresse, qui a accepté la licence." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "J'ai lu la Teaport Engine License et je l'accepte." + +msgid "I accept" +msgstr "J'accepte" + +msgid "Recording your acceptance…" +msgstr "Enregistrement de votre acceptation…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "Merci. Votre acceptation de la licence est enregistrée." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "Merci. Teaport enregistre votre acceptation auprès de Teaspoon AI dès qu'il est en ligne." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Vous lirez et accepterez la Teaport Engine License dans les Réglages une fois Teaport en ligne." + +msgid "Tick the box to accept the license." +msgstr "Cochez la case pour accepter la licence." + +msgid "Enter your email address." +msgstr "Saisissez votre adresse e-mail." + +msgid "The license is already accepted on this Teaport." +msgstr "La licence est déjà acceptée sur ce Teaport." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "L'acceptation de la licence n'est pas disponible sur ce Teaport." + +msgid "The license changed while you were reading it. Read it again." +msgstr "La licence a changé pendant que vous la lisiez. Relisez-la." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport ne peut pas afficher la licence pour le moment. Réessayez une fois qu'il sera en ligne." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI n'a pas pris en compte cette acceptation. Relisez la licence et acceptez-la." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport n'a pas pu enregistrer votre acceptation. Réessayez." + +msgid "The license is accepted as {email}." +msgstr "La licence est acceptée au nom de {email}." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "Ce n'est pas vous ? Lisez la licence et acceptez-la à nouveau avec votre propre adresse e-mail." + +msgid "Accept again" +msgstr "Accepter à nouveau" + +msgid "Accept the license first, then create your login." +msgstr "Acceptez d'abord la licence, puis créez votre identifiant." + +msgid "What will you use Teaport for?" +msgstr "À quoi servira Teaport ?" + +msgid "Personal use" +msgstr "Usage personnel" + +msgid "A business" +msgstr "Une entreprise" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Choisissez si Teaport est pour un usage personnel ou pour une entreprise." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport enregistre déjà une acceptation. Réessayez dans un instant." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "Le lien de licence de ce Teaport a été perdu : sa clé de licence a été liée avec une copie du secret du Teaport. Contactez le support de Teaspoon AI pour le récupérer." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "Le lien de licence de ce Teaport a échoué. Contactez le support de Teaspoon AI." diff --git a/brain/teaport_brain/locale/hi/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/hi/LC_MESSAGES/teaport.mo index 759fa9b2..c4e5d263 100644 Binary files a/brain/teaport_brain/locale/hi/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/hi/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/hi/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/hi/LC_MESSAGES/teaport.po index 71d13faa..9a969496 100644 --- a/brain/teaport_brain/locale/hi/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/hi/LC_MESSAGES/teaport.po @@ -966,3 +966,90 @@ msgstr "Teaport आपका लॉगिन नहीं बना सका। msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport आपका लॉगिन नहीं बना सका। आप अभी कनेक्ट कर सकते हैं और बाद में सेटिंग्स में अपना लॉगिन बना सकते हैं।" +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "लाइसेंस पढ़ें" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "Teaport का स्पीच इंजन Teaport Engine License के साथ आता है। Teaport का सेटअप पूरा करने के लिए इसे पढ़ें, फिर स्वीकार करें।" + +msgid "Your email address" +msgstr "आपका ईमेल पता" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI इस पते के साथ रिकॉर्ड करता है कि लाइसेंस किसने स्वीकार किया।" + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "Teaport Engine License मैंने पढ़ लिया है और यह मुझे स्वीकार है।" + +msgid "I accept" +msgstr "मुझे स्वीकार है" + +msgid "Recording your acceptance…" +msgstr "आपकी स्वीकृति दर्ज की जा रही है…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "धन्यवाद। लाइसेंस के लिए आपकी स्वीकृति दर्ज हो गई है।" + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "धन्यवाद। ऑनलाइन होते ही Teaport आपकी स्वीकृति Teaspoon AI के पास दर्ज कर देगा।" + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Teaport के ऑनलाइन होने पर आप सेटिंग्स में Teaport Engine License पढ़कर स्वीकार करेंगे।" + +msgid "Tick the box to accept the license." +msgstr "लाइसेंस स्वीकार करने के लिए बॉक्स पर टिक करें।" + +msgid "Enter your email address." +msgstr "अपना ईमेल पता डालें।" + +msgid "The license is already accepted on this Teaport." +msgstr "इस Teaport पर लाइसेंस पहले ही स्वीकार किया जा चुका है।" + +msgid "Accepting the license isn't available on this Teaport." +msgstr "इस Teaport पर लाइसेंस स्वीकार करना उपलब्ध नहीं है।" + +msgid "The license changed while you were reading it. Read it again." +msgstr "आपके पढ़ते समय लाइसेंस बदल गया। इसे फिर से पढ़ें।" + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport अभी लाइसेंस नहीं दिखा सकता। ऑनलाइन होने पर फिर से कोशिश करें।" + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI ने यह स्वीकृति नहीं ली। लाइसेंस फिर से पढ़ें और स्वीकार करें।" + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport आपकी स्वीकृति दर्ज नहीं कर सका। फिर से कोशिश करें।" + +msgid "The license is accepted as {email}." +msgstr "लाइसेंस {email} के नाम से स्वीकार किया गया है।" + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "आप नहीं हैं? लाइसेंस पढ़ें और अपने ईमेल पते से इसे फिर से स्वीकार करें।" + +msgid "Accept again" +msgstr "फिर से स्वीकार करें" + +msgid "Accept the license first, then create your login." +msgstr "पहले लाइसेंस स्वीकार करें, फिर अपना लॉगिन बनाएं।" + +msgid "What will you use Teaport for?" +msgstr "आप Teaport का इस्तेमाल किसके लिए करेंगे?" + +msgid "Personal use" +msgstr "निजी इस्तेमाल" + +msgid "A business" +msgstr "कोई व्यवसाय" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "चुनें कि Teaport निजी इस्तेमाल के लिए है या किसी व्यवसाय के लिए।" + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport अभी एक स्वीकृति दर्ज कर रहा है। थोड़ी देर में फिर से कोशिश करें।" + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "इस Teaport का लाइसेंस लिंक खो गया है: इसकी लाइसेंस कुंजी Teaport के सीक्रेट की एक कॉपी से लिंक कर दी गई। इसे वापस पाने के लिए Teaspoon AI सपोर्ट से संपर्क करें।" + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "इस Teaport का लाइसेंस लिंक विफल रहा। Teaspoon AI सपोर्ट से संपर्क करें।" diff --git a/brain/teaport_brain/locale/it/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/it/LC_MESSAGES/teaport.mo index cb30eb1e..7f41ceb1 100644 Binary files a/brain/teaport_brain/locale/it/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/it/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/it/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/it/LC_MESSAGES/teaport.po index 1b7f8964..21948751 100644 --- a/brain/teaport_brain/locale/it/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/it/LC_MESSAGES/teaport.po @@ -871,3 +871,90 @@ msgstr "Teaport non è riuscito a creare il tuo accesso. Riprova." msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport non è riuscito a creare il tuo accesso. Puoi connetterti ora e crearlo più tardi nelle Impostazioni." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "Leggi la licenza" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "Il motore vocale di Teaport è fornito con la Teaport Engine License. Leggila, poi accettala per finire di configurare Teaport." + +msgid "Your email address" +msgstr "Il tuo indirizzo email" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI registra chi ha accettato la licenza, con questo indirizzo." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "Ho letto la Teaport Engine License e la accetto." + +msgid "I accept" +msgstr "Accetto" + +msgid "Recording your acceptance…" +msgstr "Registrazione della tua accettazione…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "Grazie. La tua accettazione della licenza è registrata." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "Grazie. Teaport registra la tua accettazione presso Teaspoon AI appena è online." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Leggerai e accetterai la Teaport Engine License nelle Impostazioni quando Teaport sarà online." + +msgid "Tick the box to accept the license." +msgstr "Spunta la casella per accettare la licenza." + +msgid "Enter your email address." +msgstr "Inserisci il tuo indirizzo email." + +msgid "The license is already accepted on this Teaport." +msgstr "La licenza è già accettata su questo Teaport." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "Accettare la licenza non è disponibile su questo Teaport." + +msgid "The license changed while you were reading it. Read it again." +msgstr "La licenza è cambiata mentre la leggevi. Leggila di nuovo." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport non può mostrare la licenza adesso. Riprova quando è online." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI non ha preso questa accettazione. Leggi di nuovo la licenza e accettala." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport non è riuscito a registrare la tua accettazione. Riprova." + +msgid "The license is accepted as {email}." +msgstr "La licenza è accettata come {email}." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "Non sei tu? Leggi la licenza e accettala di nuovo con il tuo indirizzo email." + +msgid "Accept again" +msgstr "Accetta di nuovo" + +msgid "Accept the license first, then create your login." +msgstr "Accetta prima la licenza, poi crea il tuo accesso." + +msgid "What will you use Teaport for?" +msgstr "Per cosa userai Teaport?" + +msgid "Personal use" +msgstr "Uso personale" + +msgid "A business" +msgstr "Un'azienda" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Scegli se Teaport è per uso personale o per un'azienda." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport sta già registrando un'accettazione. Riprova tra un momento." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "Il collegamento della licenza di questo Teaport è andato perso: la sua chiave di licenza è stata collegata con una copia del segreto del Teaport. Contatta il supporto di Teaspoon AI per recuperarlo." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "Il collegamento della licenza di questo Teaport non è riuscito. Contatta il supporto di Teaspoon AI." diff --git a/brain/teaport_brain/locale/ja/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/ja/LC_MESSAGES/teaport.mo index 181967b5..26964fbd 100644 Binary files a/brain/teaport_brain/locale/ja/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/ja/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/ja/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/ja/LC_MESSAGES/teaport.po index 2c4f0db3..dd53bfc2 100644 --- a/brain/teaport_brain/locale/ja/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/ja/LC_MESSAGES/teaport.po @@ -966,3 +966,90 @@ msgstr "Teaport はログインを作成できませんでした。もう一度 msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport はログインを作成できませんでした。今は接続だけ行い、あとで設定からログインを作成することもできます。" +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "ライセンスを読む" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "Teaport の音声エンジンには Teaport Engine License が付いています。お読みのうえ同意して、Teaport のセットアップを完了してください。" + +msgid "Your email address" +msgstr "メールアドレス" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI は、ライセンスに同意した人をこのアドレスで記録します。" + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "Teaport Engine License を読み、同意します。" + +msgid "I accept" +msgstr "同意する" + +msgid "Recording your acceptance…" +msgstr "同意を記録しています…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "ありがとうございます。ライセンスへの同意を記録しました。" + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "ありがとうございます。Teaport がオンラインになりしだい、同意を Teaspoon AI に記録します。" + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Teaport がオンラインになったら、設定で Teaport Engine License を読んで同意してください。" + +msgid "Tick the box to accept the license." +msgstr "ライセンスに同意するには、チェックボックスをオンにしてください。" + +msgid "Enter your email address." +msgstr "メールアドレスを入力してください。" + +msgid "The license is already accepted on this Teaport." +msgstr "この Teaport ではすでにライセンスに同意済みです。" + +msgid "Accepting the license isn't available on this Teaport." +msgstr "この Teaport ではライセンスへの同意はできません。" + +msgid "The license changed while you were reading it. Read it again." +msgstr "お読みのあいだにライセンスが変わりました。もう一度お読みください。" + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport は今ライセンスを表示できません。オンラインになってからもう一度お試しください。" + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI はこの同意を受け付けませんでした。ライセンスをもう一度読んで同意してください。" + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport は同意を記録できませんでした。もう一度お試しください。" + +msgid "The license is accepted as {email}." +msgstr "ライセンスは {email} として同意済みです。" + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "ご本人ではありませんか?ライセンスを読み、ご自分のメールアドレスでもう一度同意してください。" + +msgid "Accept again" +msgstr "もう一度同意する" + +msgid "Accept the license first, then create your login." +msgstr "先にライセンスに同意してから、ログインを作成してください。" + +msgid "What will you use Teaport for?" +msgstr "Teaport を何に使いますか?" + +msgid "Personal use" +msgstr "個人での利用" + +msgid "A business" +msgstr "事業での利用" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Teaport を個人で使うか、事業で使うかを選んでください。" + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport は同意を記録中です。少ししてからもう一度お試しください。" + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "この Teaport のライセンスのリンクが失われました。Teaport の秘密情報のコピーでライセンスキーがリンクされました。取り戻すには Teaspoon AI のサポートにお問い合わせください。" + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "この Teaport のライセンスのリンクに失敗しました。Teaspoon AI のサポートにお問い合わせください。" diff --git a/brain/teaport_brain/locale/ko/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/ko/LC_MESSAGES/teaport.mo index 42e08a44..b36cd7e5 100644 Binary files a/brain/teaport_brain/locale/ko/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/ko/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/ko/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/ko/LC_MESSAGES/teaport.po index 587e2283..8d97ff0b 100644 --- a/brain/teaport_brain/locale/ko/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/ko/LC_MESSAGES/teaport.po @@ -970,3 +970,90 @@ msgstr "Teaport가 로그인을 만들지 못했어요. 다시 시도해 주세 msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport가 로그인을 만들지 못했어요. 지금 연결하고 나중에 설정에서 로그인을 만들 수 있어요." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "라이선스 읽기" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "Teaport의 음성 엔진에는 Teaport Engine License가 함께 제공돼요. 읽고 동의하면 Teaport 설정이 끝나요." + +msgid "Your email address" +msgstr "이메일 주소" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI는 이 주소로 라이선스에 동의한 사람을 기록해요." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "Teaport Engine License를 읽었고 이에 동의합니다." + +msgid "I accept" +msgstr "동의합니다" + +msgid "Recording your acceptance…" +msgstr "동의를 기록하고 있어요…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "감사합니다. 라이선스 동의가 기록됐어요." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "감사합니다. Teaport가 온라인이 되면 동의를 Teaspoon AI에 기록해요." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Teaport가 온라인이 되면 설정에서 Teaport Engine License를 읽고 동의하게 돼요." + +msgid "Tick the box to accept the license." +msgstr "라이선스에 동의하려면 상자에 체크해 주세요." + +msgid "Enter your email address." +msgstr "이메일 주소를 입력해 주세요." + +msgid "The license is already accepted on this Teaport." +msgstr "이 Teaport에서는 이미 라이선스에 동의했어요." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "이 Teaport에서는 라이선스에 동의할 수 없어요." + +msgid "The license changed while you were reading it. Read it again." +msgstr "읽는 동안 라이선스가 바뀌었어요. 다시 읽어 주세요." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport가 지금은 라이선스를 보여 줄 수 없어요. 온라인이 된 뒤 다시 시도해 주세요." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI가 이 동의를 받지 않았어요. 라이선스를 다시 읽고 동의해 주세요." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport가 동의를 기록하지 못했어요. 다시 시도해 주세요." + +msgid "The license is accepted as {email}." +msgstr "{email}(으)로 라이선스에 동의했어요." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "본인이 아닌가요? 라이선스를 읽고 본인 이메일 주소로 다시 동의해 주세요." + +msgid "Accept again" +msgstr "다시 동의하기" + +msgid "Accept the license first, then create your login." +msgstr "먼저 라이선스에 동의한 다음 로그인을 만드세요." + +msgid "What will you use Teaport for?" +msgstr "Teaport를 어디에 사용하시나요?" + +msgid "Personal use" +msgstr "개인 용도" + +msgid "A business" +msgstr "사업 용도" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Teaport를 개인 용도로 쓸지 사업 용도로 쓸지 선택해 주세요." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport가 동의를 기록하는 중이에요. 잠시 후 다시 시도해 주세요." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "이 Teaport의 라이선스 연결이 끊겼어요. Teaport 비밀 정보의 복사본으로 라이선스 키가 연결됐어요. 되찾으려면 Teaspoon AI 지원팀에 문의해 주세요." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "이 Teaport의 라이선스 연결에 실패했어요. Teaspoon AI 지원팀에 문의해 주세요." diff --git a/brain/teaport_brain/locale/nl/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/nl/LC_MESSAGES/teaport.mo index 8cbd8010..d9b2ff71 100644 Binary files a/brain/teaport_brain/locale/nl/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/nl/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/nl/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/nl/LC_MESSAGES/teaport.po index c540770b..ac21fbf2 100644 --- a/brain/teaport_brain/locale/nl/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/nl/LC_MESSAGES/teaport.po @@ -861,3 +861,90 @@ msgstr "Teaport kon je login niet aanmaken. Probeer het opnieuw." msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport kon je login niet aanmaken. Je kunt nu verbinding maken en je login later aanmaken in Instellingen." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "Lees de licentie" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "De spraakengine van Teaport wordt geleverd met de Teaport Engine License. Lees die en accepteer die om het instellen van Teaport af te ronden." + +msgid "Your email address" +msgstr "Je e-mailadres" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI legt met dit adres vast wie de licentie heeft geaccepteerd." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "Ik heb de Teaport Engine License gelezen en ga ermee akkoord." + +msgid "I accept" +msgstr "Ik ga akkoord" + +msgid "Recording your acceptance…" +msgstr "Je akkoord wordt vastgelegd…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "Bedankt. Je akkoord met de licentie is vastgelegd." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "Bedankt. Teaport legt je akkoord bij Teaspoon AI vast zodra Teaport online is." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Je leest en accepteert de Teaport Engine License in Instellingen zodra Teaport online is." + +msgid "Tick the box to accept the license." +msgstr "Vink het vakje aan om de licentie te accepteren." + +msgid "Enter your email address." +msgstr "Vul je e-mailadres in." + +msgid "The license is already accepted on this Teaport." +msgstr "De licentie is op deze Teaport al geaccepteerd." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "De licentie accepteren is op deze Teaport niet beschikbaar." + +msgid "The license changed while you were reading it. Read it again." +msgstr "De licentie is veranderd terwijl je die las. Lees die opnieuw." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport kan de licentie nu niet tonen. Probeer het opnieuw zodra Teaport online is." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI heeft dit akkoord niet aangenomen. Lees de licentie opnieuw en accepteer die." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport kon je akkoord niet vastleggen. Probeer het opnieuw." + +msgid "The license is accepted as {email}." +msgstr "De licentie is geaccepteerd als {email}." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "Ben jij dit niet? Lees de licentie en accepteer die opnieuw met je eigen e-mailadres." + +msgid "Accept again" +msgstr "Opnieuw accepteren" + +msgid "Accept the license first, then create your login." +msgstr "Accepteer eerst de licentie en maak daarna je login aan." + +msgid "What will you use Teaport for?" +msgstr "Waarvoor ga je Teaport gebruiken?" + +msgid "Personal use" +msgstr "Persoonlijk gebruik" + +msgid "A business" +msgstr "Een bedrijf" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Kies of Teaport voor persoonlijk gebruik of voor een bedrijf is." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport legt al een akkoord vast. Probeer het zo opnieuw." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "De licentiekoppeling van deze Teaport is kwijt: de licentiesleutel is gekoppeld met een kopie van het geheim van de Teaport. Neem contact op met de support van Teaspoon AI om hem terug te krijgen." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "De licentiekoppeling van deze Teaport is mislukt. Neem contact op met de support van Teaspoon AI." diff --git a/brain/teaport_brain/locale/pt_BR/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/pt_BR/LC_MESSAGES/teaport.mo index 93bcd196..0a666e05 100644 Binary files a/brain/teaport_brain/locale/pt_BR/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/pt_BR/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/pt_BR/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/pt_BR/LC_MESSAGES/teaport.po index 5030ab17..7178dd5b 100644 --- a/brain/teaport_brain/locale/pt_BR/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/pt_BR/LC_MESSAGES/teaport.po @@ -861,3 +861,90 @@ msgstr "O Teaport não conseguiu criar seu login. Tente de novo." msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "O Teaport não conseguiu criar seu login. Você pode se conectar agora e criá-lo depois, em Configurações." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "Leia a licença" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "O mecanismo de voz do Teaport vem com a Teaport Engine License. Leia e aceite a licença para terminar de configurar o Teaport." + +msgid "Your email address" +msgstr "Seu endereço de e-mail" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "A Teaspoon AI registra quem aceitou a licença, com este endereço." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "Li a Teaport Engine License e a aceito." + +msgid "I accept" +msgstr "Aceito" + +msgid "Recording your acceptance…" +msgstr "Registrando sua aceitação…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "Obrigado. Sua aceitação da licença foi registrada." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "Obrigado. O Teaport registra sua aceitação com a Teaspoon AI assim que estiver online." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Você vai ler e aceitar a Teaport Engine License em Configurações assim que o Teaport estiver online." + +msgid "Tick the box to accept the license." +msgstr "Marque a caixa para aceitar a licença." + +msgid "Enter your email address." +msgstr "Digite seu endereço de e-mail." + +msgid "The license is already accepted on this Teaport." +msgstr "A licença já foi aceita neste Teaport." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "Aceitar a licença não está disponível neste Teaport." + +msgid "The license changed while you were reading it. Read it again." +msgstr "A licença mudou enquanto você a lia. Leia de novo." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "O Teaport não consegue mostrar a licença agora. Tente de novo quando ele estiver online." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "A Teaspoon AI não aceitou este registro. Leia a licença de novo e aceite-a." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "O Teaport não conseguiu registrar sua aceitação. Tente de novo." + +msgid "The license is accepted as {email}." +msgstr "A licença foi aceita como {email}." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "Não é você? Leia a licença e aceite-a de novo com o seu próprio e-mail." + +msgid "Accept again" +msgstr "Aceitar de novo" + +msgid "Accept the license first, then create your login." +msgstr "Aceite a licença primeiro e depois crie seu login." + +msgid "What will you use Teaport for?" +msgstr "Para que você vai usar o Teaport?" + +msgid "Personal use" +msgstr "Uso pessoal" + +msgid "A business" +msgstr "Uma empresa" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Escolha se o Teaport é para uso pessoal ou para uma empresa." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "O Teaport está registrando uma aceitação. Tente de novo daqui a pouco." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "O vínculo de licença deste Teaport foi perdido: a chave de licença foi vinculada com uma cópia do segredo do Teaport. Fale com o suporte da Teaspoon AI para recuperá-lo." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "O vínculo de licença deste Teaport falhou. Fale com o suporte da Teaspoon AI." diff --git a/brain/teaport_brain/locale/ru/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/ru/LC_MESSAGES/teaport.mo index 79bfa14a..73d5d037 100644 Binary files a/brain/teaport_brain/locale/ru/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/ru/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/ru/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/ru/LC_MESSAGES/teaport.po index ee546109..eaf475cc 100644 --- a/brain/teaport_brain/locale/ru/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/ru/LC_MESSAGES/teaport.po @@ -869,3 +869,90 @@ msgstr "Teaport не удалось создать учётную запись. msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport не удалось создать учётную запись. Можно подключиться сейчас и создать её позже в Настройках." +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "Прочитайте лицензию" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "Речевой движок Teaport поставляется с лицензией Teaport Engine License. Прочитайте её и примите, чтобы завершить настройку Teaport." + +msgid "Your email address" +msgstr "Ваш адрес электронной почты" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI записывает, кто принял лицензию, вместе с этим адресом." + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "Лицензия Teaport Engine License прочитана, и я её принимаю." + +msgid "I accept" +msgstr "Я принимаю" + +msgid "Recording your acceptance…" +msgstr "Записываем ваше согласие…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "Спасибо. Ваше согласие с лицензией записано." + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "Спасибо. Teaport передаст ваше согласие в Teaspoon AI, как только будет в сети." + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Вы прочитаете и примете Teaport Engine License в Настройках, когда Teaport будет в сети." + +msgid "Tick the box to accept the license." +msgstr "Отметьте флажок, чтобы принять лицензию." + +msgid "Enter your email address." +msgstr "Введите адрес электронной почты." + +msgid "The license is already accepted on this Teaport." +msgstr "Лицензия на этом Teaport уже принята." + +msgid "Accepting the license isn't available on this Teaport." +msgstr "Принять лицензию на этом Teaport нельзя." + +msgid "The license changed while you were reading it. Read it again." +msgstr "Лицензия изменилась, пока вы её читали. Прочитайте её ещё раз." + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport сейчас не может показать лицензию. Попробуйте ещё раз, когда он будет в сети." + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI не приняла это согласие. Прочитайте лицензию ещё раз и примите её." + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport не удалось записать ваше согласие. Попробуйте ещё раз." + +msgid "The license is accepted as {email}." +msgstr "Лицензия принята как {email}." + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "Это не вы? Прочитайте лицензию и примите её ещё раз со своим адресом электронной почты." + +msgid "Accept again" +msgstr "Принять ещё раз" + +msgid "Accept the license first, then create your login." +msgstr "Сначала примите лицензию, затем создайте учётную запись." + +msgid "What will you use Teaport for?" +msgstr "Для чего вы будете использовать Teaport?" + +msgid "Personal use" +msgstr "Личное использование" + +msgid "A business" +msgstr "Компания" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "Выберите, для личного использования Teaport или для компании." + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport уже записывает согласие. Попробуйте ещё раз через минуту." + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "Привязка лицензии этого Teaport потеряна: его лицензионный ключ привязали с копией секрета Teaport. Обратитесь в поддержку Teaspoon AI, чтобы вернуть её." + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "Не удалось привязать лицензию этого Teaport. Обратитесь в поддержку Teaspoon AI." diff --git a/brain/teaport_brain/locale/zh/LC_MESSAGES/teaport.mo b/brain/teaport_brain/locale/zh/LC_MESSAGES/teaport.mo index 71916713..d7733d6b 100644 Binary files a/brain/teaport_brain/locale/zh/LC_MESSAGES/teaport.mo and b/brain/teaport_brain/locale/zh/LC_MESSAGES/teaport.mo differ diff --git a/brain/teaport_brain/locale/zh/LC_MESSAGES/teaport.po b/brain/teaport_brain/locale/zh/LC_MESSAGES/teaport.po index bbbd40ec..95d7e4b0 100644 --- a/brain/teaport_brain/locale/zh/LC_MESSAGES/teaport.po +++ b/brain/teaport_brain/locale/zh/LC_MESSAGES/teaport.po @@ -861,3 +861,90 @@ msgstr "Teaport 没能创建你的登录账户。请再试一次。" msgid "Teaport couldn't create your login. You can connect now and create it later in Settings." msgstr "Teaport 没能创建你的登录账户。你可以先连接,以后再到设置中创建。" +# The owner's license (#465): the setup page's step and the Settings card (owner_license.py). +msgid "Read the license" +msgstr "阅读许可协议" + +msgid "Teaport's speech engine comes with the Teaport Engine License. Read it, then accept it to finish setting up Teaport." +msgstr "Teaport 的语音引擎附带 Teaport Engine License。请阅读并接受它,以完成 Teaport 的设置。" + +msgid "Your email address" +msgstr "你的电子邮件地址" + +msgid "Teaspoon AI records who accepted the license, with this address." +msgstr "Teaspoon AI 会用这个地址记录是谁接受了许可协议。" + +msgid "I have read the Teaport Engine License and I accept it." +msgstr "我已阅读并接受 Teaport Engine License。" + +msgid "I accept" +msgstr "我接受" + +msgid "Recording your acceptance…" +msgstr "正在记录你的接受…" + +msgid "Thank you. Your acceptance of the license is recorded." +msgstr "谢谢。你对许可协议的接受已记录。" + +msgid "Thank you. Teaport records your acceptance with Teaspoon AI once it's online." +msgstr "谢谢。Teaport 联网后会将你的接受记录到 Teaspoon AI。" + +msgid "You'll read and accept the Teaport Engine License in Settings once Teaport is online." +msgstr "Teaport 联网后,你可以在设置中阅读并接受 Teaport Engine License。" + +msgid "Tick the box to accept the license." +msgstr "勾选方框以接受许可协议。" + +msgid "Enter your email address." +msgstr "请输入你的电子邮件地址。" + +msgid "The license is already accepted on this Teaport." +msgstr "这台 Teaport 上已接受过许可协议。" + +msgid "Accepting the license isn't available on this Teaport." +msgstr "这台 Teaport 上无法接受许可协议。" + +msgid "The license changed while you were reading it. Read it again." +msgstr "你阅读期间许可协议有了变化。请重新阅读。" + +msgid "Teaport can't show the license right now. Try again once it's online." +msgstr "Teaport 现在无法显示许可协议。请在联网后重试。" + +msgid "Teaspoon AI didn't take this acceptance. Read the license again and accept it." +msgstr "Teaspoon AI 没有接收这次接受。请重新阅读许可协议并接受。" + +msgid "Teaport couldn't record your acceptance. Try again." +msgstr "Teaport 没能记录你的接受。请再试一次。" + +msgid "The license is accepted as {email}." +msgstr "许可协议已由 {email} 接受。" + +msgid "Not you? Read the license and accept it again with your own email address." +msgstr "不是你?请阅读许可协议,并用你自己的电子邮件地址重新接受。" + +msgid "Accept again" +msgstr "重新接受" + +msgid "Accept the license first, then create your login." +msgstr "请先接受许可协议,再创建登录账户。" + +msgid "What will you use Teaport for?" +msgstr "你会把 Teaport 用于什么?" + +msgid "Personal use" +msgstr "个人使用" + +msgid "A business" +msgstr "企业使用" + +msgid "Choose whether Teaport is for personal use or for a business." +msgstr "请选择 Teaport 是个人使用还是企业使用。" + +msgid "Teaport is busy recording an acceptance. Try again in a moment." +msgstr "Teaport 正在记录一项接受。请稍后再试。" + +msgid "This Teaport's license link was lost: its license key was linked with a copy of the Teaport's secret. Contact Teaspoon AI support to get it back." +msgstr "这台 Teaport 的许可链接已丢失:有人用 Teaport 密钥的副本链接了它的许可证密钥。请联系 Teaspoon AI 支持以找回。" + +msgid "This Teaport's license link failed. Contact Teaspoon AI support." +msgstr "这台 Teaport 的许可链接失败了。请联系 Teaspoon AI 支持。" diff --git a/brain/teaport_brain/login_apply.py b/brain/teaport_brain/login_apply.py index de0989f0..a0f48bab 100644 --- a/brain/teaport_brain/login_apply.py +++ b/brain/teaport_brain/login_apply.py @@ -89,6 +89,18 @@ # let alone write there (it asks `status`). PENDING_PATH = "/var/lib/teaport-owner/pending" LOCK_PATH = "/run/teaport-login-apply/lock" +# The engine's license files (teaport#474 F1): nothing here writes, renames or removes them, +# whatever a path above comes to name. The same tuple in every root helper the run user +# reaches (license_link.PROTECTED is the one list; tests hold the copies to it). +PROTECTED = ("/etc/teaport/license.json", "/etc/teaport/license-revocations.json", + "/etc/teaport/license-link.secret") + + +def protected(path: str) -> bool: + """`path` is one of PROTECTED, by name or through a link.""" + return os.path.abspath(path) in PROTECTED or os.path.realpath(path) in PROTECTED + + # The brain's unit, whose User= is the run user: the login must not be that account. BRAIN_UNIT = "teaport-brain.service" # The minimum in characters, as the owner counts; the maximum in UTF-8 bytes, as PAM does @@ -282,6 +294,8 @@ def present(self) -> bool: return self._roots(directory, stat.S_ISDIR) and self._roots(marker, stat.S_ISREG) def remove(self) -> None: + if protected(self.path): + raise Refused(f"{self.path} is the engine's license, which this helper never removes") os.unlink(self.path) @@ -356,6 +370,8 @@ def handle(ops: Ops, marker: Marker, verb: str, req) -> dict: def _lock(path: str = LOCK_PATH) -> int: """An exclusive lock on root's own file, held until the process exits: two creates at once would each find no user, and the second's undo would remove the first's.""" + if protected(path): + raise Refused(f"{path} is the engine's license, which this helper never writes") os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) try: diff --git a/brain/teaport_brain/manifest_sig.py b/brain/teaport_brain/manifest_sig.py new file mode 100644 index 00000000..90524d32 --- /dev/null +++ b/brain/teaport_brain/manifest_sig.py @@ -0,0 +1,332 @@ +"""Is this release manifest the one the release keys signed? The one check, for everything +that reads a manifest. + +A release manifest (manifest/.json) names every artifact a box installs, and +`teaport update` and install.sh install them as root. So a manifest is trusted for what it +signs, not for where it was read: it is signed with an OpenSSH key kept offline +(`ssh-keygen -Y sign -n teaport-manifest`, see packaging/RELEASING.md), its signature sits +beside it as .sig, and the keys it may be signed with are the ones in the signers +file (manifest/allowed_signers in the repo, which the brain package ships as +/usr/lib/teaport/allowed_signers): a main key and a backup. Nothing is read out of a +manifest before its exact bytes have verified (`ssh-keygen -Y verify`), and a manifest +named .json must say it is that channel's: a signed stable manifest is no beta one. +A signed manifest names a release candidate's tag (brain-vX.Y.Z-rcN) only on the beta +channel, and a release tag's brain.deb is that version's package, X.Y.Z or X.Y.Z~rcN +(packaging/build-deb.sh's version, which nfpm puts in the file name). + +Who calls it: + - packaging/deb/update_apply.py, the updater's root step, loads this file from + /usr/lib/teaport/manifest_sig.py (a package file, root's) by its path; + - install.sh runs it from its own checkout: + python3 -I brain/teaport_brain/manifest_sig.py check \ + --source [--unsigned-ok] + - the brain's release check (updates.py) imports it, so a manifest that does not + verify shows as an error, never as an update; + - manifest/check.py, before the publish workflow uploads a manifest. + +A local manifest with no signature beside it is accepted only with --unsigned-ok (install.sh: +TEAPORT_MANIFEST_UNSIGNED=1, set by the person running it); a URL never is. + +Stdlib only, never imports the rest of the package: the root step runs it with the system +python3 from outside the brain's venv. +""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +import tempfile +from urllib.parse import urlparse + +# The signatures' namespaces: a key in the signers file signs nothing else for us. A +# manifest's signature is never a bootstrap's, nor the other way round. +NAMESPACE = "teaport-manifest" +BOOTSTRAP_NAMESPACE = "teaport-bootstrap" +# The trusted keys the brain package ships (the repo's manifest/allowed_signers). +SIGNERS = "/usr/lib/teaport/allowed_signers" +SSH_KEYGEN = "/usr/bin/ssh-keygen" +CHANNELS = ("stable", "beta") +# ssh-keygen with root's PATH and nothing of the caller's. +ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"} +TIMEOUT_SECS = 30 +# An SSH signature is a few hundred bytes; anything far larger is not one. +MAX_SIG_BYTES = 16 << 10 +# The mark the signers file carries until the real public keys are in it. +PLACEHOLDER = "PLACEHOLDER" + + +class SignatureError(Exception): + """The manifest is not one the release keys signed (or it cannot be told).""" + + +# The one shape a key line may have: a release principal (no pattern: ssh-keygen would read +# "*" or "a,b" as several), the two namespaces, an Ed25519 key, nothing else (no other option, +# no comment). ssh-keygen splits the file on "\n" only and skips only spaces and tabs before a +# "#", where Python's splitlines()/strip() also break on \x1c-\x1e, \x85, U+2028/9: so any +# byte outside printable ASCII and "\n" is refused before anything else is read, and the +# file is split on "\n" alone. What this accepts is what ssh-keygen trusts, line for line. +SIGNER_LINE = re.compile(rb'release-(main|backup) namespaces="teaport-manifest,teaport-bootstrap" ' + rb'ssh-ed25519 [A-Za-z0-9+/]+={0,2}') +_PRINTABLE = re.compile(rb"[ -~\n]*") +# A signers file is two lines; one over this is refused whole, never read in part. +MAX_SIGNERS_BYTES = 1 << 20 + + +def keys(signers) -> list[str]: + """The key lines of a signers file (bytes or str), read strictly: printable ASCII and "\n" + only, split on "\n" alone; a line is blank (spaces only), a comment ("#" first), or exactly + SIGNER_LINE, each principal at most once. Raises SignatureError for anything else, so a + file that fails is refused everywhere it is read.""" + data = signers.encode("utf-8", "surrogateescape") if isinstance(signers, str) else bytes(signers) + if len(data) > MAX_SIGNERS_BYTES: + raise SignatureError(f"the signers file is over {MAX_SIGNERS_BYTES} bytes: refused") + if not _PRINTABLE.fullmatch(data): + bad = next(i for i, b in enumerate(data) if not (32 <= b <= 126 or b == 10)) + raise SignatureError(f"the signers file has a byte that is not printable ASCII " + f"(0x{data[bad]:02x} at offset {bad}): refused") + found, seen = [], set() + for number, line in enumerate(data.split(b"\n"), 1): + if not line.strip(b" ") or line.startswith(b"#"): + continue + m = SIGNER_LINE.fullmatch(line) + if not m: + raise SignatureError(f"line {number} of the signers file is not a release key line " + f"(release-main or release-backup, the two namespaces, one " + f"ssh-ed25519 key): {line[:80].decode('ascii')!r}") + if m.group(1) in seen: + raise SignatureError(f"line {number} of the signers file names release-" + f"{m.group(1).decode()} a second time: refused") + seen.add(m.group(1)) + found.append(line.decode("ascii")) + return found + + +def is_local(source: str) -> bool: + """An absolute path or a file:// URL, as install.sh's fetch_manifest tells them from a + URL (anything else it hands to curl, so "host/path" is not local).""" + return source.startswith("/") or urlparse(source).scheme == "file" + + +def channel_named(source: str) -> str | None: + """The channel a manifest's name says it is (.json), else None.""" + name = os.path.basename(urlparse(source).path if not source.startswith("/") else source) + stem, ext = os.path.splitext(name) + return stem if ext == ".json" and stem in CHANNELS else None + + +def _keygen(args: list[str], data: bytes, keygen: str) -> subprocess.CompletedProcess: + try: + return subprocess.run([keygen, *args], input=data, capture_output=True, + timeout=TIMEOUT_SECS, env=ENV, cwd="/") + except FileNotFoundError: + raise SignatureError(f"cannot check the release manifest's signature: {keygen} is " + "missing (the openssh-client package)") from None + except (OSError, subprocess.SubprocessError) as e: + raise SignatureError(f"cannot check the release manifest's signature: {e}") from None + + +def verify(body: bytes, sig: bytes, signers: str, keygen: str = SSH_KEYGEN, + namespace: str = NAMESPACE) -> str: + """The principal of the signers file whose key signed exactly in + (a manifest's, unless said). Raises SignatureError.""" + try: + with open(signers, "rb") as f: + signers_bytes = f.read(MAX_SIGNERS_BYTES + 1) # one byte over is refused by keys() + except OSError as e: + raise SignatureError(f"cannot read the trusted signing keys ({signers}): {e}") from None + trusted = keys(signers_bytes) # strict: a file that fails is refused (SignatureError) + if not trusted: + raise SignatureError(f"no trusted signing key in {signers}: nothing can be verified") + if not sig or len(sig) > MAX_SIG_BYTES or b"-----BEGIN SSH SIGNATURE-----" not in sig: + raise SignatureError(f"the release {what(namespace)}'s signature is not an SSH signature") + with tempfile.TemporaryDirectory(prefix="teaport-sig-") as tmp: + sig_file = os.path.join(tmp, "manifest.sig") + with open(os.open(sig_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as f: + f.write(sig) + # ssh-keygen reads the bytes just checked, from a copy of its own, not the path again. + checked = os.path.join(tmp, "allowed_signers") + with open(os.open(checked, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as f: + f.write(signers_bytes) + found = _keygen(["-Y", "find-principals", "-s", sig_file, "-f", checked], b"", keygen) + principals = [p for p in found.stdout.decode("ascii", "replace").split("\n") if p] \ + if found.returncode == 0 else [] + if not principals: + raise SignatureError(f"the release {what(namespace)} is not signed by a trusted key ({signers})") + why = "" + for principal in principals: + p = _keygen(["-Y", "verify", "-f", checked, "-I", principal, "-n", namespace, + "-s", sig_file], body, keygen) + if p.returncode == 0: + return principal + said = (p.stderr or p.stdout).decode(errors="replace").strip().splitlines() + why = why or (said[0] if said else f"exit {p.returncode}") + raise SignatureError(f"the release {what(namespace)}'s signature does not verify ({why})") + + +def what(namespace: str) -> str: + return "installer (install-bootstrap.sh)" if namespace == BOOTSTRAP_NAMESPACE else "manifest" + + +def parse(body: bytes, channel: str | None) -> dict: + """The manifest's JSON object; when is given, one that says it is that + channel's. Raises SignatureError (a channel that does not match) or ValueError.""" + manifest = json.loads(body) + if not isinstance(manifest, dict): + raise ValueError("the release manifest is not a JSON object") + if channel is not None and manifest.get("channel") != channel: + raise SignatureError(f"the release manifest is signed for the {manifest.get('channel')!r} " + f"channel, not {channel!r}") + bad = bad_hashes(manifest) + if bad: + raise ValueError(f"the release manifest has a sha256 that is not 64 lowercase hex " + f"characters ({', '.join(bad)}): sha256sum would take it as more than one line") + return manifest + + +_SHA256 = re.compile(r"[0-9a-f]{64}") +# A release's tag, and the version of the package built from it (packaging/build-deb.sh): a +# candidate's brain-vX.Y.Z-rcN builds X.Y.Z~rcN, named teaport-brain_X.Y.Z~rcN_.deb. +RELEASE_TAG = re.compile(r"brain-v([0-9]+\.[0-9]+\.[0-9]+)(?:-rc([1-9][0-9]*))?") +_COMMIT = re.compile(r"[0-9a-f]{40}") +DEB_FILE = re.compile(r"teaport-brain_([0-9A-Za-z.~+-]+)_([a-z0-9]+)\.deb") + + +def release_version(tag) -> str | None: + """The package version builds (X.Y.Z, or X.Y.Z~rcN for brain-vX.Y.Z-rcN), or None + when it is no release tag.""" + m = RELEASE_TAG.fullmatch(tag) if isinstance(tag, str) else None + if not m: + return None + return m.group(1) + (f"~rc{m.group(2)}" if m.group(2) else "") + + +def release_problem(manifest: dict, channel: str | None = None) -> str | None: + """Why the signed names a release this channel may not install, or None: a + manifest that names a release (brain.commit a full commit id) whose brain.tag is no + release tag; a release candidate's tag (brain-vX.Y.Z-rcN) anywhere but on beta; a + brain.deb whose file name is not the version its release tag builds. defaults + to the manifest's own. A manifest that names no commit (the repository's placeholders) + names no release, and nothing installs from it.""" + channel = channel or manifest.get("channel") + brain = manifest.get("brain") if isinstance(manifest.get("brain"), dict) else {} + tag = brain.get("tag") + version = release_version(tag) + if version is None: + if isinstance(brain.get("commit"), str) and _COMMIT.fullmatch(brain["commit"]): + return (f"brain.tag {tag!r} is not a release tag (brain-vX.Y.Z, or brain-vX.Y.Z-rcN on the " + "beta channel)") + return None + if "~rc" in version and channel != "beta": + return (f"brain.tag {tag} is a release candidate: only the beta channel names one, and the " + f"{channel} channel names a final brain-vX.Y.Z") + deb = brain.get("deb") if isinstance(brain.get("deb"), dict) else {} + url = deb.get("url") + if not isinstance(url, str) or "TODO" in url: + return None + name = url.rsplit("/", 1)[-1] + m = DEB_FILE.fullmatch(name) + if not m or m.group(1) != version: + return (f"brain.deb {name!r} is not teaport-brain_{version}_.deb, the package {tag} " + "builds") + return None + + +def bad_hashes(node, path="") -> list[str]: + """Where (a manifest) has a sha256 value (a "sha256" or "*_sha256" key, or an entry + of an "*_sha256" map) that is neither 64 lowercase hex characters nor the "TODO" + placeholder. install.sh hands these to sha256sum -c, which reads a value with a newline + in it as several lines and passes once one of them checks out.""" + out = [] + if isinstance(node, dict): + for key, value in node.items(): + where = f"{path}.{key}" if path else str(key) + if isinstance(key, str) and (key == "sha256" or key.endswith("_sha256")): + for sub, v in (value.items() if isinstance(value, dict) else [("", value)]): + if v != "TODO" and not (isinstance(v, str) and _SHA256.fullmatch(v)): + out.append(f"{where}.{sub}" if sub else where) + else: + out += bad_hashes(value, where) + elif isinstance(node, list): + for i, value in enumerate(node): + out += bad_hashes(value, f"{path}[{i}]") + return out + + +def accept(body: bytes, sig: bytes | None, source: str, signers: str = SIGNERS, *, + channel: str | None = None, unsigned_ok: bool = False, + keygen: str = SSH_KEYGEN) -> tuple[dict, str]: + """The manifest read from , once its signature (None: there is none) + has verified, and what was checked, to say. defaults to the one the + source's name says. Only a local source may go without a signature, and only with + . Raises SignatureError or ValueError (not JSON).""" + if channel is None: + channel = channel_named(source) + if sig is None: + if not (unsigned_ok and is_local(source)): + raise SignatureError(f"the release manifest has no signature ({source}.sig): nothing " + "is installed from an unsigned manifest") + return parse(body, channel), f"{source} is not signed: accepted as given (unsigned allowed)" + principal = verify(body, sig, signers, keygen) + manifest = parse(body, channel) + problem = release_problem(manifest, channel) + if problem: + raise SignatureError(f"the signed release manifest is refused: {problem}") + return manifest, f"signed by {principal} (trusted keys: {signers})" + + +def main(argv: list[str]) -> int: + """check [--source S] [--channel C] [--unsigned-ok]: + exit 0 and say who signed it, or 1 and why not. A that does not exist is no + signature. signers : the number of keys in it, read as verify() reads it (exit 1 + when it is refused).""" + usage = ("usage: manifest_sig.py check [--source S] " + "[--channel stable|beta] [--unsigned-ok]\n" + " manifest_sig.py signers (read it strictly; print its key count)") + if len(argv) == 2 and argv[0] == "signers": + try: + with open(argv[1], "rb") as f: + print(len(keys(f.read(MAX_SIGNERS_BYTES + 1)))) + except (OSError, SignatureError) as e: + print(str(e), file=sys.stderr) + return 1 + return 0 + if len(argv) < 4 or argv[0] != "check": + print(usage, file=sys.stderr) + return 2 + manifest, sig_path, signers = argv[1:4] + source, channel, unsigned_ok, rest = manifest, None, False, argv[4:] + while rest: + arg = rest.pop(0) + if arg == "--unsigned-ok": + unsigned_ok = True + elif arg in ("--source", "--channel") and rest: + value = rest.pop(0) + if arg == "--source": + source = value + elif value in CHANNELS: + channel = value + else: + print(f"unknown channel: {value}", file=sys.stderr) + return 2 + else: + print(usage, file=sys.stderr) + return 2 + try: + with open(manifest, "rb") as f: + body = f.read() + sig = None + if os.path.exists(sig_path): + with open(sig_path, "rb") as f: + sig = f.read(MAX_SIG_BYTES + 1) + _, said = accept(body, sig, source, signers, channel=channel, unsigned_ok=unsigned_ok) + except (SignatureError, ValueError, OSError) as e: + print(str(e), file=sys.stderr) + return 1 + print(said) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/brain/teaport_brain/owner_license.py b/brain/teaport_brain/owner_license.py new file mode 100644 index 00000000..e3fc4271 --- /dev/null +++ b/brain/teaport_brain/owner_license.py @@ -0,0 +1,175 @@ +# +# teaport — the owner accepts the Teaport Engine License at setup (#465), from the run +# user's side: what the setup page (wifi_setup.py, offline) and Settings (config_ui.py, +# online) share -- whether the step is offered, the license's text, accepting it, and the +# words the owner reads about it. +# +# The recording is license_accept.py's, as root, behind its sudoers line: it takes the +# owner's email, makes POST /api/accept itself (or queues it, offline) and records the id +# the license server returns. Then license_link.py, the same way, puts that acceptance on +# the box's appliance key. The run user is the agent's: it may ask, never decide, and it +# never names an acceptance. The email goes to the helper and nowhere else (no log line, no +# answer). Only setup is held up until the owner accepts: the engine runs all the while, +# under the appliance key the box shipped with (#474, the owner's decision 2026-11-28). +# No Pipecat import: the setup unit runs this alone on a box short of memory. +# +from teaport_brain import license_accept, license_link, root_helper +from teaport_brain.i18n import N_ + +# The root-owned copies the sudoers lines name (packaging/deb/sudoers-sync). +ACCEPT_HELPER = "/usr/lib/teaport/license_accept.py" +LINK_HELPER = "/usr/lib/teaport/license_link.py" +# Each helper's longest path: the wait for the send lock, then a manifest, the text and the +# POST, each to its own limit, and a margin for python's start: a caller that gave up first +# would kill the helper mid-POST. +HELPER_SECS = license_accept.LOCK_SECS + 3 * license_accept.NET_SECS + 15 +HELPER_STOP_SECS = 10 +PENDING, QUEUED, RECORDED, NOT_OFFERED = (license_accept.PENDING, license_accept.QUEUED, + license_accept.RECORDED, license_accept.NOT_OFFERED) +# Why an acceptance did not happen, beyond the helper's codes: the box was not ticked. +UNTICKED = "unticked" + +# What the owner reads, in their language (say()). +TEXT = { + "title": N_("Read the license"), + "intro": N_("Teaport's speech engine comes with the Teaport Engine License. Read it, " + "then accept it to finish setting up Teaport."), + "email": N_("Your email address"), + "email_note": N_("Teaspoon AI records who accepted the license, with this address."), + # What the owner uses the box for (license_accept.OWNER_USES): recorded with the + # acceptance, never with a license id. + "use": N_("What will you use Teaport for?"), + "use_personal": N_("Personal use"), + "use_business": N_("A business"), + "tick": N_("I have read the Teaport Engine License and I accept it."), + "accept": N_("I accept"), + "accepting": N_("Recording your acceptance…"), + "recorded": N_("Thank you. Your acceptance of the license is recorded."), + "queued": N_("Thank you. Teaport records your acceptance with Teaspoon AI once it's online."), + # The setup page, offline, on a box that has no copy of the license yet. + "later": N_("You'll read and accept the Teaport Engine License in Settings once Teaport " + "is online."), + # The acceptance on the box, its email masked (license_accept.mask), while it may still be + # replaced: an agent could have accepted first (license_accept.py's module comment). + "accepted_as": N_("The license is accepted as {email}."), + "not_you": N_("Not you? Read the license and accept it again with your own email address."), + "again": N_("Accept again"), + # The box's secret no longer links its key (license_link.LOST): someone linked it with a + # copy; support gives the owner a recovery code. + "link_lost": N_("This Teaport's license link was lost: its license key was linked with a copy " + "of the Teaport's secret. Contact Teaspoon AI support to get it back."), + # A secret that never linked, refused, its cause unknown (license_link.CAUSE_UNKNOWN): + # neutral words, the cause is support's to find. + "link_failed": N_("This Teaport's license link failed. Contact Teaspoon AI support."), + # Settings' login card while the license waits (the login comes after it, as on the page). + "login_first": N_("Accept the license first, then create your login."), +} +WHY = { + UNTICKED: N_("Tick the box to accept the license."), + license_accept.EMAIL_BAD: N_("Enter your email address."), + license_accept.ACCEPTED: N_("The license is already accepted on this Teaport."), + license_accept.NOT_OFFERED: N_("Accepting the license isn't available on this Teaport."), + license_accept.CHANGED: N_("The license changed while you were reading it. Read it again."), + license_accept.UNAVAILABLE: N_("Teaport can't show the license right now. Try again " + "once it's online."), + license_accept.DROPPED: N_("Teaspoon AI didn't take this acceptance. Read the license " + "again and accept it."), + license_accept.FAILED: N_("Teaport couldn't record your acceptance. Try again."), + license_accept.USE: N_("Choose whether Teaport is for personal use or for a business."), + license_accept.BUSY: N_("Teaport is busy recording an acceptance. Try again in a moment."), + license_accept.REFUSED: N_("Teaport couldn't record your acceptance. Try again."), +} + + +def say(t, msgid: str, **fill) -> str: + """`msgid` (one of TEXT's or WHY's) in t's language, its placeholders ({email}) filled in.""" + text = t._(msgid) + return text.format(**fill) if fill else text + + +def sudo_helper(helper: str, verb: str, req: dict) -> dict: + return root_helper.call(helper, verb, req, timeout=HELPER_SECS, + stop_secs=HELPER_STOP_SECS, name="the license helper") + + +class License: + """The owner's acceptance. `accept_helper` and `link_helper` (verb, req) -> reply are + injectable; given `box` (and `link_box`, tests), the requests run in-process through + the helpers' handle().""" + + def __init__(self, accept_helper=None, link_helper=None, box=None, link_box=None): + if accept_helper is None: + accept_helper = (self._in_process(license_accept, box) if box is not None + else lambda verb, req: sudo_helper(ACCEPT_HELPER, verb, req)) + if link_helper is None: + link_helper = (self._in_process(license_link, link_box) if link_box is not None + else lambda verb, req: sudo_helper(LINK_HELPER, verb, req)) + self._accept, self._link = accept_helper, link_helper + + @staticmethod + def _in_process(module, box): + def call(verb: str, req: dict) -> dict: + try: + return module.handle(box, verb, req) + except module.Refused as e: + return {"ok": False, "err": str(e), "why": e.why} + return call + + def state(self) -> str: + """PENDING, QUEUED, RECORDED or NOT_OFFERED. A helper that cannot answer (no sudoers + line, an install without it) offers nothing: the step is only shown when it can work.""" + state = self._accept("status", {}).get("state") + return state if state in (PENDING, QUEUED, RECORDED) else NOT_OFFERED + + def pending(self) -> bool: + return self.state() == PENDING + + def accepted(self) -> dict | None: + """{email: masked, replaceable} of the acceptance on the box, while setup is + unfinished (queued or recorded); None for none, or a helper that cannot answer.""" + r = self._accept("status", {}) + if r.get("state") not in (QUEUED, RECORDED) or not isinstance(r.get("email"), str): + return None + return {"email": r["email"], "replaceable": r.get("replaceable") is True} + + def text(self) -> dict | None: + """{version, sha256, text} of the license to accept now, or None (no copy on the box + and no way to fetch one, or nothing offered).""" + r = self._accept("text", {}) + if isinstance(r.get("text"), str) and isinstance(r.get("sha256"), str): + return {"version": r.get("version"), "sha256": r["sha256"], "text": r["text"]} + return None + + def accept(self, email: str, sha256: str, ticked: bool, owner_use: str | None = None, + replace: bool = False) -> tuple[bool, str]: + """(True, QUEUED or RECORDED) once the acceptance is on the box, else (False, a WHY + code). `owner_use`: personal or business, as the owner chose. `replace`: in place of + the one on the box ("Not you? Accept again", while the + helper says it may). Recorded: linked to the box's key at once (link(); a link that + fails is retried by the timer, and never undoes the acceptance).""" + if not ticked: + return False, UNTICKED + if not license_accept.valid_email(email): + return False, license_accept.EMAIL_BAD + if owner_use not in license_accept.OWNER_USES: + return False, license_accept.USE + r = self._accept("accept", {"email": email.strip(), "eula_sha256": sha256, "owner_use": owner_use, + "replace": replace is True}) + if r.get("ok") is True and r.get("state") in (QUEUED, RECORDED): + if r["state"] == RECORDED: + self.link() + return True, r["state"] + why = r.get("why") + return False, why if why in WHY else license_accept.FAILED + + def link_lost(self) -> str | None: + """The box's secret no longer links its key (license_link.LOST): the TEXT that says + why ("link_lost", or "link_failed" for a secret that never linked, cause unknown).""" + r = self._link("status", {}) + if r.get("state") != license_link.LOST: + return None + return "link_failed" if r.get("why") == license_link.CAUSE_UNKNOWN else "link_lost" + + def link(self) -> bool: + """The recorded acceptance on the box's key, through the link helper: whether it is.""" + return self._link("link", {}).get("linked") is True diff --git a/brain/teaport_brain/static/config.html b/brain/teaport_brain/static/config.html index 7c011734..ca942247 100644 --- a/brain/teaport_brain/static/config.html +++ b/brain/teaport_brain/static/config.html @@ -323,6 +323,11 @@ .account .acct-msg.ok { color: var(--ok-ink); } .account .acct-connect { display: grid; gap: 8px; max-width: 560px; margin: 16px 0 0; } .account .acct-connect .btn-primary { justify-self: start; } + /* The license the owner accepts (#465): its whole text, in a box of its own that scrolls. */ + .account .eula-text { max-height: 320px; overflow: auto; margin: 16px 0 0; padding: 12px; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; line-height: 1.5; border: 1px solid var(--border-strong); border-radius: var(--control-radius); background: var(--surface); font-family: var(--mono); } + .account .eula-tick { display: flex; gap: 8px; align-items: flex-start; } + .account .eula-use { border: 0; margin: 0; padding: 0; display: grid; gap: 6px; } + .account .eula-use legend { padding: 0; margin: 0 0 4px; } .account .banner { margin: 12px 0 0; } .account > .group-blurb + .group-blurb { margin-top: 10px; } .adv-toggle { margin: 0 0 24px; } @@ -366,6 +371,7 @@

This box asks for its token