diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 6950b79..417a58f 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -10,6 +10,8 @@ env: TETHER_PUB_KEY: ${{ secrets.TETHER_PUB_KEY }} TETHER_ADMIN_PUB_KEY: ${{ secrets.TETHER_ADMIN_PUB_KEY }} TETHER_UPDATER_PUB_KEY: ${{ secrets.TETHER_UPDATER_PUB_KEY }} + # Optional repository variable: build Tether-, installable beside the default app (build.rs). + TETHER_INSTANCE: ${{ vars.TETHER_INSTANCE }} # Only whether the signing secrets exist (for `if:`); the secrets themselves go to the signing steps alone. HAVE_SIGNPATH: ${{ secrets.SIGNPATH_API_TOKEN != '' }} HAVE_WINDOWS_P12: ${{ secrets.WINDOWS_SIGNING_P12 != '' }} @@ -33,6 +35,9 @@ jobs: with: { targets: "${{ matrix.target }}" } - uses: actions/setup-node@v4 with: { node-version: 22, cache: npm, cache-dependency-path: apps/desktop/package-lock.json } + - name: Installer hooks name no app literally (instance builds) + shell: bash + run: bash scripts/check-hooks.sh - name: Fetch pinned sources and apply patches shell: bash run: bash scripts/bootstrap.sh @@ -64,7 +69,14 @@ jobs: - name: Bundle working-directory: apps/desktop shell: bash - run: npx tauri build --target ${{ matrix.target }} --bundles nsis + run: | + config=$(bash ../../scripts/instance-config.sh "$TETHER_INSTANCE") + npx tauri build --target ${{ matrix.target }} --bundles nsis ${config:+--config "$config"} + # The release index takes only Tether__x64-setup.exe, for an instance build too. + if [ -n "$TETHER_INSTANCE" ]; then + cd src-tauri/target/${{ matrix.target }}/release/bundle/nsis + for f in "Tether-${TETHER_INSTANCE}_"*_x64-setup.exe; do mv "$f" "Tether_${f#"Tether-${TETHER_INSTANCE}_"}"; done + fi # Free self-signed Authenticode (scripts/make-windows-cert.ps1), mirroring the macOS cert. # Gives a stable publisher identity and full trust on fleets that deploy the .cer (GPO/Intune); # inert without the secret. Superseded by the SignPath step below once that is approved. @@ -126,7 +138,7 @@ jobs: # Unsigned universal build (Apple silicon + Intel), the same script as on a developer Mac. macos: - runs-on: macos-14 + runs-on: macos-15 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@stable @@ -176,6 +188,8 @@ jobs: name: tether-macos-universal path: dist/macos/* - name: Smoke test (window shown, no admin prompt) + # It checks Tether.app; an instance build ships Tether-.app. + if: env.TETHER_INSTANCE == '' shell: bash run: bash scripts/smoke-macos.sh dist/macos - uses: actions/upload-artifact@v4 diff --git a/.github/workflows/mac-smoke.yml b/.github/workflows/mac-smoke.yml index 00f6c9f..252ac62 100644 --- a/.github/workflows/mac-smoke.yml +++ b/.github/workflows/mac-smoke.yml @@ -7,7 +7,7 @@ on: permissions: { contents: read, actions: read } jobs: smoke: - runs-on: macos-14 + runs-on: macos-15 steps: - uses: actions/checkout@v4 - uses: actions/download-artifact@v4 diff --git a/.github/workflows/macos-smoke.yml b/.github/workflows/macos-smoke.yml index 62158c9..b2f4d21 100644 --- a/.github/workflows/macos-smoke.yml +++ b/.github/workflows/macos-smoke.yml @@ -7,7 +7,7 @@ on: permissions: { contents: read, actions: read } jobs: smoke: - runs-on: macos-14 + runs-on: macos-15 steps: - uses: actions/checkout@v4 - uses: actions/download-artifact@v4 diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml index 195ba67..dfe6a06 100644 --- a/.github/workflows/server.yml +++ b/.github/workflows/server.yml @@ -2,7 +2,10 @@ name: server on: push: branches: [main] - paths: [server/**, vendor/**, crates/**, patches/**, scripts/**, tools/macbuild/**, .github/workflows/server.yml] + paths: [server/**, vendor/**, crates/**, patches/**, scripts/**, tools/macbuild/**, tools/monitor-publish/**, tools/load/**, apps/manage/src-tauri/src/keys.rs, .github/workflows/server.yml] + # Pull requests that touch the relay, the device-status tools or the shared crates. + pull_request: + paths: [server/**, crates/**, scripts/**, tools/monitor-publish/**, tools/load/**, apps/manage/src-tauri/src/keys.rs, .github/workflows/server.yml] workflow_dispatch: permissions: @@ -25,6 +28,14 @@ jobs: - name: Test tether-trust working-directory: crates/tether-trust run: cargo test --release + # The device-status admin tool: unit tests, then end to end against the tether-api built above. + - name: Test tools/monitor-publish + working-directory: tools/monitor-publish + run: | + cargo test --release + TETHER_API_BIN="$RUNNER_TEMP/relay/bin/tether-api" cargo test --release --test e2e -- --ignored + - name: Build the status load generator (tools/load/status-run.sh runs it by hand) + run: cargo build --release --manifest-path tools/load/status-load/Cargo.toml # The Mac build runner and its client (stdlib + ssh-keygen, no network). - name: Test tools/macbuild run: python3 -m unittest discover -s tools/macbuild diff --git a/CHANGELOG.md b/CHANGELOG.md index 1955315..27834ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,107 @@ from 0.6.0 Tether, TetherQS and Tether Manage share one version, kept in sync in ## [Unreleased] +### Device health (not in a numbered version yet) + +- **Health of supported machines in the host list.** A relay can now store health reports from a + monitoring agent, a separate program that is not part of Tether: a device enrols once with a + short-lived token an administrator creates (`scripts/status-token.sh`), signing the enrolment + with its own key, then signs every report with it (`Tether-Sig: device-v1`; an enrolment without + it gets `401 enrolment needs the device's signature`, so enrolling proves possession of the key + being pinned). The host list shows a health dot and Health, + Products and Agent columns, finds hosts with `health:`, `product:`, `version:`, `role:`, + `check:`, `agent:` and `since:`, and has a built-in view *Needs attention* (critical, not + reporting, or in a link conflict). The host detail gains a Health section with the failing checks first, setup items, + 90 days of history, all checks and the raw report; a session window has a Health button; the + export adds health fields and a CSV with one row per failing check. On Windows Tether notifies + when a host turns critical or stops reporting, at most once per host and hour; a switch in the + team dialog turns it off. Machines with an agent but without Tether appear as rows without a + connect action. `role:` used to be a plain word that found tags; it now means the detected + role (`#role:server` still finds the tag) in the search box; in tag rules all the new terms stay + plain words as before, so shared rules tag the same hosts on older desktops. + Needs the technician to be in the team roster. Report format, relay settings and operation: + [docs/health.md](docs/health.md). +- **Relay (tether-api).** New routes `POST /api/status/enroll`, `POST` and `DELETE /api/status`, + `GET /api/team/status[/]` and `DELETE /api/admin/status/` + ([docs/api.md](docs/api.md#device-status-health-reports)). The relay paces the devices + (`STATUS_TARGET_RPS`, default 10 posts per second), keeps heartbeats in memory, writes + `seen.json`, the summary cache, the compaction of `status/keys.jsonl` and history trimming + off the request path, caps enrolment (`STATUS_MAX_DEVICES`, default 20 000) and can switch the + whole feature off (`STATUS=off`). A pin or revocation file it cannot read (`keys.jsonl`, `revoked.json`) locks only the status routes (503); + sessions, policy and updates are not affected. New gauges `tether_api_status_hosts` and + `tether_api_status_write_errors`; `/api/team/*` requests are now counted as endpoint `team` + instead of `other`. Privacy and security: [PRIVACY.md](PRIVACY.md), + [SECURITY.md](SECURITY.md#device-status-health-reports). +- **A second signed release index per channel, `monitor.json`,** carries the agent + (`monitor/windows-x86_64`) and its check packs (`monitor-packs/any`). `releases.json` refuses + these keys and `monitor.json` refuses Tether's, so installed Tether clients never read it and + Tether's release generation does not move. Publish with `scripts/monitor-publish.sh` (it runs + `tools/monitor-publish`, which reads Tether Manage's key file); Tether Manage has no screen for + it yet. The new `Caddyfile` and `nginx.conf` route `monitor.json` to tether-api, + so they go out with it ([docs/updates.md](docs/updates.md#device-status-agent-monitorjson-and-enrolment-tokens)). + It expires 30 days after a publish: `monitor-publish refresh` (`scripts/monitor-refresh.sh`) + signs it again with a new expiry, the tool never publishes below the highest serial it ever + published (`monitor-serials.json`), and `tether_api_release_index_expires_timestamp{index="monitor"}` + shows the expiry. +- **Tokens can be revoked, Tether IDs are verified, devices can be removed.** An enrolment token + now carries a random id (required; tokens without one are refused) and can be issued for one + Tether ID (`--tether-id`): that token enrols one device, with exactly that ID. Tokens are + revoked with `monitor-publish revoke` (admin route `POST /api/admin/status/revoke`, kept in + `status/revoked.json`; a revoked token gets `401 token revoked`); devices that enrolled with it + stay until removed. A Tether ID that a device names with any other token is only a claim: the + host list shows the agent on a row of its own with "Claims to be …" and **Link to this host**, + which a team member with `write` confirms once (`POST /api/team/status//link`; the relay + records who and when, and the detail shows it with **Unlink**, which also dismisses the claim + until a member chooses **Allow a new claim**). Nothing links by itself, and a report cannot + change a link. Two devices linked to one Tether ID on different relays are shown as a **link + conflict**, joined to neither. Pins from before this change keep their Tether ID only as a claim. **Remove from health monitoring…** in the Health section (members + with `write`, `DELETE /api/team/status/`) and `monitor-publish remove` remove a device on + every relay; `monitor-publish devices` lists them (`GET /api/admin/status/devices`, paged) and + `monitor-publish tokens` the issued tokens (a local journal without the tokens themselves). + A bound token or a technician's confirmation is the word of a trusted person, not a proof by + Tether on the machine ([SECURITY.md](SECURITY.md#device-status-health-reports)). +- **Customer reference.** An enrolment token can name a customer (`monitor-publish token + --customer 4711`, or the 4th argument of `scripts/status-token.sh`; 1 to 32 characters + `A-Z a-z 0-9 . _ -`). The relay sets it on the device that enrols with the token, also on one + that is already enrolled (the journal says so). As every enrolment is signed with the device's + own key, a token holder who knows another device's uuid and public key can neither move it nor + create a pin for it. A token without one changes nothing, and a device + cannot name it. The team summary, the host detail and `GET /api/admin/status/devices` return + it; the host list has a Customer column, the search term `customer:` and the field in both + exports; `monitor-publish devices --customer` lists one customer's devices. A relay from before + this refuses a token with a customer: update tether-api first. Once a token with a customer has + been used, an older tether-api can no longer read `status/keys.jsonl` and locks the status + routes (503). It groups devices inside one + deployment and is not a security boundary + ([docs/health.md](docs/health.md#customer-reference), + [SECURITY.md](SECURITY.md#device-status-health-reports)). Separate organisations need separate + deployments: [docs/several-organisations.md](docs/several-organisations.md). +- Checked and not checked: to be filled in at release. + +### Instances: two organisations' Tether on one PC (not in a numbered version yet) + +- **`TETHER_INSTANCE`**, an optional build value (1 to 16 characters `a-z 0-9`), builds a + technician app that installs beside the default one or beside another instance: with `north` + it is `Tether-north` (`tether-north.exe`, identifier `app.tether.desktop.north`, link scheme + `tether-north://`) with its own device ID, settings folder, Windows service, firewall rule, + machine policy key (`HKLM\SOFTWARE\Policies\Tether-north`, macOS `net.tether.app.north`) and + recording folder. Unset, the build is unchanged. It must be built together with the + `--config` that `scripts/instance-config.sh` prints; the `desktop` workflow (repository + variable `TETHER_INSTANCE`) and `scripts/build-macos.sh` do both and rename the files to the + usual `Tether__…` names. The installer hooks name the app through `${PRODUCTNAME}` + only (`scripts/check-hooks.sh` in CI). Limits: of two builds on one PC only the one started + first gets direct connections (both use TCP 21118 and UDP 21119), `tether://` links open only + the default build, an existing install cannot become an instance, and each organisation + publishes only its own build + ([docs/several-organisations.md](docs/several-organisations.md#two-organisations-on-one-pc)). + A release build also checks that the Tauri product name matches the instance (`Tether` for + none, `Tether-` otherwise) and stops with a message when it does not. Checked: the + unit tests with and without the value, refused values, three real Windows bundle runs + (none installed): `north` with its `--config` built `Tether-north_0.6.3_x64-setup.exe`; + `north` without it stopped at the product-name check; the default build with north's + `--config` stopped at it. Not checked: installing it, two builds side by side, the service and firewall + rule on a real PC, updates, the macOS build. + ### 0.6.3 (2026-11-23; files in dist/, ready to publish; frozen) Six files in `dist/` (Windows setup and TetherQS signed; Mac files universal, as built by the diff --git a/PRIVACY.md b/PRIVACY.md index fd69950..5e6d1c6 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -12,6 +12,16 @@ What goes to those relay servers: | Screen, input, clipboard, files and audio of a session | The remote session itself; encrypted between the two devices, the relay only forwards it | not stored | | Session audit record: time, device, technician name, IP address, duration, names of transferred files, security alarms | Accountability of remote access (shown in Tether Manage) | daily files, kept for the retention the organization sets | | Update checks: app, channel, version | Offering signed updates | access logs of the relay | +| Health report, only on machines where the organization installed a monitoring agent: machine name, names and versions of installed products, the state, title, value and hint of each check, agent version, time of the last report | Showing the health of supported machines to technicians | the last full report and 90 days of state changes; removed when the device is removed or after 180 days without a report | +| Customer reference, only on machines where the organization installed a monitoring agent and its administrator put one in the enrolment token: a short label such as a customer number (set by the administrator, never by the machine) | Grouping supported machines by customer in Tether | with the device's enrolment: removed when the device is removed or after 180 days without a report | + +Health reports come from a separate monitoring agent, not from Tether or TetherQS, and only if the +organization installed it. They go to the same relay servers, are not end-to-end encrypted, and can be +read by the relay's operator and by every member of the organization's technician team in Tether. +What a report contains is decided by the agent; the format is described in [docs/health.md](docs/health.md). +When a technician links a monitoring agent to a host in Tether, the relay stores that technician's +name (as in the team roster) and the time with the device's enrolment; every team member sees it, +and it is removed with the device. Session recordings are made only when recording is switched on and are saved on the technician's computer. They are uploaded only if the organization's signed policy sets an upload target diff --git a/README.md b/README.md index 6acbfc3..f17a6f6 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,9 @@ in the middle. You run the relay; the apps talk only to it. installer, no admin rights. You can brand it: [docs/quick-support.md](docs/quick-support.md). - **Hundreds of hosts.** Tags, saved searches, bulk actions and a command palette: [docs/advanced.md](docs/advanced.md). +- **Health of supported machines.** A separate monitoring agent reports to your relay, and the host + list shows which machines need attention, with no inbound port on the machine: + [docs/health.md](docs/health.md). - **Central management.** Tether Manage signs policies and releases on the administrator's PC; the relay only serves them: [docs/management.md](docs/management.md). - **Also included:** unattended access, file transfer, recording with consent, 2FA, signed @@ -113,6 +116,8 @@ If Tether is useful to you, a star helps others find it. [docs/recording.md](docs/recording.md), [docs/cli.md](docs/cli.md), [docs/troubleshooting.md](docs/troubleshooting.md), [docs/api.md](docs/api.md), [docs/key-rotation.md](docs/key-rotation.md), [docs/upstream.md](docs/upstream.md) (RustDesk pin and upstream review), [docs/download-page.md](docs/download-page.md) (custom download page templates). +- **Several organisations:** one deployment each; no tenants inside a relay: + [docs/several-organisations.md](docs/several-organisations.md). - **Scale and HA:** several relays and Kubernetes: [docs/relay-ha.md](docs/relay-ha.md), [docs/kubernetes.md](docs/kubernetes.md); performance: [docs/performance.md](docs/performance.md); macOS build: [docs/macos.md](docs/macos.md); Mac builds from the PC while the Mac is locked (signed diff --git a/SECURITY.md b/SECURITY.md index 0a2fc65..8003987 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -21,6 +21,7 @@ is left. | Admin key, updater key | Tether Manage vault on the admin's PC (argon2id + XChaCha20-Poly1305) | | Host secrets at rest | Permanent password hash, 2FA secret, remembered passwords (obfuscated, see below) | | Metadata | Device IDs, IPs, machine uuids, connection times on hbbs/hbbr/tether-api; audit log | +| Device health reports | `status/` on each relay: pinned device keys, the last report and the history of each device that runs a monitoring agent; readable by the relay operator and team members | | Mac build signing material | Sent per job to the Mac build runner ([docs/mac-build-runner.md](docs/mac-build-runner.md)) | ### Trust boundaries @@ -154,6 +155,110 @@ never replaced (`apps/desktop/src-tauri/src/team.rs::key_at`). roster key, at most 500, under the state lock), body limits 64 KiB (roster) and 512 KiB (tags); `team/roster.json` and `team/tags.json` are `0600`. +### Device status (health reports) + +A monitoring agent on a machine can report its health to the relay ([docs/health.md](docs/health.md), +[docs/api.md](docs/api.md#device-status-health-reports)). It adds two kinds of caller to the relay: +devices that sign with their own key, and members that read what the devices posted. The feature +runs nothing on a device and opens no port on it. + +- **Device keys are pinned.** A device generates an Ed25519 key and enrols with an admin-signed + token, the request signed with that key: enrolling needs a valid token **and** the private key of + the key being pinned (without the signature: `401 enrolment needs the device's signature`). The + relay pins the key to the device's uuid in `status/keys.jsonl`. Every enrolment, report and removal is signed (`Tether-Sig: device-v1`, message prefix + `tether-device-v1`) over the relay's host name, the method, the path, the time, a nonce and the + body hash, so a captured request is worth nothing at another relay and cannot be replayed + (±300 s, nonces kept 601 s in memory, `seq` must increase on every post). A device key never + passes as an admin or member key, and an admin or member signature never passes on a device + route (separate prefix and header version, tested both ways). A second key for a pinned uuid or + Tether ID is refused (`409`). Only an admin-signed `DELETE /api/admin/status/`, a + member-signed `DELETE /api/team/status/` from a member with `write`, or the device's own + signed `DELETE /api/status` releases a pin; the journal names who did it. +- **Tether IDs are verified, not claimed.** A device's Tether ID, the only thing that puts its + health on a host row in the technician app, is set in two ways only: the admin issued the token + for that Tether ID (`tether_id` in the signed token; it enrols one device per relay, a second uuid gets + `409 token already used` there, and a request naming another ID `409 token is issued for another + id`; only its first use links, so it cannot undo a member's Unlink), or a roster member with `write` confirmed the device's claim + (`POST /api/team/status//link`, after one explicit confirmation in the app; the pin records + the member's name and the time). A Tether ID the device names with any other token is kept as + `claimed_id`, shown as a claim on a row of its own, and never joins a host row by itself. A + report can neither set nor change a Tether ID. A member's Unlink also dismisses the + claim (`no_claim`) until a member allows a new one; the same key under another uuid, with the + dismissed pin still there or after the device dropped it itself, comes back with `no_claim` + and claims nothing (the relay remembers dismissed keys). The boundary: a + holder of a valid enrolment token not issued for an ID can always enrol a *new* device (new + key) that claims any Tether ID. A claim joins nothing and is fixed for that device until a + technician acts; to stop claim rows from an unwanted source, revoke the token and remove its + devices (`monitor-publish devices --token `, `remove`). The app refuses to link a claim to + a host that already has a linked health agent, so a confirmed impostor cannot hide that host's + health behind a link conflict. Pin records from before verified IDs are + read with their Tether ID as a claim. **Single use is per relay:** each relay records a + token's use itself, so a copy of a token issued for one ID can link a second device on a relay + the first device has not enrolled on; the technician app then shows a link conflict and joins + neither device to the host. Give such tokens only to that machine and keep them short-lived. + **What this does not prove:** both ways are the word of + a trusted person (the admin who issued the token, the technician who confirmed), not a + cryptographic proof by Tether on that machine. A technician who confirms the claim of the wrong + agent shows that agent's reports on the wrong host until someone unlinks it. +- **What a token holder can do.** Enrol devices until the token expires or is revoked: any uuid + that is not pinned yet, up to 30 new pins per minute per IP and `STATUS_MAX_DEVICES` in total; + with a token issued for a Tether ID, one device with that ID. A token is valid 1 to 30 days and + can be **revoked** before that (`POST /api/admin/status/revoke`, `monitor-publish revoke`): + the relay then answers `401 token revoked`. Revoking does not remove the devices that enrolled + with it already; `monitor-publish devices --token ` lists them and `remove` removes them. + Issue tokens for as short as the rollout takes and treat them like a password. A holder can + fill the device cap, which makes `507` for devices that enrol later, and can make devices that + claim any Tether ID; a claim shows only as a claim until a member confirms it. With a token that + names a customer, every device it enrols is under that token's customer. +- **The customer reference is a grouping, not a boundary.** An admin-signed token may name a + customer (`customer`, 1 to 32 characters `[A-Za-z0-9._-]`); the relay sets it on the pin of the + device that enrols with it. A device cannot name or change it: neither the enrolment request nor + a report has the field, and a request with it is refused (`400`). A token holder can enrol new + devices, with new keys of their own, under the token's customer. Every enrolment is signed with + the private key of the key it pins (`Tether-Sig: device-v1`, as for a status post), so an + existing device's pin, link and customer cannot be taken or changed without that device's key: + the same device enrolling again with a token that names another customer (or any customer, when + it had none) gets it (journal: `status: customer of set to by token `; the + pin keeps the token it first enrolled with), and knowing a device's uuid and public key is not + enough to create a pin for it either, also where a relay has none (removed, dropped after 180 + days without a report, or never enrolled there). Every roster member sees every device whatever its customer: the customer + groups devices inside one deployment, and organisations that must not see each other's machines + need separate deployments ([docs/several-organisations.md](docs/several-organisations.md)). +- **What a token holder cannot do.** Read any report, summary or history (those routes need a + roster member's key). Replace or change an existing pin (its customer included, above), post as another device, remove a pin, + link a Tether ID, set or change the Tether ID of a pinned device (a report cannot), sign an + admin or member request, or reach anything outside the status routes. A device key holder can post, and remove + the pin of, that device only. A device's reports can therefore be forged by whoever controls + that machine (as for any agent); they are shown as what the device said, never as a fact the + relay checked. +- **Report content is untrusted.** The relay never parses the report's `body`: it checks that it + is a JSON object in valid UTF-8, stores it byte for byte (64 KiB at most) and returns it as it + is. The technician app shows every text from a report as plain text, shortened to fit. Nothing a + report says changes a device, a policy or an access decision. +- **Who can read reports.** The relay operator, who can read `status/`, and every member of the + team roster (no `write` or `audit` flag needed; linking, unlinking and removing a device need + `write`, refused with `403` otherwise). Reports are readable on the relay, not + end-to-end encrypted: machine name, installed product names and versions, check titles, values + and hints ([PRIVACY.md](PRIVACY.md)). An unauthenticated caller can tell whether a uuid is + enrolled (`401 unknown device` against `401 signature does not match`); uuids are not secrets. +- **Limits** (all before the signature check and the parser, so the cheap path stays cheap): + 64 KiB per post, one accepted post per uuid per 60 s, 10 correctly signed but refused posts per + uuid per minute, 60 failed signatures or unknown uuids per minute per IP (IPv6: per /64), 30 new + enrolments, refused tokens or unsigned enrolments per minute per IP. A forged post that names a device's uuid is not + counted against that device. The relay paces devices with `next` (`STATUS_TARGET_RPS`) and + `STATUS=off` turns every status route into `503` at once, before any body is read. +- **Fail closed.** When `status/keys.jsonl` or `status/revoked.json` cannot be read (anything but + a last line of `keys.jsonl` cut short by a crash), the status routes answer + `503 status store unavailable` and nothing under `status/` is written: an empty pin list would + hand every uuid to the next token holder, an empty revocation list would make revoked tokens + valid again. Sessions, policy and + updates are not affected. Recovery: restore or repair the file and restart tether-api + ([docs/health.md](docs/health.md#the-locked-state)). +- **The monitor release index** is signed like the Tether one and refused in the other direction: + `monitor.json` takes only the apps `monitor` and `monitor-packs`, `releases.json` only Tether's, + so the agent's files can never be offered to an installed Tether client. The agent verifies the + index, the size, the SHA-256 and the minisign signature of each artifact before installing. + ## Least privilege and attack surface Settings below are **forced** for every Tether process (UI, server, service and connection manager) @@ -442,6 +547,10 @@ Report vulnerabilities privately to the maintainers. Do not open a public issue. - While a relay accepts v1 request signatures, a captured admin or team request can be replayed at another relay within ±300 s. Remedy: update the relays first (with `RELAY_HOST`), then the apps, then set `TETHER_SIG_V1=off` (W14). +- A device's Tether ID in the health view rests on a token issued for that ID or on a + technician's confirmation, both the word of a trusted person, not a cryptographic proof by + Tether on that machine ([Device status](#device-status-health-reports)). Reports are readable + by the relay operator and every team member, not end-to-end encrypted. - A custom app's settings apply above the policy profile, except for features the profile locks: it can add restrictions and defaults, and its branding (title, accent, welcome text) applies, but it cannot unlock what the policy locks. diff --git a/apps/desktop/e2e/hosts-mock.e2e.mjs b/apps/desktop/e2e/hosts-mock.e2e.mjs index 8104324..4816209 100644 --- a/apps/desktop/e2e/hosts-mock.e2e.mjs +++ b/apps/desktop/e2e/hosts-mock.e2e.mjs @@ -38,6 +38,8 @@ async function run(name) { await ctx.addInitScript(() => { window.__mockCalls = []; window.open = () => null; // the mock's open_session opens a window; not needed here + // The clipboard as the page wrote it (no permission prompt in either engine). + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText: async (t) => void (window.__clip = t), readText: async () => window.__clip ?? "" } }); }); const p = await ctx.newPage(); const errors = []; @@ -232,6 +234,156 @@ async function run(name) { const exp = await p.evaluate(() => window.__lastExport); check(tag("export: JSON without notes"), !!exp && exp.name.endsWith(".json") && exp.content.includes('"tether-hosts"') && !exp.content.includes("front desk before restarting")); + // ---- Health: built-in view, column sort, a search term, the Health section, raw report, rules, export. + const SHOTS = process.env.SHOTS; // a folder: screenshots of the health views + const shot = async (n) => SHOTS && (await p.screenshot({ path: `${SHOTS}/${name}-${n}.png` })); + const nav = p.getByRole("navigation", { name: "Library" }); + const attention = nav.getByRole("button", { name: /^Needs attention/ }); + const navCount = Number((await attention.textContent()).replace(/\D/g, "")); + await attention.click(); + check(tag("Needs attention applies health:crit | health:stale | health:conflict"), (await search.inputValue()) === "health:crit | health:stale | health:conflict"); + check(tag("Needs attention count equals its result count"), navCount > 0 && navCount === (await shown()), `${navCount} vs ${await shown()}`); + const dotsOf = () => rows().evaluateAll((rs) => rs.map((r) => r.querySelector("[role=img][aria-label^='Health:']")?.getAttribute("aria-label"))); + check(tag("every row of the view is critical, not reporting or in a link conflict"), (await dotsOf()).every((d) => d === "Health: Critical" || d === "Health: Not reporting" || d === "Health: Link conflict")); + await setQuery("health:crit"); + check(tag("health:crit finds only critical hosts"), (await shown()) > 0 && (await dotsOf()).every((d) => d === "Health: Critical")); + await setQuery("check:db-service"); + const db = await shown(); + check(tag("check:db-service finds hosts with that failing check"), db > 0 && db <= navCount, `${db}`); + await setQuery(""); + await p.getByRole("columnheader", { name: "Health" }).click(); + check(tag("sorting by Health puts the link conflict, then a critical row first"), (await dotsOf())[0] === "Health: Link conflict" && (await dotsOf())[1] === "Health: Critical", (await dotsOf()).slice(0, 2).join()); + check(tag("Health column says it in words"), /Link conflict/.test(await rows().first().locator("[role=gridcell]").nth(5).textContent()) && /critical/.test(await rows().nth(1).locator("[role=gridcell]").nth(5).textContent())); + // The conflicted host: nothing joined, the conflict explained. + await rows().first().click(); + check(tag("a host with two linked devices shows the link conflict"), await until(() => p.getByTestId("health-conflict-host").isVisible())); + await shot("conflict-host"); + await rows().nth(1).click(); + const sec = p.getByTestId("health-section"); + check(tag("detail shows the Health section"), await until(() => sec.locator("li[data-check]").first().isVisible())); + check(tag("detail shows the customer reference"), /Customer 471[12]/.test(await sec.textContent()), (await sec.textContent()).slice(0, 120)); + // Every fault (all groups) and the setup items come before the first "checks passed" fold. + const order = await sec.evaluate((s) => { + const items = [...s.querySelectorAll("li[data-check]")]; + const passed = [...s.querySelectorAll("button")].filter((b) => /checks? passed/.test(b.textContent)); + const groups = [...s.querySelectorAll("li[data-check]")].map((li) => li.closest("div").firstElementChild?.textContent); + return { ok: items.length > 1 && passed.length > 0 && items.every((li) => !!(li.compareDocumentPosition(passed[0]) & Node.DOCUMENT_POSITION_FOLLOWING)), n: items.length, groups: new Set(groups).size }; + }); + check(tag("all faults are listed before checks passed"), order.ok && order.groups > 1, JSON.stringify(order)); + await shot("detail"); + await sec.getByRole("button", { name: "History (90 days)" }).click(); + check(tag("history lists changes"), (await sec.getByRole("list", { name: "History" }).locator("li").count()) > 0); + await sec.getByRole("button", { name: "Raw report" }).click(); + await sec.getByRole("button", { name: "Copy raw report" }).click(); + const clip = await p.evaluate(() => window.__clip ?? ""); + let raw = null; + try { + raw = JSON.parse(clip); + } catch {} + check(tag("raw report Copy writes the report JSON"), raw?.v === 1 && Array.isArray(raw?.body?.checks), clip.slice(0, 60)); + await shot("raw"); + await p.keyboard.press("Escape"); + // Agent-only rows: no connect actions, Enter only explains. + await setQuery("id:m:"); + check(tag("agent-only rows are listed (two of them in a conflict)"), (await shown()) === 7); + await rows().first().click(); + await clearCalls(); + check(tag("an m: row has no Connect button"), (await p.getByText("No remote access: Tether is not installed").first().isVisible()) && !(await p.getByRole("button", { name: /^Connect/ }).isVisible())); + const det = p.getByRole("complementary", { name: "Host details" }); + check(tag("an m: row has no name, tags, notes, pin or Remove host"), !(await det.locator("#host-name").count()) && !(await det.locator("#host-notes").count()) && !(await det.getByRole("button", { name: /^(Pin|Unpin|Remove host)$/ }).count())); + await p.keyboard.press("Delete"); + await sleep(100); + check(tag("Delete on an m: row opens no Remove dialog"), !(await p.getByRole("dialog").count())); + await p.keyboard.press("Enter"); + await sleep(100); + check(tag("Enter on an m: row opens nothing"), (await calls("open_session")).length === 0); + // A report without body: an empty state, no error. + await setQuery("NAS-BACKUP-01"); + await rows().first().click(); + check(tag("a report without checks shows an empty state"), await until(() => p.getByText("This report lists no checks.").isVisible())); + // The other device of the conflict: its own row, marked, with Unlink and Remove. + await setQuery("SHADOW-PC"); + await rows().first().click(); + check(tag("a conflicting agent row says which host it is in conflict for"), await p.getByText(/^In conflict with another agent for host /).isVisible()); + check(tag("a conflicting agent is its own row with the conflict line and Unlink"), (await rows().first().getAttribute("data-id")) === "m:agent-dup-1" && (await until(() => p.getByTestId("health-conflict").isVisible())) && (await until(() => p.getByTestId("health-section").getByRole("button", { name: "Unlink" }).isVisible()))); + await shot("conflict-agent"); + // A claim to a host whose health agent is linked already cannot be linked (it would hide that host's health). + await setQuery("IMPOSTER-PC"); + await rows().first().click(); + check(tag("Link is refused for a host that already has a linked health agent"), (await until(() => p.getByText(/This host already has a linked health agent \(.+\)\. Unlink that one first/).isVisible())) && (await p.getByTestId("health-claim").getByRole("button", { name: "Link to this host" }).isDisabled())); + await shot("link-blocked"); + // Verified links: an agent that only claims a Tether ID keeps its own row until a member confirms it. + await setQuery("FRONT-DESK-AGENT"); + await rows().first().click(); + const claimLine = p.getByTestId("health-claim"); + // The enrolment time comes with the host's report (asked for once the cursor rests). + const claimText = (await until(async () => /enrolled/.test(await claimLine.textContent()))) ? await claimLine.textContent() : await claimLine.textContent().catch(() => ""); + check(tag("a claimed agent stays an m: row with the claim line"), (await rows().first().getAttribute("data-id")) === "m:agent-only-4" && /Claims to be \d{9} \(.+\)\. Confirm only if this is that computer\./.test(claimText) && /enrolled/.test(claimText), claimText); + await shot("claim"); + await claimLine.getByRole("button", { name: "Link to this host" }).click(); + const ldlg = p.getByRole("dialog"); + check(tag("Link asks for one explicit confirmation"), await until(() => ldlg.getByText("The agent's claim is not proof").isVisible())); + if (SHOTS) await sleep(500); // past the dialog's fade-in + await shot("link-dialog"); + await clearCalls(); + await ldlg.getByRole("button", { name: "Link", exact: true }).click(); + await until(async () => (await calls("team_status_link")).length > 0); + const la = (await calls("team_status_link"))[0]; + check(tag("Link calls team_status_link with the claimed ID"), la?.uuid === "agent-only-4" && claimText.includes(`Claims to be ${la?.tetherId} `), JSON.stringify(la)); + await setQuery(`id:${la?.tetherId}`); + await rows().first().click(); + check(tag("the linked host shows who linked it"), await until(() => p.getByText("Health linked by Anna (Helpdesk)").isVisible())); + await setQuery("id:m:"); + check(tag("the linked agent no longer has its own row"), (await shown()) === 6); + await setQuery(`id:${la?.tetherId}`); + await rows().first().click(); + await p.getByTestId("health-section").getByRole("button", { name: "Unlink" }).click(); + await clearCalls(); + await p.getByRole("dialog").getByRole("button", { name: "Unlink" }).click(); + check(tag("Unlink calls team_status_unlink"), await until(async () => (await calls("team_status_unlink"))[0]?.uuid === "agent-only-4")); + await setQuery("FRONT-DESK-AGENT"); + check(tag("an unlinked agent is its own row again, link dismissed, no claim"), (await until(async () => (await rows().first().getAttribute("data-id")) === "m:agent-only-4")) && (await rows().first().click(), await until(() => p.getByTestId("health-dismissed").isVisible())) && !(await claimLine.isVisible())); + check(tag("a dismissed row says so in its banner"), await p.getByText("Link dismissed. This agent is not linked to a host.").isVisible()); + await shot("dismissed"); + await clearCalls(); + await p.getByRole("button", { name: "Allow a new claim" }).click(); + check(tag("Allow a new claim calls team_status_allow_claim"), await until(async () => (await calls("team_status_allow_claim"))[0]?.uuid === "agent-only-4")); + await rows().first().click(); + await p.getByRole("button", { name: "Remove from health monitoring…" }).click(); + const rmdlg = p.getByRole("dialog"); + check(tag("Remove names the host and asks to uninstall the agent"), (await rmdlg.getByText("Remove FRONT-DESK-AGENT from health monitoring?").isVisible()) && (await rmdlg.getByText(/enrols again by itself.*Uninstall the agent there, or ask an admin to revoke the token/).isVisible())); + await clearCalls(); + await rmdlg.getByRole("button", { name: "Remove", exact: true }).click(); + check(tag("Remove calls team_status_remove"), await until(async () => (await calls("team_status_remove"))[0]?.uuid === "agent-only-4")); + check(tag("a removed agent leaves the list"), await until(async () => (await setQuery("FRONT-DESK-AGENT"), (await shown()) === 0))); + // In tag rules health terms are plain words, as older desktops read them; the dialog says so. + await setQuery(""); + await p.getByRole("button", { name: "Tag rules" }).click(); + const rdlg = p.getByRole("dialog"); + await rdlg.getByRole("textbox", { name: "Rule tag" }).fill("plain"); + await rdlg.getByRole("textbox", { name: "Rule search" }).fill("health:crit"); + check(tag("rules dialog says health terms are not available in rules"), (await rdlg.getByText("are not available in rules: there they are plain words").isVisible()) && !(await rdlg.getByRole("button", { name: "Add rule" }).isDisabled())); + await rdlg.getByRole("button", { name: "Close" }).click(); + // Export: failing checks, one row per host and failing check. + await setQuery("health:crit"); + const ncrit = await shown(); + await p.keyboard.press("Control+k"); + await pal.fill("export hosts"); + await p.keyboard.press("Enter"); + const edlg = p.getByRole("dialog"); + await edlg.getByRole("radio", { name: "Failing checks (CSV)" }).click(); + await edlg.getByRole("radio", { name: /^Shown/ }).click(); + await shot("export"); + await edlg.getByRole("button", { name: "Export…" }).click(); + const fx = await p.evaluate(() => window.__lastExport); + const lines = fx?.content.trim().split("\r\n") ?? []; + check(tag("export: failing checks CSV"), /^tether-health-faults-\d{4}-\d{2}-\d{2}\.csv$/.test(fx?.name ?? "") && lines[0] === "id,name,uuid,check,state,since" && lines.length - 1 >= ncrit && lines.some((l) => l.includes(",app/db-service,crit,")), `${fx?.name} ${lines.length - 1} rows, ${ncrit} hosts`); + await setQuery(""); + // Team dialog: the notification switch. + await p.getByRole("button", { name: "Team", exact: true }).click(); + check(tag("Team dialog has the notification switch (on)"), (await p.getByRole("switch", { name: "Notify me when a host turns critical or stops reporting" }).getAttribute("aria-checked")) === "true"); + await p.keyboard.press("Escape"); + // ---- Help and sessions dialogs open from the keyboard / title bar. await rows().first().click(); await p.keyboard.press("?"); @@ -244,6 +396,19 @@ async function run(name) { check(tag("Ctrl+Alt+Del goes to that session"), await until(async () => (await calls("session_ctrl_alt_del"))[0]?.key === "k1")); await p.keyboard.press("Escape"); + // A member without write sees the claim, but cannot link, unlink or remove. + await p.goto(`${base}?hosts=5000&team=ro#/`); + await search.waitFor({ timeout: 60000 }); + await until(async () => (await total()) > 4000, 30000); + await setQuery("FRONT-DESK-AGENT"); + await rows().first().click(); + await until(() => claimLine.isVisible()); + check(tag("read-only member: Link is disabled with a reason, no Remove"), (await claimLine.getByRole("button", { name: "Link to this host" }).isDisabled()) && (await claimLine.getByText("Only team members who may edit shared tags can link").isVisible()) && !(await p.getByRole("button", { name: "Remove from health monitoring…" }).isVisible())); + await setQuery("health:crit"); + await rows().first().click(); + await until(() => p.getByTestId("health-section").locator("li[data-check]").first().isVisible()); + check(tag("read-only member: no Unlink or Remove on a linked host"), !(await p.getByRole("button", { name: "Unlink" }).isVisible()) && !(await p.getByRole("button", { name: "Remove from health monitoring…" }).isVisible())); + check(tag("no page errors"), errors.length === 0, errors.join(" | ")); await browser.close(); } diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 3de5443..3c2787d 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -9823,6 +9823,7 @@ dependencies = [ "tauri-plugin-dialog", "tauri-plugin-single-instance", "tauri-plugin-updater", + "tauri-winrt-notification", "tether-trust", "url", "uuid", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index e9f7905..8d15752 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -11,6 +11,7 @@ path = "src/main.rs" [build-dependencies] tauri-build = { version = "2", features = [] } +serde_json = "1" [dependencies] tauri = { version = "2", features = ["tray-icon", "image-png"] } @@ -41,6 +42,8 @@ librustdesk = { package = "rustdesk", path = "../../../vendor/rustdesk", default [target.'cfg(windows)'.dependencies] # VRAM (D3D11) zero-copy encoding exists on Windows only (hwcodec's ffmpeg_vram is D3D11 code). librustdesk = { package = "rustdesk", path = "../../../vendor/rustdesk", default-features = false, features = ["vram"] } +# Health notifications (already in the tree through vendor/rustdesk). +tauri-winrt-notification = "0.1" windows-sys = { version = "0.59", features = ["Win32_UI_HiDpi", "Win32_Foundation", "Win32_Networking_WinHttp", "Win32_System_Registry", "Win32_System_Console", "Win32_System_DataExchange", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_System_StationsAndDesktops", "Win32_System_Threading"] } [features] diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs index a1ccb68..fec6620 100644 --- a/apps/desktop/src-tauri/build.rs +++ b/apps/desktop/src-tauri/build.rs @@ -1,3 +1,6 @@ +#[path = "src/instance.rs"] +mod instance; + fn main() { // A release build without a pinned server and keys would fall back to upstream defaults, accept // no policy and install no updates: refuse to produce one. @@ -12,6 +15,27 @@ fn main() { } } } + // A second build for another organisation, installed beside the default one: its own product + // name and so its own service, config folder, firewall rule and policy key (scripts/instance-config.sh). + println!("cargo:rerun-if-env-changed=TETHER_INSTANCE"); + let inst = match std::env::var("TETHER_INSTANCE") { + Ok(v) => v, + Err(std::env::VarError::NotPresent) => String::new(), + Err(e) => panic!("TETHER_INSTANCE: {e}"), + }; + if !instance::valid_instance(&inst) { + panic!("TETHER_INSTANCE must be empty or 1 to 16 characters a-z, 0-9 (got {inst:?})"); + } + // Debug builds (cargo test, tauri dev) are exempt; a release `cargo build` without the Tauri + // CLI has no TAURI_CONFIG, so only the default build passes there. + println!("cargo:rerun-if-env-changed=TAURI_CONFIG"); + if std::env::var("PROFILE").as_deref() == Ok("release") { + if let Err(e) = instance::check_product_name(&inst, std::env::var("TAURI_CONFIG").ok().as_deref()) { + panic!("{e}"); + } + } + println!("cargo:rustc-env=TETHER_APP_NAME={}", instance::app_name(&inst)); + println!("cargo:rustc-env=TETHER_INSTANCE={inst}"); link_clang_rt(); tauri_build::build() } diff --git a/apps/desktop/src-tauri/src/cli.rs b/apps/desktop/src-tauri/src/cli.rs index f3d2614..52ff7c8 100644 --- a/apps/desktop/src-tauri/src/cli.rs +++ b/apps/desktop/src-tauri/src/cli.rs @@ -9,7 +9,7 @@ use std::{ use crate::{diag, policy, security, update}; -pub const HELP: &str = "\ +const HELP: &str = "\ Usage: tether [command] (no command) start Tether @@ -66,19 +66,29 @@ pub enum Cmd { PolicyRefresh, } -const URI_PREFIX: &str = "tether://"; +/// `--help`: an instance build names its own binary and link scheme (`tether-`). +pub fn help() -> String { + let bin = crate::APP_NAME.to_lowercase(); + HELP.replace("Usage: tether ", &format!("Usage: {bin} ")).replace(" tether://", &format!(" {}", uri_prefix())) +} + +/// `tether://`, `tether-://` for an instance build (its deep-link scheme, scripts/instance-config.sh). +fn uri_prefix() -> String { + format!("{}://", crate::APP_NAME.to_lowercase()) +} /// `tether://connect/` (optional trailing `/`). Nothing else: no query, no password. pub fn parse_uri(uri: &str) -> Result { + let prefix = uri_prefix(); let rest = uri - .get(..URI_PREFIX.len()) - .filter(|p| p.eq_ignore_ascii_case(URI_PREFIX)) - .map(|_| &uri[URI_PREFIX.len()..]) - .ok_or("not a tether:// link")?; + .get(..prefix.len()) + .filter(|p| p.eq_ignore_ascii_case(&prefix)) + .map(|_| &uri[prefix.len()..]) + .ok_or_else(|| format!("not a {prefix} link"))?; let peer = rest .strip_prefix("connect/") .map(|p| p.strip_suffix('/').unwrap_or(p)) - .ok_or("only tether://connect/ links are supported")?; + .ok_or_else(|| format!("only {prefix}connect/ links are supported"))?; security::check_peer_id(peer)?; Ok(Connect { peer: peer.to_owned(), conn: "default".into(), ..Default::default() }) } @@ -86,9 +96,10 @@ pub fn parse_uri(uri: &str) -> Result { /// `None`: not a Tether command, the core handles it. pub fn parse(args: &[String]) -> Option> { let first = args.first()?; - if first.len() >= URI_PREFIX.len() && first[..URI_PREFIX.len()].eq_ignore_ascii_case(URI_PREFIX) { + let prefix = uri_prefix(); + if first.get(..prefix.len()).is_some_and(|p| p.eq_ignore_ascii_case(&prefix)) { if args.len() > 1 { - return Some(Err("a tether:// link takes no other arguments".into())); + return Some(Err(format!("a {prefix} link takes no other arguments"))); } return Some(parse_uri(first).map(Cmd::Connect)); } @@ -236,7 +247,7 @@ pub fn run(args: &[String]) -> Option { Ok(c) => c, Err(e) => { console(); - eprintln!("{e}\n\n{HELP}"); + eprintln!("{e}\n\n{}", help()); return Some(ExitCode::from(2)); } }; @@ -244,7 +255,7 @@ pub fn run(args: &[String]) -> Option { console(); } let result: Result = match cmd { - Cmd::Help => Ok(HELP.into()), + Cmd::Help => Ok(help()), Cmd::Version => Ok(update::VERSION.into()), Cmd::GetId => Ok(librustdesk::ipc::get_id()), Cmd::Diagnostics(out) => diag::export_to(&out).map(|_| format!("wrote {}", out.display())), @@ -383,19 +394,37 @@ mod tests { assert!(decode_forward("zz").is_err()); } + #[test] + fn uri_prefix_follows_the_app_name() { + assert_eq!(uri_prefix(), format!("{}://", crate::APP_NAME.to_lowercase())); + if env!("TETHER_INSTANCE").is_empty() { + assert_eq!(uri_prefix(), "tether://"); + assert_eq!(help(), HELP); + } else { + let i = env!("TETHER_INSTANCE"); + assert!(help().starts_with(&format!("Usage: tether-{i} [command]\n"))); + assert!(help().contains(&format!("\n tether-{i}://connect/ "))); + assert!(!help().contains(" tether://")); + } + } + #[test] fn uris() { - assert_eq!(connect("tether://connect/123456789").peer, "123456789"); - assert_eq!(connect("TETHER://connect/123456789/").peer, "123456789"); + let u = |rest: &str| format!("{}{rest}", uri_prefix()); + assert_eq!(connect(&u("connect/123456789")).peer, "123456789"); + assert_eq!(connect(&format!("{}connect/123456789/", uri_prefix().to_uppercase())).peer, "123456789"); for bad in [ - "tether://connect/123456789?password=x", - "tether://connect/123456789/x", - "tether://file-transfer/123456789", - "tether://connect/", - "tether://connect/1@2#3", + u("connect/123456789?password=x"), + u("connect/123456789/x"), + u("file-transfer/123456789"), + u("connect/"), + u("connect/1@2#3"), ] { - assert!(matches!(p(bad), Some(Err(_))), "{bad} accepted"); + assert!(matches!(p(&bad), Some(Err(_))), "{bad} accepted"); } - assert!(matches!(p("tether://connect/123456789 pw"), Some(Err(_)))); + assert!(matches!(p(&u("connect/123456789 pw")), Some(Err(_)))); + // Another build's scheme is not this app's link. + let other = if env!("TETHER_INSTANCE").is_empty() { "tether-north://" } else { "tether://" }; + assert!(parse_uri(&format!("{other}connect/123456789")).is_err()); } } diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 83a7f4a..e317474 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -751,6 +751,14 @@ pub fn handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static team_tags_get, team_tags_put, team_audit, + team_status, + team_status_host, + team_status_find, + team_status_link, + team_status_unlink, + team_status_remove, + team_status_allow_claim, + health_notify, ] } @@ -845,6 +853,70 @@ async fn team_tags_put(window: tauri::WebviewWindow, rev: u64, doc: String) -> R async fn team_audit(device: String, since: u64) -> R { blocking(move || team::audit(&device, since)).await? } + +#[tauri::command] +async fn team_status() -> R { + blocking(team::status).await? +} + +#[tauri::command] +async fn team_status_host(relay: String, uuid: String) -> R { + blocking(move || team::status_host(&relay, &uuid)).await? +} + +#[tauri::command] +async fn team_status_link(window: tauri::WebviewWindow, uuid: String, tether_id: String) -> R<()> { + main_only(&window)?; + blocking(move || team::status_link(&uuid, &tether_id)).await? +} + +#[tauri::command] +async fn team_status_unlink(window: tauri::WebviewWindow, uuid: String) -> R<()> { + main_only(&window)?; + blocking(move || team::status_unlink(&uuid)).await? +} + +#[tauri::command] +async fn team_status_remove(window: tauri::WebviewWindow, uuid: String) -> R<()> { + main_only(&window)?; + blocking(move || team::status_remove(&uuid)).await? +} + +#[tauri::command] +async fn team_status_allow_claim(window: tauri::WebviewWindow, uuid: String) -> R<()> { + main_only(&window)?; + blocking(move || team::status_allow_claim(&uuid)).await? +} + +/// The cached health summaries linked to a Tether ID (session window: two or more are a link +/// conflict); never a request. +#[tauri::command] +fn team_status_find(id: String) -> Vec { + team::status_find(&id) +} + +/// A health notification (host list, spec 10.5): a Windows toast. Other systems: nothing yet +/// (no notification facility in this app; see the health docs). +#[tauri::command] +async fn health_notify(title: String, body: String) -> R<()> { + // Device-chosen host names end up here: plain text, bounded. + let cut = |s: &str, n: usize| s.chars().filter(|c| !c.is_control()).take(n).collect::(); + let (title, body) = (cut(&title, 120), cut(&body, 240)); + #[cfg(windows)] + { + blocking(move || { + tauri_winrt_notification::Toast::new(tauri_winrt_notification::Toast::POWERSHELL_APP_ID) + .title(&title) + .text1(&body) + .show() + .map_err(|e| e.to_string()) + }) + .await??; + } + #[cfg(not(windows))] + let _ = (title, body); + Ok(()) +} // --- end advanced mode --- // --- reconnect/recording --- diff --git a/apps/desktop/src-tauri/src/instance.rs b/apps/desktop/src-tauri/src/instance.rs new file mode 100644 index 0000000..f37fbdb --- /dev/null +++ b/apps/desktop/src-tauri/src/instance.rs @@ -0,0 +1,80 @@ +// Used by build.rs (`#[path]` module) and by the unit tests below; the app itself reads the result +// through env!("TETHER_APP_NAME") / env!("TETHER_INSTANCE"). + +/// `TETHER_INSTANCE`: empty (the default build) or 1 to 16 characters a-z, 0-9. It becomes part of +/// the product name, the Windows service name (`sc create` unquoted) and paths: nothing else. +pub fn valid_instance(i: &str) -> bool { + i.len() <= 16 && i.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) +} + +/// Product name and `APP_NAME` of an instance: `Tether`, or `Tether-`. +pub fn app_name(instance: &str) -> String { + if instance.is_empty() { "Tether".to_owned() } else { format!("Tether-{instance}") } +} + +/// Release builds: the Tauri product name must be this instance's, or the setup would install over +/// the other build (same uninstall key and exe) with a different config folder, ID and policy key. +/// `tauri_config` is `TAURI_CONFIG`: only the `--config` JSON (merged), set by the Tauri CLI, absent +/// without `--config`; then tauri.conf.json's `Tether` applies. +pub fn check_product_name(instance: &str, tauri_config: Option<&str>) -> Result<(), String> { + let want = app_name(instance); + let got = tauri_config + .and_then(|c| serde_json::from_str::(c).ok()) + .and_then(|v| v.get("productName")?.as_str().map(str::to_owned)) + .unwrap_or_else(|| "Tether".to_owned()); + if got == want { + return Ok(()); + } + let fix = if instance.is_empty() { + let i = got.strip_prefix("Tether-").unwrap_or(""); + format!("set TETHER_INSTANCE={i} for --config \"$(bash scripts/instance-config.sh {i})\", or drop that --config") + } else { + format!("build with --config \"$(bash scripts/instance-config.sh {instance})\"") + }; + Err(format!("TETHER_INSTANCE={instance:?} needs productName {want:?}, but the Tauri config gives {got:?}: {fix}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn instance_values() { + for ok in ["", "north", "a", "0", "abcdefghij123456"] { + assert!(valid_instance(ok), "{ok:?} refused"); + } + for bad in ["North", "a b", "abcdefghij1234567", "../x", "tether-x", " ", "nörd"] { + assert!(!valid_instance(bad), "{bad:?} accepted"); + } + } + + #[test] + fn product_name_must_match_the_instance() { + let north = r#"{"productName":"Tether-north","mainBinaryName":"tether-north"}"#; + let other = r#"{"build":{"frontendDist":"/x"}}"#; // build-macos.sh PREBUILT_FRONTEND only + // Matching. + assert!(check_product_name("north", Some(north)).is_ok()); + assert!(check_product_name("", None).is_ok()); + assert!(check_product_name("", Some(other)).is_ok()); + assert!(check_product_name("", Some(r#"{"productName":"Tether"}"#)).is_ok()); + // Instance without its --config: absent variable, productName absent, another instance. + let e = check_product_name("north", None).unwrap_err(); + assert!(e.contains("\"Tether-north\"") && e.contains("\"Tether\""), "{e}"); + assert!(e.contains(r#"--config "$(bash scripts/instance-config.sh north)""#), "{e}"); + assert!(check_product_name("north", Some(other)).is_err()); + assert!(check_product_name("north", Some(r#"{"productName":"Tether-south"}"#)).is_err()); + // Instance --config without TETHER_INSTANCE. + let e = check_product_name("", Some(north)).unwrap_err(); + assert!(e.contains("\"Tether-north\"") && e.contains("TETHER_INSTANCE=north"), "{e}"); + } + + #[test] + fn default_build_keeps_todays_names() { + assert_eq!(app_name(""), "Tether"); + if env!("TETHER_INSTANCE").is_empty() { + assert_eq!(crate::APP_NAME, "Tether"); + } else { + assert_eq!(crate::APP_NAME, format!("Tether-{}", env!("TETHER_INSTANCE"))); + } + } +} diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index b6101e7..b30eacd 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -7,6 +7,8 @@ mod diag; mod diag_bundle; mod fluxrt; mod hosts; +#[cfg(test)] +mod instance; mod keys; mod netpolicy; mod policy; @@ -20,13 +22,20 @@ use std::process::ExitCode; use librustdesk::core_main::{core_main, CoreMainAction}; -pub const APP_NAME: &str = "Tether"; +/// `Tether`, or `Tether-` for an instance build (`TETHER_INSTANCE`, build.rs). +pub const APP_NAME: &str = env!("TETHER_APP_NAME"); #[cfg_attr(not(target_os = "macos"), allow(dead_code))] pub const ORG: &str = "app.tether"; /// Set in the main window's process, inherited by the `--cm` process its server starts (app.rs). #[cfg(target_os = "macos")] pub const MAIN_GUI_ENV: &str = "TETHER_MAIN_GUI"; +/// Mixed into the MAC-derived ID (hbb_common `Config::auto_id_from_mac`) of an instance build: +/// FNV-1a 64 of the app name, never 0 (0 is the default build). Never change it. +fn instance_id_salt(name: &str) -> u64 { + name.bytes().fold(0xcbf2_9ce4_8422_2325, |h: u64, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)) | 1 +} + fn main() -> ExitCode { // Release builds abort on panic (0xc0000409, no message anywhere): log it first. let default_hook = std::panic::take_hook(); @@ -43,6 +52,11 @@ fn main() -> ExitCode { _ => APP_NAME.to_owned(), }; *hbb_common::config::APP_NAME.write().unwrap() = name; + // An instance build gets its own ID: the default build on the same PC derives the same one + // from the MAC address, and two apps registering one ID take it from each other. + if !env!("TETHER_INSTANCE").is_empty() { + hbb_common::config::AUTO_ID_SALT.store(instance_id_salt(APP_NAME), std::sync::atomic::Ordering::Relaxed); + } #[cfg(target_os = "macos")] { *hbb_common::config::ORG.write().unwrap() = ORG.to_owned(); @@ -98,3 +112,16 @@ fn main() -> ExitCode { librustdesk::common::global_clean(); code } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn instance_id_salt_is_stable_and_not_zero() { + // Pinned: a changed salt gives every installed instance build a new ID. + assert_eq!(instance_id_salt("Tether-north"), 0xf982_4b2b_f7b9_c7bf); + assert_ne!(instance_id_salt("Tether-north"), instance_id_salt("Tether-south")); + assert_ne!(instance_id_salt("Tether-a"), 0); + } +} diff --git a/apps/desktop/src-tauri/src/netpolicy.rs b/apps/desktop/src-tauri/src/netpolicy.rs index 2e1ffb4..d0b28fc 100644 --- a/apps/desktop/src-tauri/src/netpolicy.rs +++ b/apps/desktop/src-tauri/src/netpolicy.rs @@ -46,7 +46,7 @@ pub fn apply() { } /// Windows firewall rule the installer creates for the direct listener (hooks.nsh). -const FIREWALL_RULE: &str = "Tether"; +const FIREWALL_RULE: &str = crate::APP_NAME; /// Policy `network.direct`: `auto` races direct paths (LAN) beside the relay, `off` keeps every /// session on the relay. The host side listens only where that raises no firewall prompt. @@ -328,6 +328,14 @@ mod winhttp { mod tests { use super::*; + #[test] + fn firewall_rule_is_the_app_name() { + assert_eq!(FIREWALL_RULE, crate::APP_NAME); + if env!("TETHER_INSTANCE").is_empty() { + assert_eq!(FIREWALL_RULE, "Tether"); + } + } + #[test] fn stun_on_own_servers_only() { let v = ["a.example", "wss://k.example/ws/id", "1.2.3.4:21116", ""].map(String::from); diff --git a/apps/desktop/src-tauri/src/policy.rs b/apps/desktop/src-tauri/src/policy.rs index 304ad30..1f9e2c5 100644 --- a/apps/desktop/src-tauri/src/policy.rs +++ b/apps/desktop/src-tauri/src/policy.rs @@ -377,17 +377,29 @@ fn apply_core(eff: &Effective, applied: &mut Vec) { } /// GPO/MDM layer: a `Layer` JSON in `HKLM\SOFTWARE\Policies\Tether` `PolicyJson` (REG_SZ) or -/// `/Library/Managed Preferences/net.tether.app.plist` key `PolicyJson`. +/// `/Library/Managed Preferences/net.tether.app.plist` key `PolicyJson`. An instance build +/// (`TETHER_INSTANCE`) reads `…\Policies\Tether-` and `net.tether.app.`. fn machine_layer() -> Option { let raw = machine_json()?; serde_json::from_str(&raw).map_err(|e| log::error!("machine policy ignored: {e}")).ok() } +#[cfg_attr(not(windows), allow(dead_code))] +const MACHINE_POLICY_KEY: &str = concat!("SOFTWARE\\Policies\\", env!("TETHER_APP_NAME")); + +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +fn managed_preferences_domain() -> String { + match env!("TETHER_INSTANCE") { + "" => "net.tether.app".to_owned(), + i => format!("net.tether.app.{i}"), + } +} + #[cfg(windows)] fn machine_json() -> Option { use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ}; let wide = |s: &str| s.encode_utf16().chain(std::iter::once(0)).collect::>(); - let (key, name) = (wide("SOFTWARE\\Policies\\Tether"), wide("PolicyJson")); + let (key, name) = (wide(MACHINE_POLICY_KEY), wide("PolicyJson")); unsafe { let mut size = 0u32; let get = |buf: *mut std::ffi::c_void, size: &mut u32| { @@ -410,7 +422,7 @@ fn machine_json() -> Option { // shortcut: reads via `defaults`, no plist crate; fine for one string key. Upgrade (plist crate // or CFPreferences) when a second managed key or a non-string value is read. let out = std::process::Command::new("/usr/bin/defaults") - .args(["read", "/Library/Managed Preferences/net.tether.app", "PolicyJson"]) + .args(["read", format!("/Library/Managed Preferences/{}", managed_preferences_domain()).as_str(), "PolicyJson"]) .output() .ok()?; out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned()) @@ -679,6 +691,28 @@ mod tests { use super::*; use tether_trust::policy::{Group, Rule, State as S}; + #[test] + fn machine_policy_names_follow_the_app_name() { + assert_eq!(MACHINE_POLICY_KEY, format!("SOFTWARE\\Policies\\{}", crate::APP_NAME)); + match env!("TETHER_INSTANCE") { + "" => { + assert_eq!(MACHINE_POLICY_KEY, "SOFTWARE\\Policies\\Tether"); + assert_eq!(managed_preferences_domain(), "net.tether.app"); + // The generated docs/policy.md text is today's, byte for byte. + assert!(render_doc().contains( + "(`HKLM\\SOFTWARE\\Policies\\Tether` REG_SZ `PolicyJson`, or \ + `/Library/Managed Preferences/net.tether.app.plist` key `PolicyJson`," + )); + } + i => { + assert_eq!(managed_preferences_domain(), format!("net.tether.app.{i}")); + let doc = render_doc(); + assert!(doc.contains(&format!("`HKLM\\SOFTWARE\\Policies\\Tether-{i}` REG_SZ"))); + assert!(doc.contains(&format!("`/Library/Managed Preferences/net.tether.app.{i}.plist`"))); + } + } + } + fn bundle_locking_everything() -> Bundle { let layer: Layer = FEATURES .iter() @@ -837,7 +871,10 @@ mod tests { `/Library/Managed Preferences/net.tether.app.plist` key `PolicyJson`, both a `Layer` JSON such as \ `{\"connect.outgoing\":{\"state\":\"off\"}}`). Core options in `FLOOR` (TLS, encryption, 443-only \ networking, no silent recording) can never be set by policy.\n\n", - ); + ) + // An instance build (TETHER_INSTANCE) reads its own key and domain. + .replace("HKLM\\SOFTWARE\\Policies\\Tether", &format!("HKLM\\{MACHINE_POLICY_KEY}")) + .replace("net.tether.app.plist", &format!("{}.plist", managed_preferences_domain())); s.push_str("| Feature | Area | Description | Default | Profiles | Core option |\n| --- | --- | --- | --- | --- | --- |\n"); for f in FEATURES { let def = if f.default.is_empty() { "–".to_owned() } else { format!("`{}`", f.default) }; diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs index 148fa2c..97787ee 100644 --- a/apps/desktop/src-tauri/src/recording.rs +++ b/apps/desktop/src-tauri/src/recording.rs @@ -59,15 +59,19 @@ pub fn set_user_folder(path: &str) -> Result<(), String> { Ok(()) } +#[cfg(target_os = "macos")] +const DEFAULT_FOLDER: &str = concat!("%HOME%/Movies/", env!("TETHER_APP_NAME")); +#[cfg(not(target_os = "macos"))] +const DEFAULT_FOLDER: &str = concat!(r"%USERPROFILE%\Videos\", env!("TETHER_APP_NAME")); + /// The folder picked in Settings, else `recording.folder` with `%VAR%` expanded, else -/// `%USERPROFILE%\Videos\Tether` (macOS `~/Movies/Tether`). +/// `%USERPROFILE%\Videos\Tether` (macOS `~/Movies/Tether`; an instance build `Tether-`). pub fn folder() -> PathBuf { if let Some(f) = user_folder() { return PathBuf::from(f); } let f = policy::get("recording.folder"); - let default = if cfg!(target_os = "macos") { "%HOME%/Movies/Tether" } else { r"%USERPROFILE%\Videos\Tether" }; - let f = if f.trim().is_empty() { default.to_owned() } else { f }; + let f = if f.trim().is_empty() { DEFAULT_FOLDER.to_owned() } else { f }; PathBuf::from(expand_env(&f, |k| std::env::var(k).ok())) } @@ -484,6 +488,13 @@ fn collect(dir: &Path, q: &Path, now: SystemTime) -> Vec { mod tests { use super::*; + #[test] + fn default_folder_is_named_after_the_app() { + let name = if env!("TETHER_INSTANCE").is_empty() { "Tether" } else { crate::APP_NAME }; + let want = if cfg!(target_os = "macos") { format!("%HOME%/Movies/{name}") } else { format!(r"%USERPROFILE%\Videos\{name}") }; + assert_eq!(DEFAULT_FOLDER, want); + } + fn tmp(name: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("tether-rec-test-{name}-{}", std::process::id())); let _ = fs::remove_dir_all(&d); diff --git a/apps/desktop/src-tauri/src/team.rs b/apps/desktop/src-tauri/src/team.rs index 7b9c61b..b0a5013 100644 --- a/apps/desktop/src-tauri/src/team.rs +++ b/apps/desktop/src-tauri/src/team.rs @@ -2,6 +2,9 @@ //! `/api/team/*` once an admin has added its public key to the team roster in Tether Manage. //! The private key never leaves this file and this process; the webview only sees the public half. +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; + use hbb_common::config::Config; use serde_json::Value; use tether_trust::{reqauth, SigningKey}; @@ -11,6 +14,9 @@ type R = Result; const DEVICES_MAX: usize = 4 * 1024 * 1024; const TAGS_MAX: usize = 1024 * 1024; const AUDIT_MAX: usize = 2 * 1024 * 1024; +const STATUS_MAX: usize = 16 << 20; +/// One report (≤ 64 KiB) plus 90 days of history. +const REPORT_MAX: usize = 1 << 20; /// The relay refuses larger tag documents (docs/api.md, team endpoints). pub const TAGS_PUT_MAX: usize = 512 * 1024; @@ -97,6 +103,13 @@ fn now() -> u64 { } /// Readable answer for the UI; `offline:`-prefixed when no relay was reached. +/// Only a real "no" forgets a relay's health list: membership gone (401, 403), no health +/// support (404) or reporting switched off. Anything else may pass, and the hosts must not +/// flip to "no agent" (and back, with a burst of notifications) because of it. +fn status_drops_cache(code: u16, body: &[u8]) -> bool { + matches!(code, 401 | 403 | 404) || (code == 503 && body.starts_with(b"status reporting is off")) +} + fn status_error(code: u16, body: &str) -> String { match code { // Requests are signed for one relay (v2). A relay from before that, or one that does not @@ -107,30 +120,39 @@ fn status_error(code: u16, body: &str) -> String { 403 => "Your team membership does not allow this.".into(), 404 => "unsupported: The server does not offer team access yet.".into(), 413 => "The shared tags are too large for the server (512 KB).".into(), + 409 => format!("Refused by the server: {}", body.chars().take(200).collect::()), + 503 if body.starts_with("status reporting is off") => "off: Health reporting is switched off on this server.".into(), 429 => "Too many requests; try again in a minute.".into(), _ => format!("The server answered {code}: {}", body.chars().take(200).collect::()), } } -/// One signed request. `path` includes the query string (it is part of the signature). -fn call(method: &str, path: &str, body: Option<&[u8]>, if_match: Option, limit: usize) -> R<(u16, Vec)> { +/// One signed request to the first reachable relay, or to the first reachable of `hosts`. +/// `path` includes the query string (it is part of the signature). Answers status, ETag, body. +fn call_via(hosts: Option<&[String]>, method: &str, path: &str, body: Option<&[u8]>, headers: &[(&str, String)], limit: usize) -> R<(u16, Option, Vec)> { let k = key()?; let body = body.unwrap_or_default().to_vec(); - let r = crate::policy::api(|c, base| { + let build = |c: &reqwest::blocking::Client, base: &str| { // A fresh signature (and nonce) per attempt: the relay rejects a replayed one, and each // is made for the relay it goes to. let sig = reqauth::sign_request_for(&k, base, method, path, &body, now()); let url = format!("{base}{path}"); - let rq = if method == "PUT" { c.put(url).header("Content-Type", "application/json").body(body.clone()) } else { c.get(url) }; - let rq = rq.header(reqauth::HEADER, sig); - match if_match { - Some(rev) => rq.header("If-Match", rev.to_string()), - None => rq, - } - })?; + let rq = c.request(reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET), url); + let rq = if body.is_empty() { rq } else { rq.header("Content-Type", "application/json").body(body.clone()) }; + headers.iter().fold(rq.header(reqauth::HEADER, sig), |rq, (n, v)| rq.header(*n, v)) + }; + let r = match hosts { + Some(h) => crate::policy::api_via(h, build), + None => crate::policy::api(build), + }?; let code = r.status().as_u16(); + let etag = r.headers().get("ETag").and_then(|v| v.to_str().ok()).map(str::to_owned); let raw = tether_trust::read_limited(r, limit)?; - Ok((code, raw)) + Ok((code, etag, raw)) +} + +fn call(method: &str, path: &str, body: Option<&[u8]>, headers: &[(&str, String)], limit: usize) -> R<(u16, Vec)> { + call_via(None, method, path, body, headers, limit).map(|(c, _, b)| (c, b)) } fn json_ok(code: u16, raw: &[u8]) -> R { @@ -141,17 +163,17 @@ fn json_ok(code: u16, raw: &[u8]) -> R { } pub fn me() -> R { - let (c, b) = call("GET", "/api/team/me", None, None, 4096)?; + let (c, b) = call("GET", "/api/team/me", None, &[], 4096)?; json_ok(c, &b) } pub fn devices() -> R { - let (c, b) = call("GET", "/api/team/devices", None, None, DEVICES_MAX)?; + let (c, b) = call("GET", "/api/team/devices", None, &[], DEVICES_MAX)?; json_ok(c, &b) } pub fn tags_get() -> R { - let (c, b) = call("GET", "/api/team/tags", None, None, TAGS_MAX)?; + let (c, b) = call("GET", "/api/team/tags", None, &[], TAGS_MAX)?; json_ok(c, &b) } @@ -164,7 +186,7 @@ pub fn tags_put(rev: u64, doc: &str) -> R { if !matches!(serde_json::from_str::(doc), Ok(Value::Object(_))) { return Err("invalid tag document".into()); } - let (c, b) = call("PUT", "/api/team/tags", Some(doc.as_bytes()), Some(rev), TAGS_MAX)?; + let (c, b) = call("PUT", "/api/team/tags", Some(doc.as_bytes()), &[("If-Match", rev.to_string())], TAGS_MAX)?; match c { 409 => Ok(serde_json::json!({ "ok": false, "conflict": json_ok(200, &b)? })), _ => { @@ -176,10 +198,168 @@ pub fn tags_put(rev: u64, doc: &str) -> R { pub fn audit(device: &str, since: u64) -> R { crate::security::check_peer_id(device)?; - let (c, b) = call("GET", &format!("/api/team/audit?device={device}&since={since}&limit=200"), None, None, AUDIT_MAX)?; + let (c, b) = call("GET", &format!("/api/team/audit?device={device}&since={since}&limit=200"), None, &[], AUDIT_MAX)?; json_ok(c, &b) } +/// Each relay's last health summary answer (`{built, hosts}`) and its ETag ("" = none sent). +/// `Arc`: a 304 and the copy kept here share one value. +static STATUS_CACHE: Mutex)>> = Mutex::new(BTreeMap::new()); + +/// Health is kept per relay (docs/api.md): every relay is asked. +/// `[{"relay","hosts":[…]} | {"relay","error"} | {"relay","hosts","error"}]`; the last form is a relay +/// that could not be reached, with its last answer. Err only when every relay failed. +pub fn status() -> R { + let relays: Vec = crate::policy::relay_bases().into_iter().map(|(h, _)| h).collect(); + status_with(&relays, &STATUS_CACHE, |relay, inm| call_via(Some(&[relay.to_owned()]), "GET", "/api/team/status", None, inm, STATUS_MAX)) +} + +/// [`status`] with the relays, the cache and the signed request given (tests: a stand-in answer). +fn status_with(relays: &[String], cache: &Mutex)>>, call: impl Fn(&str, &[(&str, String)]) -> R<(u16, Option, Vec)>) -> R { + let mut out = Vec::new(); + let mut first_err = None; + let mut all_failed = true; + for relay in relays.iter().cloned() { + let cached = cache.lock().unwrap().get(&relay).cloned(); + let inm: Vec<(&str, String)> = cached.iter().filter(|(e, _)| !e.is_empty()).map(|(e, _)| ("If-None-Match", e.clone())).collect(); + let hosts = |v: &Value| v.get("hosts").cloned().unwrap_or_else(|| Value::Array(vec![])); + let entry = match call(&relay, &inm) { + Ok((304, _, _)) if cached.is_some() => Ok(cached.as_ref().unwrap().1.clone()), + Ok((c, etag, raw)) => { + let v = json_ok(c, &raw).map(Arc::new); + let mut cache = cache.lock().unwrap(); + match &v { + Ok(v) => { + cache.insert(relay.clone(), (etag.unwrap_or_default(), v.clone())); + } + // The relay answered no (off, membership gone): its old data is not shown any more. + Err(_) if status_drops_cache(c, &raw) => { + cache.remove(&relay); + } + // A passing failure (5xx, 429, 408, a garbled answer): handled as not reached below. + Err(_) => {} + } + v + } + Err(e) => Err(e), + }; + // Not reached, or a passing failure (cache kept above): its last answer stays in the list, + // with the error beside it. + if let (Err(e), Some((_, v))) = (&entry, &cached) { + if cache.lock().unwrap().contains_key(&relay) { + first_err.get_or_insert_with(|| e.clone()); + out.push(serde_json::json!({ "relay": relay, "hosts": hosts(v), "error": e })); + all_failed = false; + continue; + } + } + out.push(match entry { + Ok(v) => { + all_failed = false; + serde_json::json!({ "relay": relay, "hosts": hosts(&v) }) + } + Err(e) => { + first_err.get_or_insert_with(|| e.clone()); + serde_json::json!({ "relay": relay, "error": e }) + } + }); + } + match first_err { + Some(e) if all_failed => Err(e), + _ if out.is_empty() => Err("offline: no server compiled into this build".into()), + _ => Ok(Value::Array(out)), + } +} + +/// One host's last report and history from `relay` (one of this build's relays). +pub fn status_host(relay: &str, uuid: &str) -> R { + if !tether_trust::status::valid_uuid(uuid) { + return Err("invalid host id".into()); + } + // The webview names the relay: signed requests go only to this build's own relays. + if !crate::policy::relay_bases().iter().any(|(h, _)| h == relay) { + return Err("unknown server".into()); + } + let (c, _, b) = call_via(Some(&[relay.to_owned()]), "GET", &format!("/api/team/status/{uuid}"), None, &[], REPORT_MAX)?; + json_ok(c, &b) +} + +/// Changes one health device on every relay of this build: pins (and so links) are kept per relay, +/// and the host list shows the newest summary of any of them. A relay that does not know the device +/// (404) is skipped. Err names each relay that refused or could not be reached. +fn status_change(method: &str, uuid: &str, suffix: &str, body: Option<&[u8]>) -> R<()> { + if !tether_trust::status::valid_uuid(uuid) { + return Err("invalid host id".into()); + } + let (mut done, mut errs) = (false, Vec::new()); + for (relay, _) in crate::policy::relay_bases() { + match call_via(Some(std::slice::from_ref(&relay)), method, &format!("/api/team/status/{uuid}{suffix}"), body, &[], 4096) { + Ok((c, _, _)) if (200..300).contains(&c) => done = true, + Ok((404, _, _)) => {} + Ok((c, _, b)) => errs.push(format!("{relay}: {}", status_error(c, &String::from_utf8_lossy(&b)))), + Err(e) => errs.push(format!("{relay}: {e}")), + } + } + match (done, errs.is_empty()) { + (_, false) => Err(errs.join(" · ")), + (false, true) => Err("No server knows this agent any more.".into()), + (true, true) => Ok(()), + } +} + +/// Confirms an agent's claim to `tether_id` (a member with write; the relay checks the claim). +pub fn status_link(uuid: &str, tether_id: &str) -> R<()> { + if !tether_trust::status::valid_uuid(uuid) { + return Err("invalid host id".into()); + } + if !tether_trust::status::valid_tether_id(tether_id) || tether_id.starts_with("m:") { + return Err("invalid Tether ID".into()); + } + let body = serde_json::json!({ "tether_id": tether_id }).to_string(); + status_change("POST", uuid, "/link", Some(body.as_bytes())) +} + +/// Removes an agent's link or claim. +pub fn status_unlink(uuid: &str) -> R<()> { + status_change("DELETE", uuid, "/link", None) +} + +/// After an Unlink: lets the agent claim a Tether ID again (still only a claim). +pub fn status_allow_claim(uuid: &str) -> R<()> { + status_change("POST", uuid, "/allow-claim", None) +} + +/// Removes an agent from health monitoring: pin, link or claim, and its stored reports. +pub fn status_remove(uuid: &str) -> R<()> { + status_change("DELETE", uuid, "", None) +} + +/// The cached summary entries linked to a Tether ID, one per device (its newest over all relays, +/// with `relay`); no request. Two or more: a link conflict, for which no device's health is shown. +pub fn status_find(tether_id: &str) -> Vec { + find_in(&STATUS_CACHE.lock().unwrap(), tether_id) +} + +fn find_in(cache: &BTreeMap)>, tether_id: &str) -> Vec { + let seen = |x: &Value| x.get("last_seen").and_then(Value::as_u64).unwrap_or(0); + let mut by: BTreeMap = BTreeMap::new(); + for (relay, (_, v)) in cache { + for h in v.get("hosts").and_then(Value::as_array).into_iter().flatten() { + if h.get("tether_id").and_then(Value::as_str) != Some(tether_id) { + continue; + } + let uuid = h.get("uuid").and_then(Value::as_str).unwrap_or_default().to_owned(); + // On a tie the first relay in name order, as the host list (health.ts mergeStatus). + if by.get(&uuid).is_none_or(|b| seen(h) > seen(b)) { + let mut h = h.clone(); + h["relay"] = Value::from(relay.as_str()); + by.insert(uuid, h); + } + } + } + by.into_values().collect() +} + #[cfg(test)] mod tests { use super::*; @@ -236,4 +416,82 @@ mod tests { assert!(status_error(404, "").starts_with("unsupported:")); assert!(status_error(500, &"x".repeat(1000)).len() < 260); } + + #[test] + fn link_inputs_are_checked_before_any_request() { + for uuid in ["bad uuid!", "short", "../../api/admin/status"] { + assert_eq!(status_link(uuid, "123456789").unwrap_err(), "invalid host id"); + assert_eq!(status_unlink(uuid).unwrap_err(), "invalid host id"); + assert_eq!(status_remove(uuid).unwrap_err(), "invalid host id"); + assert_eq!(status_allow_claim(uuid).unwrap_err(), "invalid host id"); + } + for id in ["", "a b", "m:dev-0001", &"1".repeat(33)] { + assert_eq!(status_link("dev-0001", id).unwrap_err(), "invalid Tether ID", "{id:?}"); + } + } + + fn cache_of(entries: &[(&str, Value)]) -> BTreeMap)> { + entries.iter().map(|(r, v)| (r.to_string(), (String::new(), Arc::new(v.clone())))).collect() + } + + #[test] + fn a_session_finds_every_device_linked_to_its_peer() { + let h = |uuid: &str, id: &str, seen: u64| serde_json::json!({"uuid": uuid, "tether_id": id, "last_seen": seen}); + // One device on two relays: its newest entry, with the relay it came from. + let c = cache_of(&[("a", serde_json::json!({"hosts": [h("u1", "111", 5), h("u9", "999", 1)]})), ("b", serde_json::json!({"hosts": [h("u1", "111", 7)]}))]); + let found = find_in(&c, "111"); + assert_eq!((found.len(), &found[0]["relay"], &found[0]["last_seen"]), (1, &Value::from("b"), &Value::from(7))); + // Two devices linked to one ID on different relays: both (a conflict, no health shown). + let c = cache_of(&[("a", serde_json::json!({"hosts": [h("u1", "111", 5)]})), ("b", serde_json::json!({"hosts": [h("u2", "111", 9)]}))]); + assert_eq!(find_in(&c, "111").iter().map(|x| x["uuid"].as_str().unwrap()).collect::>(), ["u1", "u2"]); + assert!(find_in(&c, "222").is_empty()); + } + + #[test] + fn the_summary_cache_reuses_its_etag_and_is_dropped_only_on_a_real_no() { + let relays = vec!["a".to_owned()]; + let cache = Mutex::new(BTreeMap::new()); + let body = br#"{"built":1,"hosts":[{"uuid":"u1","tether_id":"111"}]}"#.to_vec(); + let sent = Mutex::new(Vec::new()); + let ask = |answer: Result<(u16, Option, Vec), String>| { + status_with(&relays, &cache, |relay, h| { + assert_eq!(relay, "a"); + sent.lock().unwrap().push(h.iter().find(|(n, _)| *n == "If-None-Match").map(|(_, v)| v.clone())); + answer.clone() + }) + }; + let hosts = |v: &Value| v[0]["hosts"][0]["uuid"].clone(); + let r = ask(Ok((200, Some("\"e1\"".into()), body.clone()))).unwrap(); + assert_eq!((hosts(&r), r[0].get("error")), (Value::from("u1"), None)); + // Unchanged: a 304 to the tag sent, the cached hosts. + let r = ask(Ok((304, Some("\"e1\"".into()), vec![]))).unwrap(); + assert_eq!((hosts(&r), sent.lock().unwrap().last().cloned().flatten()), (Value::from("u1"), Some("\"e1\"".to_owned()))); + // Passing failures keep the cache: the hosts stay, with the error beside them. + for a in [Ok((500, None, b"oops".to_vec())), Ok((503, None, b"busy".to_vec())), Ok((429, None, vec![])), Ok((408, None, vec![])), Err("offline: timed out".to_owned())] { + let r = ask(a.clone()).unwrap(); + assert_eq!(hosts(&r), Value::from("u1"), "{a:?}"); + assert!(r[0]["error"].is_string(), "{a:?}"); + } + assert_eq!(sent.lock().unwrap().last().cloned().flatten(), Some("\"e1\"".to_owned()), "the tag is still sent"); + // A real no (membership gone, no health support, reporting off): the cache goes. + for a in [(401, b"unknown member".to_vec()), (403, vec![]), (404, vec![]), (503, b"status reporting is off".to_vec())] { + ask(Ok((200, Some("\"e2\"".into()), body.clone()))).unwrap(); + assert!(ask(Ok((a.0, None, a.1.clone()))).is_err(), "{a:?}"); + assert!(cache.lock().unwrap().is_empty(), "{a:?}"); + assert!(ask(Ok((500, None, vec![]))).is_err(), "nothing cached to show: {a:?}"); + assert_eq!(sent.lock().unwrap().last().cloned().flatten(), None, "no tag after a drop: {a:?}"); + } + } + + #[test] + fn status_errors_are_classified() { + assert!(status_error(503, "status reporting is off").starts_with("off:")); + assert!(!status_error(503, "busy").starts_with("off:")); + for (code, body) in [(401, "unknown member"), (403, "x"), (404, "not found"), (503, "status reporting is off")] { + assert!(status_drops_cache(code, body.as_bytes()), "{code} {body}"); + } + for (code, body) in [(500, "oops"), (502, ""), (503, "busy"), (429, "too many requests"), (408, ""), (200, "not json")] { + assert!(!status_drops_cache(code, body.as_bytes()), "{code} {body}"); + } + } } diff --git a/apps/desktop/src-tauri/windows/hooks.nsh b/apps/desktop/src-tauri/windows/hooks.nsh index 5f45cb2..21c835d 100644 --- a/apps/desktop/src-tauri/windows/hooks.nsh +++ b/apps/desktop/src-tauri/windows/hooks.nsh @@ -15,8 +15,8 @@ Var TetherRelaunch ; children), then every other tether.exe from this folder (main window, tray, session viewers), ; waiting until none is left. Prints 1 if a main window/tray process (no arguments) was running. !macro TETHER_STOP_ALL - nsExec::Exec '${TETHER_SC} stop Tether' - nsExec::ExecToStack `${TETHER_POWERSHELL} -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$$exe = '$INSTDIR\tether.exe'; $$s = Get-Service Tether -ErrorAction SilentlyContinue; if ($$s -and $$s.Status -ne 'Stopped') { try { $$s.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(20)) } catch {} }; $$ui = 0; for ($$i = 0; $$i -lt 50; $$i++) { $$p = @(Get-CimInstance Win32_Process -Filter 'Name=''tether.exe''' | Where-Object { $$_.ExecutablePath -eq $$exe }); if ($$p.Count -eq 0) { break }; foreach ($$x in $$p) { if ($$x.CommandLine -match '\.exe.?\s*$$') { $$ui = 1 }; Stop-Process -Id $$x.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 200 }; Write-Output $$ui"` + nsExec::Exec '${TETHER_SC} stop ${PRODUCTNAME}' + nsExec::ExecToStack `${TETHER_POWERSHELL} -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "$$exe = '$INSTDIR\${MAINBINARYNAME}.exe'; $$s = Get-Service ${PRODUCTNAME} -ErrorAction SilentlyContinue; if ($$s -and $$s.Status -ne 'Stopped') { try { $$s.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(20)) } catch {} }; $$ui = 0; for ($$i = 0; $$i -lt 50; $$i++) { $$p = @(Get-CimInstance Win32_Process -Filter 'Name=''${MAINBINARYNAME}.exe''' | Where-Object { $$_.ExecutablePath -eq $$exe }); if ($$p.Count -eq 0) { break }; foreach ($$x in $$p) { if ($$x.CommandLine -match '\.exe.?\s*$$') { $$ui = 1 }; Stop-Process -Id $$x.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Milliseconds 200 }; Write-Output $$ui"` Pop $0 Pop $1 ; Runs before the old uninstaller and again in PREINSTALL: only ever raise the relaunch flag. @@ -32,17 +32,17 @@ Var TetherRelaunch !macroend !macro NSIS_HOOK_POSTINSTALL - nsExec::ExecToStack '${TETHER_SC} query Tether' + nsExec::ExecToStack '${TETHER_SC} query ${PRODUCTNAME}' Pop $0 Pop $1 StrCmp $0 "0" 0 +2 - nsExec::Exec '${TETHER_SC} start Tether' + nsExec::Exec '${TETHER_SC} start ${PRODUCTNAME}' ; Direct LAN connections (policy network.direct): Tether listens on TCP 21118 and answers the ; LAN lookup on UDP 21119, from the local subnet only. The app listens only while this rule ; exists (netpolicy.rs), so it never raises a firewall prompt. Replaces older versions' rules. - nsExec::Exec '${TETHER_NETSH} advfirewall firewall delete rule name="Tether"' - nsExec::Exec '${TETHER_NETSH} advfirewall firewall add rule name="Tether" dir=in action=allow program="$INSTDIR\${MAINBINARYNAME}.exe" protocol=TCP localport=21118 remoteip=localsubnet profile=any enable=yes' - nsExec::Exec '${TETHER_NETSH} advfirewall firewall add rule name="Tether" dir=in action=allow program="$INSTDIR\${MAINBINARYNAME}.exe" protocol=UDP localport=21119 remoteip=localsubnet profile=any enable=yes' + nsExec::Exec '${TETHER_NETSH} advfirewall firewall delete rule name="${PRODUCTNAME}"' + nsExec::Exec '${TETHER_NETSH} advfirewall firewall add rule name="${PRODUCTNAME}" dir=in action=allow program="$INSTDIR\${MAINBINARYNAME}.exe" protocol=TCP localport=21118 remoteip=localsubnet profile=any enable=yes' + nsExec::Exec '${TETHER_NETSH} advfirewall firewall add rule name="${PRODUCTNAME}" dir=in action=allow program="$INSTDIR\${MAINBINARYNAME}.exe" protocol=UDP localport=21119 remoteip=localsubnet profile=any enable=yes' ; Reopen Tether for the signed-in user (unelevated, like "Run Tether" on the finish page) if we ; closed it. With /R (in-app update) the bundler restarts it itself. ${If} $TetherRelaunch == "1" @@ -56,12 +56,12 @@ Var TetherRelaunch !macro NSIS_HOOK_PREUNINSTALL ; Stop and remove the background service, only if unattended access was installed. - nsExec::ExecToStack '${TETHER_SC} query Tether' + nsExec::ExecToStack '${TETHER_SC} query ${PRODUCTNAME}' Pop $0 Pop $1 StrCmp $0 "0" 0 +2 - nsExec::Exec '"$INSTDIR\tether.exe" --uninstall-service' - nsExec::Exec '${TETHER_NETSH} advfirewall firewall delete rule name="Tether"' + nsExec::Exec '"$INSTDIR\${MAINBINARYNAME}.exe" --uninstall-service' + nsExec::Exec '${TETHER_NETSH} advfirewall firewall delete rule name="${PRODUCTNAME}"' !insertmacro TETHER_STOP_ALL !macroend @@ -71,13 +71,13 @@ Var TetherRelaunch ; bundler removes, and the service keeps a copy in the LocalService profile. ${If} $DeleteAppDataCheckboxState = 1 ${AndIf} $UpdateMode <> 1 - RmDir /r "$WINDIR\ServiceProfiles\LocalService\AppData\Roaming\Tether" + RmDir /r "$WINDIR\ServiceProfiles\LocalService\AppData\Roaming\${PRODUCTNAME}" ; The elevated uninstaller's profile (the admin who confirmed UAC) ... SetShellVarContext current - RmDir /r "$APPDATA\Tether" + RmDir /r "$APPDATA\${PRODUCTNAME}" ; ... and the signed-in user's, as that user (RunAsUser: unelevated, %APPDATA% is theirs). ; shortcut: other users' profiles on this PC keep their %APPDATA%\Tether; walk ; HKLM\...\ProfileList when shared PCs must be wiped by one uninstall. - nsis_tauri_utils::RunAsUser "$SYSDIR\cmd.exe" '/c rd /s /q "%APPDATA%\Tether"' + nsis_tauri_utils::RunAsUser "$SYSDIR\cmd.exe" '/c rd /s /q "%APPDATA%\${PRODUCTNAME}"' ${EndIf} !macroend diff --git a/apps/desktop/src/components/hosts/Detail.tsx b/apps/desktop/src/components/hosts/Detail.tsx index 255be52..f07e49f 100644 --- a/apps/desktop/src/components/hosts/Detail.tsx +++ b/apps/desktop/src/components/hosts/Detail.tsx @@ -3,10 +3,12 @@ import { useEffect, useRef, useState } from "react"; import { ArrowRight, Copy, Eye, FolderSync, History, Pin, PinOff, Trash2 } from "lucide-react"; import { Button, IconButton, PlatformIcon } from "../ui"; import { formatId, invoke } from "../../lib/ipc"; -import { label, osFamily, type Host, type Store } from "../../lib/hosts/model"; +import { label, osFamily, type Host, type StatusSummary, type Store } from "../../lib/hosts/model"; import { actions, useHosts, useReadOnly } from "../../lib/hosts/store"; import { errorText } from "../../lib/policy"; +import { uiLang } from "../../lib/hosts/health"; import { ago, OnlineDot, TagChip, TagInput } from "./bits"; +import { HealthSection, useStatusHost } from "./Health"; interface AuditRow { ts: number; @@ -27,6 +29,8 @@ export function Detail({ onConnect, onToast, onRemove, + nameOf, + holderOf, }: { h: Host; meta: Store["tags"]; @@ -35,14 +39,19 @@ export function Detail({ onConnect: (id: string, kind: "default" | "file-transfer" | "view-only") => void; onToast: (m: string) => void; onRemove: (ids: string[]) => void; + /** A host row's name by its ID (the host an agent claims to be). */ + nameOf?: (id: string) => string | undefined; + /** The health summary already joined to a host row (a claim to it cannot be linked). */ + holderOf?: (id: string) => StatusSummary | "conflict" | undefined; }) { - const entry = useHosts((s) => s.store.hosts[h.id]); + const entry = useHosts((s) => (Object.hasOwn(s.store.hosts, h.id) ? s.store.hosts[h.id] : undefined)); const me = useHosts((s) => s.team.me); const teamOn = useHosts((s) => !!s.store.team?.enabled); const [name, setName] = useState(h.name); const [notes, setNotes] = useState(h.notes); const [audit, setAudit] = useState(null); const ro = useReadOnly(); + const report = useStatusHost(h); // Mounted per host (key = id). What was typed and is not saved yet: saved on blur, and on unmount, // because clicking another row removes this panel before the field loses the focus. const edit = useRef<{ name?: string; notes?: string }>({}); @@ -85,24 +94,43 @@ export function Detail({ - actions.setPinned([h.id], !h.pinned)}> - {h.pinned ? : } - + {!h.agentOnly && ( + actions.setPinned([h.id], !h.pinned)}> + {h.pinned ? : } + + )} -
- - - -
-
Enter connects · Shift+Enter files · Alt+Enter view only
+ {h.agentOnly ? ( +
+ {h.conflict + ? `In conflict with another agent for host ${nameOf?.(h.status?.tether_id ?? "") || h.status?.tether_id || ""}.` + : h.status?.claimed_id + ? "This agent is not linked to a host yet. Its health is reported by the monitor agent." + : h.status?.no_claim || (typeof report === "object" && report?.no_claim) + ? "Link dismissed. This agent is not linked to a host." + : "No remote access: Tether is not installed on this machine. Its health is reported by the monitor agent."} +
+ ) : ( + <> +
+ + + +
+
Enter connects · Shift+Enter files · Alt+Enter view only
+ + )} + {/* An agent-only row is not a host of the list: no name, tags, notes or pin (never stored or shared). */} + {!h.agentOnly && ( + <> @@ -136,7 +164,18 @@ export function Detail({ actions.addTags([h.id], [t])} placeholder="Add tag (site:berlin)" /> )} + + )} + {h.conflict && !h.status && ( +
+ Health link conflict: two devices are linked to this host on different relays, so no health is shown here. Open the rows of the two agents (search id:m:) and unlink or remove the one that is not this computer. +
+ )} + {h.status && } + + {!h.agentOnly && ( + <> @@ -153,6 +192,8 @@ export function Detail({ }} className="mt-1 resize-none rounded-xl border border-hairline bg-parchment px-3 py-2 text-caption outline-none placeholder:text-faint focus-visible:border-focus" /> + + )}
{( @@ -189,7 +230,7 @@ export function Detail({ ))} - {teamOn && me?.audit && ( + {teamOn && me?.audit && !h.agentOnly && (
{audit === null ? (
)} -
- -
+ {!h.agentOnly && ( +
+ +
+ )} ); } diff --git a/apps/desktop/src/components/hosts/Dialogs.tsx b/apps/desktop/src/components/hosts/Dialogs.tsx index fd95294..fc5f5e6 100644 --- a/apps/desktop/src/components/hosts/Dialogs.tsx +++ b/apps/desktop/src/components/hosts/Dialogs.tsx @@ -4,7 +4,7 @@ import { Copy, Keyboard, Lock, Plus, Power, RefreshCw, Trash2, Users } from "luc import { Button, IconButton, Modal, Segmented, TextField, Toggle } from "../ui"; import { formatId, inTauri, invoke } from "../../lib/ipc"; import { label, newId, normTag, TAG_COLORS, tagColor, type Host, type Store, type TagColor } from "../../lib/hosts/model"; -import { exportCsv, exportJson, mergeImport, parseImport, type Imported } from "../../lib/hosts/io"; +import { exportCsv, exportFaultsCsv, exportJson, mergeImport, parseImport, type Imported } from "../../lib/hosts/io"; import { parse, search } from "../../lib/hosts/query"; import { actions, teamSync, useHosts, useReadOnly } from "../../lib/hosts/store"; import { errorText } from "../../lib/policy"; @@ -108,8 +108,9 @@ export function Rules({ hosts, store, onClose }: { hosts: Host[]; store: Store; const [tag, setTag] = useState(""); const [when, setWhen] = useState(""); const ro = useReadOnly(); - const p = useMemo(() => parse(when), [when]); - const n = useMemo(() => (p.node ? search(hosts, p).length : 0), [hosts, p]); + // As a rule reads it: health terms are plain words there (older desktops of the team read them so). + const p = useMemo(() => parse(when, true), [when]); + const n = useMemo(() => (p.node ? search(hosts, p, undefined, true).length : 0), [hosts, p]); const add = () => { const t = normTag(tag); if (!t || !p.node) return; @@ -160,6 +161,7 @@ export function Rules({ hosts, store, onClose }: { hosts: Host[]; store: Store; Add rule +
Health terms (health:, product:, role: …) are not available in rules: there they are plain words. Use them in the search box or a saved search.
+ ); +} + +function Check({ c, lang, hint = true }: { c: ReportCheck; lang: Lang; hint?: boolean }) { + const title = clip(pick(c.title, lang), 120) || clip(c.id, 64); + const value = clip(typeof c.value === "string" ? c.value : "", 80); + const since = c.state !== "ok" ? when(c.since) : ""; + const h = hint ? clip(pick(c.hint, lang), 600) : ""; + return ( +
  • + + + +
    +
    {title}
    + {(value || since) && ( +
    + {value} + {value && since ? " · " : ""} + {since && `since ${since}`} +
    + )} + {h &&
    {h}
    } +
    +
  • + ); +} + +const day = (t: number | null | undefined) => (t ? new Date(t * 1000).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }) : ""); + +type Ask = "link" | "unlink" | "remove"; + +/** Who this agent is linked to, and the team actions on it: confirm a claim (link), unlink, remove. + * Nothing links by itself: a member with write decides, after one explicit confirmation. */ +function LinkPart({ h, rep, nameOf, holderOf, ask, setAsk }: { h: Host; rep: StatusHostReply | null; nameOf?: (id: string) => string | undefined; holderOf?: (id: string) => StatusSummary | "conflict" | undefined; ask: Ask | null; setAsk: (a: Ask | null) => void }) { + const write = useHosts((s) => !!s.team.me?.write); + const [busy, setBusy] = useState(false); + const [err, setErr] = useState(""); + const claimed = h.agentOnly ? h.status?.claimed_id : null; + const st = linkState(h, rep, write, claimed ? holderOf?.(claimed) : undefined); + const s = h.status!; + const agentHost = clip(s.host, 64); + const claimName = st.claim ? clip(nameOf?.(st.claim), 64) : ""; + // A device names itself: a host name other than the claimed host's is worth a second look. + const differs = !!claimName && claimName.toLowerCase() !== agentHost.toLowerCase(); + const close = () => (setAsk(null), setErr("")); + const run = (cmd: string, args: Record) => { + setBusy(true); + setErr(""); + invoke(cmd, args).then( + () => (setBusy(false), close(), void actions.teamRefresh()), + (e) => (setBusy(false), setErr(errorText(e))), + ); + }; + const what: Record void }> = { + link: { + title: `Link this agent to ${clip(st.claim ?? "", 32)}?`, + text: `Health reports from ${agentHost} (enrolled ${day(rep?.enrolled) || "at an unknown time"}) will show on ${claimName || clip(st.claim ?? "", 32)}. The agent's claim is not proof: confirm only if this is that computer.`, + warn: differs ? `The agent calls its computer “${agentHost}”, but this host is “${claimName}”. Check that they are the same computer.` : undefined, + button: "Link", + go: () => run("team_status_link", { uuid: s.uuid, tetherId: st.claim }), + }, + unlink: { + title: `Unlink health from ${clip(label(h), 64)}?`, + text: "The link and the agent's claim are removed. The agent keeps reporting, as a host of its own, and cannot claim a Tether ID again until a team member allows a new claim.", + button: "Unlink", + go: () => run("team_status_unlink", { uuid: s.uuid }), + }, + remove: { + title: `Remove ${clip(label(h), 64)} from health monitoring?`, + text: "Its enrolment, link and stored reports are deleted on every server. If the agent on that computer still holds a valid enrolment token it enrols again by itself, and comes back as an agent that is not linked to any host. Uninstall the agent there, or ask an admin to revoke the token.", + button: "Remove", + go: () => run("team_status_remove", { uuid: s.uuid }), + }, + }; + return ( + <> + {st.claim && ( +
    +
    + Claims to be {clip(st.claim, 32)} + {claimName && ` (${claimName})`}. Confirm only if this is that computer. +
    +
    + Agent's host name {agentHost} + {rep?.enrolled ? ` · enrolled ${day(rep.enrolled)}` : ""} +
    + + {st.link === "disabled" &&
    Only team members who may edit shared tags can link an agent.
    } + {st.blocked && "conflict" in st.blocked && ( +
    This host is in a link conflict: two agents are linked to it on different relays. Resolve that first (unlink or remove the one that is not this computer).
    + )} + {st.blocked && !("conflict" in st.blocked) && ( +
    + This host already has a linked health agent ({clip(st.blocked.host, 64)} + {st.blocked.at ? `, linked ${day(st.blocked.at)}` : ""}). Unlink that one first if this is its replacement. +
    + )} +
    + )} + {st.conflict && st.linked && ( +
    + Link conflict: this agent and another device are both linked to {clip(h.status?.tether_id ?? "", 32)} on different relays, so neither is shown on that host. Unlink or remove the one that is not that computer. +
    + )} + {st.dismissed && ( +
    +
    Link dismissed: this agent claims no host until a team member allows it again.
    + {st.allow && ( + + )} +
    + )} + {!ask && err && ( +

    + {clip(err, 300)} +

    + )} + {st.linked && rep && ( +
    + + {st.conflict + ? `Linked to ${clip(h.status?.tether_id ?? "", 32)} on its relay${st.linked.at ? `, ${day(st.linked.at)}` : ""}` + : st.linked.by + ? `Health linked by ${clip(st.linked.by, 64)}, ${day(st.linked.at)}` + : `Health linked by the enrolment token issued for this host${st.linked.at ? `, ${day(st.linked.at)}` : ""}`} + + {st.unlink && ( + + )} +
    + )} + {ask && ( + +

    {what[ask].title}

    +

    {what[ask].text}

    + {what[ask].warn && ( +

    + {what[ask].warn} +

    + )} + {err && ( +

    + {clip(err, 300)} +

    + )} +
    + + +
    +
    + )} + + ); +} + +export function HealthSection({ h, reply, lang, nameOf, holderOf }: { h: Host; reply: StatusHostReply | string | null; lang: Lang; nameOf?: (id: string) => string | undefined; holderOf?: (id: string) => StatusSummary | "conflict" | undefined }) { + const [open, setOpen] = useState>({}); + const [filter, setFilter] = useState(""); + const [copied, setCopied] = useState(false); + const [ask, setAsk] = useState(null); + const write = useHosts((st) => !!st.team.me?.write); + const flip = (k: string) => setOpen((o) => ({ ...o, [k]: !o[k] })); + const checks = useMemo(() => checksOf(reply), [reply]); + const view = useMemo(() => groupChecks(checks), [checks]); + const rep = typeof reply === "object" && reply ? reply : null; + const s = h.status; + const now = Date.now() / 1000; + const raw = useMemo(() => (open.raw && rep?.report ? JSON.stringify(rep.report, null, 2) : ""), [open.raw, rep]); + const history = useMemo(() => { + const from = Date.now() / 1000 - 90 * 86400; + const f = filter.trim().toLowerCase(); + const list = Array.isArray(rep?.history) ? rep.history : []; + // Oldest first from the relay: shown newest first. + return list + .filter((x) => { + const t = x && typeof x.id === "string" ? (x.at ?? Date.parse(x.time) / 1000) : -Infinity; + return (Number.isNaN(t) || t >= from) && (!f || x.id.toLowerCase().includes(f)); + }) + .reverse(); + }, [rep, filter]); + if (!s) return null; + const titleOf = new Map(checks.map((c) => [c.id, clip(pick(c.title, lang), 120)])); + + return ( +
    +
    + Health + + reported {ago(s.last_seen, now)}, agent {clip(s.agent, 32)} + +
    + {s.customer &&
    Customer {clip(s.customer, 32)}
    } +
    + + {healthText(h, now)} +
    + + + {reply === null &&
    Loading report…
    } + {typeof reply === "string" &&
    {clip(reply, 300)}
    } + {rep && !rep.report &&
    No full report yet.
    } + {rep?.report && checks.length === 0 &&
    This report lists no checks.
    } + + {view.faults.map((g) => ( +
    +
    + {clip(g.name, 80)} +
    +
      + {g.checks.map((c) => ( + + ))} +
    +
    + ))} + + {view.setup.length > 0 && ( +
    +
    Setup
    +
      + {view.setup.map((c) => ( + + ))} +
    +
    + )} + {view.unknown.length > 0 && ( +
    + flip("unknown")} /> + {open.unknown && ( +
      + {view.unknown.map((c) => ( + + ))} +
    + )} +
    + )} + + {view.passed.length > 0 && ( +
    +
    Passed
    + {view.passed.map((g) => ( +
    + flip(`g:${g.name}`)} + extra={} + /> + {open[`g:${g.name}`] && ( +
      + {g.checks.map((c) => ( + + ))} +
    + )} +
    + ))} +
    + )} + + {rep && ( +
    + flip("history")} /> + {open.history && ( +
    + setFilter(e.target.value.slice(0, 64))} + onKeyDown={(e) => e.stopPropagation()} + placeholder="Filter by check" + aria-label="Filter history by check" + spellCheck={false} + className="mt-1 h-8 w-full rounded-xl border border-hairline bg-parchment px-3 font-mono text-footnote text-ink outline-none placeholder:font-sans placeholder:text-faint focus-visible:border-focus" + /> + {history.length === 0 &&
    No changes{filter ? " for this check" : ""}.
    } +
      + {history.slice(0, 500).map((x, i) => ( +
    • +
      + + {titleOf.get(x.id) || clip(x.id, 64)} + + {when(x.time)} +
      +
      + {WORD[x.from] ?? clip(String(x.from), 16)} → {WORD[x.to] ?? clip(String(x.to), 16)} +
      +
    • + ))} +
    +
    + )} + flip("all")} /> + {open.all && ( +
      + {checks.map((c) => ( + + ))} +
    + )} + flip("raw")} /> + {open.raw && ( +
    + {rep.report ? ( + <> +
    +                    {raw}
    +                  
    + + navigator.clipboard.writeText(raw).then( + () => (setCopied(true), setTimeout(() => setCopied(false), 1500)), + () => {}, + ) + } + > + + + + ) : ( +
    No full report yet.
    + )} +
    + )} +
    + )} + {linkState(h, rep, write).remove && ( + + )} +
    + ); +} diff --git a/apps/desktop/src/components/hosts/HostTable.test.ts b/apps/desktop/src/components/hosts/HostTable.test.ts new file mode 100644 index 0000000..00cdc9d --- /dev/null +++ b/apps/desktop/src/components/hosts/HostTable.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; +import { buildHosts, emptyStore, type StatusSummary } from "../../lib/hosts/model"; +import { sortHosts } from "./HostTable"; + +const NOW = 1_800_000_000; +const sum = (uuid: string, tether_id: string, p: Partial): StatusSummary => ({ + uuid, + tether_id, + host: tether_id, + agent: "0.1.0", + overall: "ok", + counts: { ok: 3, warn: 0, crit: 0, unknown: 0, setup: 0 }, + products: [], + faults: [], + last_seen: NOW, + next: 300, + stale: false, + relay: "r", + ...p, +}); + +describe("sortHosts", () => { + const rows = buildHosts(emptyStore(), [{ id: "444444444", hostname: "NONE", username: "", platform: "", last: NOW }], [], null, NOW, [ + sum("a", "111111111", { overall: "warn", counts: { ok: 1, warn: 2, crit: 0, unknown: 0, setup: 0 }, products: [{ name: "Imaging", version: "3.1" }], agent: "0.1.10", customer: "4711" }), + sum("b", "222222222", { overall: "crit", counts: { ok: 1, warn: 0, crit: 1, unknown: 0, setup: 0 }, products: [{ name: "Records", version: "26.3" }], agent: "0.1.2", customer: "0815" }), + sum("c", "333333333", { stale: true }), + ]); + const ids = (key: "health" | "products" | "agent" | "customer", desc = false) => sortHosts(rows, { key, desc }).map((h) => h.id); + it("health: worst first ascending", () => { + expect(ids("health")).toEqual(["222222222", "333333333", "111111111", "444444444"]); + expect(ids("health", true)).toEqual(["444444444", "111111111", "333333333", "222222222"]); + }); + it("products and agent: rows without a value last; agent versions numerically", () => { + expect(ids("products")).toEqual(["111111111", "222222222", "444444444", "333333333"]); + expect(ids("agent")).toEqual(["333333333", "222222222", "111111111", "444444444"]); + }); + it("customer: rows without one last", () => { + // 333333333 has a status without a customer, 444444444 has no status: both go last, in list order. + expect(ids("customer")).toEqual(["222222222", "111111111", "444444444", "333333333"]); + expect(ids("customer", true).slice(2)).toEqual(["111111111", "222222222"]); // descending is the exact reverse, as for the other columns + }); +}); diff --git a/apps/desktop/src/components/hosts/HostTable.tsx b/apps/desktop/src/components/hosts/HostTable.tsx index a54a816..623572c 100644 --- a/apps/desktop/src/components/hosts/HostTable.tsx +++ b/apps/desktop/src/components/hosts/HostTable.tsx @@ -5,12 +5,13 @@ import { ArrowDown, ArrowUp, Pin } from "lucide-react"; import { PlatformIcon } from "../ui"; import { formatId } from "../../lib/ipc"; import { label, osFamily, type Host, type Store } from "../../lib/hosts/model"; -import { ago, OnlineDot, TagChip } from "./bits"; +import { healthRank, healthText } from "../../lib/hosts/health"; +import { ago, HealthDot, OnlineDot, TagChip } from "./bits"; export const ROW = 36; const OVERSCAN = 8; -export type SortKey = "smart" | "name" | "id" | "os" | "version" | "last"; +export type SortKey = "smart" | "name" | "id" | "os" | "version" | "last" | "health" | "products" | "agent" | "customer"; export interface Sort { key: SortKey; desc: boolean; @@ -21,18 +22,45 @@ export interface Sort { const COLS = "grid-cols-[32px_16px_minmax(120px,1fr)_112px] @min-[600px]:grid-cols-[32px_16px_minmax(150px,1.3fr)_112px_minmax(120px,1.7fr)] @min-[900px]:grid-cols-[32px_16px_minmax(170px,1.3fr)_112px_minmax(150px,1.7fr)_128px_72px_96px]"; const WIDE = "hidden @min-[900px]:block"; +// With health data (deviations: no column chooser): Health from the start (icon only while narrow), +// OS/version/last active from 1050px, Products, Agent and Customer from 1300px. +const HCOLS = + "grid-cols-[32px_16px_minmax(120px,1fr)_112px_16px] @min-[600px]:grid-cols-[32px_16px_minmax(130px,1.3fr)_112px_minmax(80px,1.7fr)_150px] @min-[1050px]:grid-cols-[32px_16px_minmax(170px,1.3fr)_112px_minmax(150px,1.7fr)_150px_128px_72px_96px] @min-[1300px]:grid-cols-[32px_16px_minmax(170px,1.3fr)_112px_minmax(150px,1.7fr)_150px_minmax(140px,1.2fr)_64px_88px_128px_72px_96px]"; +const HWIDE = "hidden @min-[1050px]:block"; +const XWIDE = "hidden @min-[1300px]:block"; + +const NONE = "\uffff"; // sorts after every text: rows without the value go last +const pad = (v: string) => v.split(".").map((x) => x.padStart(5, "0")).join("."); +const productText = (h: Host) => (h.status?.products ?? []).map((p) => [p.name, p.version].filter(Boolean).join(" ")).join(", "); export function sortHosts(rows: Host[], s: Sort): Host[] { if (s.key === "smart") return rows; const k = s.key; const val = (h: Host): string | number => - k === "name" ? label(h).toLowerCase() : k === "id" ? h.id : k === "os" ? `${osFamily(h.os)} ${h.os}`.toLowerCase() : k === "version" ? h.version.split(".").map((x) => x.padStart(5, "0")).join(".") : Math.max(h.last, h.seen); + k === "name" + ? label(h).toLowerCase() + : k === "id" + ? h.id + : k === "os" + ? `${osFamily(h.os)} ${h.os}`.toLowerCase() + : k === "version" + ? pad(h.version) + : // Health ascending = worst first (the first click answers "what needs me"). + k === "health" + ? -(healthRank(h.health) * 1e8 + (h.status?.counts.crit ?? 0) * 1e4 + (h.status?.counts.warn ?? 0)) + : k === "products" + ? productText(h).toLowerCase() || NONE + : k === "agent" + ? (h.status ? pad(h.status.agent) : NONE) + : k === "customer" + ? h.status?.customer?.toLowerCase() || NONE + : Math.max(h.last, h.seen); const d = s.desc ? -1 : 1; - return [...rows].sort((a, b) => { - const x = val(a); - const y = val(b); - return x < y ? -d : x > y ? d : 0; - }); + // Each row's key once, not per comparison (5,000 rows: ~60,000 comparisons). + return rows + .map((h) => ({ h, k: val(h) })) + .sort((a, b) => (a.k < b.k ? -d : a.k > b.k ? d : 0)) + .map((x) => x.h); } /** Default order without a search: pinned, online, most recently used. */ @@ -49,10 +77,12 @@ const Row = memo(function Row({ selected, meta, now, + hv, onRow, onToggle, onOpen, }: { + hv: boolean; h: Host; top: number; index: number; @@ -75,7 +105,7 @@ const Row = memo(function Row({ onMouseDown={(e) => onRow(h.id, e)} onDoubleClick={() => onOpen(h.id)} style={{ transform: `translateY(${top}px)` }} - className={`absolute inset-x-0 top-0 grid h-9 ${COLS} items-center gap-3 rounded-md px-2 text-caption ${ + className={`absolute inset-x-0 top-0 grid h-9 ${hv ? HCOLS : COLS} items-center gap-3 rounded-md px-2 text-caption ${ selected ? "bg-accent/12" : cursor ? "bg-tile-2" : "hover:bg-tile-2" } ${cursor ? "ring-1 ring-inset ring-focus/60" : ""}`} > @@ -114,13 +144,32 @@ const Row = memo(function Row({ ))} - + {hv && ( + <> + + + + {healthText(h, now)} + + + + {productText(h) || "—"} + + + {h.status?.agent || "—"} + + + {h.status?.customer || "—"} + + + )} + {h.os ? `${osFamily(h.os)} ${/\d[\d.]*/.exec(h.os)?.[0] ?? ""}`.trim() : "—"} - + {h.version || "—"} - + {ago(Math.max(h.last, h.seen), now)}
    @@ -138,7 +187,10 @@ export function HostTable({ onToggle, onToggleAll, onOpen, + health = false, }: { + /** Health data exists: the Health, Products and Agent columns are shown. */ + health?: boolean; rows: Host[]; cursor: string | null; selected: Set; @@ -183,6 +235,8 @@ export function HostTable({ const first = Math.max(0, Math.floor(top / ROW) - OVERSCAN); const last = Math.min(rows.length, Math.ceil((top + height) / ROW) + OVERSCAN); const all = rows.length > 0 && rows.every((h) => selected.has(h.id)); + const hv = health; + const wide = hv ? "hidden @min-[1050px]:flex" : "hidden @min-[900px]:flex"; const head = (k: SortKey, text: string, cls = "") => (